Documentation
¶
Overview ¶
Package models provides DynamORM data models for account features and relationship management.
Index ¶
- Constants
- Variables
- func ActivityDayKey(day string) string
- func AgentAccessLeaseTokenExpiresAt(now time.Time, lease *AgentAccessLease, idleExpiresAt time.Time) time.Time
- func AgentShareGrantGranteeGSI2PK(granteeUsername string) string
- func AgentShareGrantPK(agentUsername string) string
- func AgentShareGrantSK(granteeUsername string) string
- func CMSArticleIndexExtractArticleID(sk string) string
- func CMSArticleIndexPKForAuthor(actorID string) string
- func CMSArticleIndexPKForCategory(categoryID string) string
- func CMSArticleIndexPKForSeries(seriesID string) string
- func CMSArticleIndexSK(published time.Time, articleID string) string
- func CMSArticleSlugIndexPK(slug string) string
- func CMSArticleSlugIndexSK() string
- func CMSCategorySlugIndexPK(slug string) string
- func CMSCategorySlugIndexSK() string
- func CMSPublicationSlugIndexPK(slug string) string
- func CMSPublicationSlugIndexSK() string
- func CMSSeriesSlugIndexPK(slug string) string
- func CMSSeriesSlugIndexSK() string
- func CMSSlugIndexSK() string
- func CMSTenantArticleSlugIndexPK(tenant string, slug string) string
- func CMSTenantCategorySlugIndexPK(tenant string, slug string) string
- func CMSTenantPublicationSlugIndexPK(tenant string, slug string) string
- func CMSTenantSeriesSlugIndexPK(tenant string, slug string) string
- func CalculateCost(readUnits, writeUnits float64) (readCostMicroCents, writeCostMicroCents, totalCostMicroCents int64)
- func CalculateDynamoDBCost(readCapacityUnits, writeCapacityUnits float64) int64
- func CalculateEmailCost(_ int64) int64
- func CalculateLambdaCost(invocations int64, gbSeconds float64) int64
- func CalculatePatternAccuracy(feedbacks []*PatternFeedback) float64
- func CalculatePatternMetrics(feedbacks []*PatternFeedback) map[string]interface{}
- func CalculatePushCost(messageCount int64) int64
- func CalculateSMSCost(_ int64) int64
- func CalculateScheduledJobCosts(lambdaDurationMs int64, memoryMB int, dynamoDBReadOps, dynamoDBWriteOps int64, ...) (...)
- func CalculateWebSocketCost(messageCount int64) int64
- func CanonicalActivityPubObjectIDForStatus(status *Status, localDomain string) string
- func CanonicalConversationParticipantID(participantID string) string
- func CanonicalConversationParticipants(participants []string) []string
- func CanonicalStatusID(raw string) string
- func CanonicalStatusIDForDomain(raw string, localDomain string) string
- func ConversationHasRemoteParticipants(conversation *Conversation) bool
- func ConversationLocalParticipantIDs(conversation *Conversation) []string
- func ConversationParticipantIDsFromRefs(refs []ConversationParticipantRef) []string
- func DayFormat(t time.Time) string
- func ExtractDomain(actorID string) string
- func FormatStatsDate(t time.Time) string
- func GetCostDriverKey(category, resource string) (pk, sk string)
- func GetCostDriversByCategoryKeys(category string) (pk, skPrefix string)
- func GetCostProjectionKey(period string, timestamp time.Time) (pk, sk string)
- func GetFederationStatsKey(date string) (pk, sk string)
- func GetFederationStatsRangeKeys(startDate, endDate string) (pk, skStart, skEnd string)
- func GetHealthReportKey(domain, timestamp string) (pk, sk string)
- func GetHealthReportRangeKeys(domain string, startTime, endTime time.Time) (pk, skStart, skEnd string)
- func GetLatestHealthReportKeys(domain string) (pk, skPrefix string)
- func GetLatestProjectionKeys(period string) (pk, skPrefix string)
- func GetLinkMetadataKey(linkURL string) (pk, sk string)
- func GetPatternFeedbackKey(patternID, timestamp, feedbackID string) (pk, sk string)
- func GetPatternFeedbackKeys(patternID string) (pk, skPrefix string)
- func GetPatternFeedbackRangeKeys(patternID string, startTime, endTime time.Time) (pk, skStart, skEnd string)
- func GetProjectionRangeKeys(period string, startTime, endTime time.Time) (pk, skStart, skEnd string)
- func GetReviewerStatsKey(reviewerID string) (pk, sk string)
- func GetTimeBucket(timestamp time.Time, period string) time.Time
- func GetTrendingLinkKey(date, linkID string, score float64) (pk, sk string)
- func GetTrendingLinksByDomainKeys(date, _ string) (pk, skPrefix string)
- func GetTrendingLinksKeys(date string) (pk, skPrefix string)
- func GetTrendingStatusKey(date, statusID string, score float64) (pk, sk string)
- func GetTrendingStatusRangeKeys(date string, minScore float64) (pk, skStart, skEnd string)
- func GetTrendingStatusesKeys(date string) (pk, skPrefix string)
- func GetTrusteeConfigKey(category, username string) (pk, sk string)
- func GetTrusteeConfigsByCategoryKeys(category string) (pk, skPrefix string)
- func GetTrusteeConfigsByUserKeys(_ string) (pk, skStart, skEnd string)
- func IsCanonicalRemoteStatusID(statusID string) bool
- func IsCanonicalSHA256Digest(value string) bool
- func IsValidMediaCategory(category MediaCategory) bool
- func NormalizeAgentAccessLeaseTokenTTLHours(idleTimeoutHours, absoluteTTLHours, tokenTTLHours int) int
- func NormalizePromoPackageVisibility(visibility string) (string, error)
- func NormalizeRelationshipIdentity(identifier string, localDomain string) string
- func NormalizeRemoteActorHandle(handle string) string
- func OAuthRefreshAuthorityPK(username, clientID, resource string) string
- func PromoPackageContentHash(p *PromoPackage) string
- func ReputationActorIDsMatch(left, right string) bool
- func ReputationActorPartitionKeyCandidates(actorID string) ([]string, error)
- func ReputationActorPartitionKeyForRecord(actorID string, reputation interface{}) (string, error)
- func SkillAssignmentPartitionKey(subjectType, subjectID string) string
- func SkillAssignmentSortKey(skillID, assignmentID string) string
- func SkillPartitionKey(skillID string) string
- func SkillPromotionDigest(proposal *SkillProposal, revision *SkillRevision) (string, error)
- func SkillProposalPartitionKey(proposalID string) string
- func SkillRevisionApprovalDigest(revision *SkillRevision, principalID, authorityType, authorityID string) (string, error)
- func SkillRevisionSortKey(revisionNumber int) string
- func SoulBindingIdempotencyKeyHash(idempotencyKey string) string
- func SoulBindingIdempotencyPartitionKey(callerID string) string
- func SoulBindingIdempotencySortKey(idempotencyKey string) string
- func SoulBindingIdempotencySortKeyFromHash(idempotencyKeyHash string) string
- func SoulBodyBindingSortKey(agentID string) string
- func SoulBodyBindingUsernamePartitionKey(username string) string
- func SoulENSChannelSortKey(agentID string) string
- func StatusLookupCandidates(raw string) []string
- func StatusLookupCandidatesForDomain(raw string, localDomain string) []string
- type AIAggregatedCost
- type AIAnalysis
- type AIAnalysisQueue
- type AICost
- func (a *AICost) AddComplexityFactor(factor string)
- func (a *AICost) BeforeCreate() error
- func (a *AICost) BeforeUpdate() error
- func (a *AICost) CalculateTotalCost()
- func (a *AICost) GetOperationSummary() map[string]interface{}
- func (a *AICost) GetPK() string
- func (a *AICost) GetPerformanceMetrics() map[string]interface{}
- func (a *AICost) GetSK() string
- func (a *AICost) GetTotalCostDollars() float64
- func (a *AICost) SetModelPricing()
- func (a *AICost) TableName() string
- func (a *AICost) UpdateKeys() error
- type AIInstanceConfig
- type AIInstanceConfigManaged
- type AIInstanceConfigOverride
- type AIInstanceConfigPatch
- type APIRateLimit
- type AccountNote
- type AccountPin
- type Activity
- type ActivityActorDay
- type ActivityDayCounter
- type ActivityMetric
- type Actor
- type ActorField
- type ActorMetadata
- type AdvancedModerationAction
- type AdvancedSeverity
- type AffectedRelationship
- type AgentAccessLease
- func (l *AgentAccessLease) BeforeCreate() error
- func (l *AgentAccessLease) BeforeUpdate() error
- func (l *AgentAccessLease) EffectiveTokenTTLHours() int
- func (l *AgentAccessLease) GetPK() string
- func (l *AgentAccessLease) GetSK() string
- func (AgentAccessLease) TableName() string
- func (l *AgentAccessLease) UpdateKeys() error
- type AgentAccessLeaseChallenge
- func (c *AgentAccessLeaseChallenge) BeforeCreate() error
- func (c *AgentAccessLeaseChallenge) EffectiveTokenTTLHours() int
- func (c *AgentAccessLeaseChallenge) GetPK() string
- func (c *AgentAccessLeaseChallenge) GetSK() string
- func (AgentAccessLeaseChallenge) TableName() string
- func (c *AgentAccessLeaseChallenge) UpdateKeys() error
- type AgentConcurrencySlot
- type AgentGovernanceState
- type AgentInstanceConfig
- type AgentKeyChallenge
- type AgentMemoryEvent
- type AgentShareGrant
- type AggregatedMetrics
- func (am *AggregatedMetrics) BeforeCreate() error
- func (am *AggregatedMetrics) BeforeUpdate() error
- func (am *AggregatedMetrics) GetPK() string
- func (am *AggregatedMetrics) GetSK() string
- func (AggregatedMetrics) TableName() string
- func (am *AggregatedMetrics) UpdateKeys() error
- func (am *AggregatedMetrics) Validate() error
- type Alert
- func (a *Alert) Acknowledge()
- func (a *Alert) AddDimension(key, value string)
- func (a *Alert) AddMetadata(key string, value interface{})
- func (a *Alert) AddThreshold(key string, value float64)
- func (a *Alert) AddValue(key string, value float64)
- func (a *Alert) CalculateNextRetry() time.Time
- func (a *Alert) Escalate()
- func (a *Alert) GetPK() string
- func (a *Alert) GetSK() string
- func (a *Alert) IsActive() bool
- func (a *Alert) IsCritical() bool
- func (a *Alert) IsHighPriority() bool
- func (a *Alert) IsResolved() bool
- func (a *Alert) RecordDeliveryAttempt(success bool)
- func (a *Alert) Resolve()
- func (a *Alert) ShouldRetry() bool
- func (a *Alert) Suppress(until time.Time)
- func (Alert) TableName() string
- func (a *Alert) UpdateKeys() error
- type Announce
- type Announcement
- type AnnouncementDismissal
- type AnnouncementReaction
- type Article
- type AuditLog
- type AuthAuditLog
- type AuthRefreshToken
- func (a *AuthRefreshToken) BeforeCreate() error
- func (a *AuthRefreshToken) BeforeUpdate() error
- func (a *AuthRefreshToken) GetPK() string
- func (a *AuthRefreshToken) GetSK() string
- func (a *AuthRefreshToken) IsActive() bool
- func (a *AuthRefreshToken) IsExpired() bool
- func (AuthRefreshToken) TableName() string
- func (a *AuthRefreshToken) UpdateKeys() error
- type AuthorizationCode
- type BackgroundFetchJob
- func (j *BackgroundFetchJob) AddMetadata(key, value string)
- func (j *BackgroundFetchJob) BeforeCreate() error
- func (j *BackgroundFetchJob) BeforeUpdate() error
- func (j *BackgroundFetchJob) GetMetadata(key string) string
- func (j *BackgroundFetchJob) IsReady() bool
- func (j *BackgroundFetchJob) IsRetryable() bool
- func (j *BackgroundFetchJob) MarkCompleted()
- func (j *BackgroundFetchJob) MarkFailed(errorMsg, errorDetails string)
- func (j *BackgroundFetchJob) MarkRunning()
- func (j *BackgroundFetchJob) SetRemoteURL(url string)
- func (BackgroundFetchJob) TableName() string
- func (j *BackgroundFetchJob) UpdateKeys()
- type BatchGetKeys
- type Block
- type Bookmark
- type CMSArticleIndex
- type CMSSeriesSlugIndex
- type CMSSlugIndex
- type CSRFToken
- func (c *CSRFToken) BeforeCreate() error
- func (c *CSRFToken) BeforeUpdate() error
- func (c *CSRFToken) GetPK() string
- func (c *CSRFToken) GetSK() string
- func (c *CSRFToken) IsExpired() bool
- func (c *CSRFToken) IsValid() bool
- func (c *CSRFToken) MarkAsUsed()
- func (c *CSRFToken) RemainingTime() time.Duration
- func (CSRFToken) TableName() string
- func (c *CSRFToken) UpdateKeys() error
- func (c *CSRFToken) Validate() error
- type Category
- type CircuitBreakerConfig
- type CircuitBreakerEvent
- type CircuitBreakerState
- func (c *CircuitBreakerState) GetBackoffDuration() time.Duration
- func (c *CircuitBreakerState) GetPK() string
- func (c *CircuitBreakerState) GetSK() string
- func (c *CircuitBreakerState) SetBackoffDuration(d time.Duration)
- func (CircuitBreakerState) TableName() string
- func (c *CircuitBreakerState) UpdateKeys() error
- type CloudWatchMetrics
- type CollectionItem
- func (c *CollectionItem) BeforeCreate() error
- func (c *CollectionItem) ExtractCollection() string
- func (c *CollectionItem) ExtractItemID() string
- func (c *CollectionItem) SetPosition(position int)
- func (c *CollectionItem) SetTTL(ttl time.Time)
- func (CollectionItem) TableName() string
- func (c *CollectionItem) UpdateKeys()
- type CommunityNote
- type CommunityNoteVote
- type ComponentHealthHistory
- type ConcurrentViewerMetrics
- type ConnectionInfo
- type ConnectionMetrics
- type ConnectionState
- type Conversation
- type ConversationMessage
- type ConversationMute
- type ConversationParticipantKey
- type ConversationParticipantRecord
- func (p *ConversationParticipantRecord) BeforeCreate(participantID string) error
- func (p *ConversationParticipantRecord) GetPK() string
- func (p *ConversationParticipantRecord) GetSK() string
- func (ConversationParticipantRecord) TableName() string
- func (p *ConversationParticipantRecord) UpdateKeys() error
- type ConversationParticipantRef
- type ConversationParticipantType
- type ConversationStatus
- type CostProjection
- type CustomEmoji
- type DLQMessage
- func NewDependencyErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
- func NewProcessingErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
- func NewTransientErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
- func NewValidationErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
- func (d *DLQMessage) AddTag(tag string)
- func (d *DLQMessage) BeforeCreate() error
- func (d *DLQMessage) BeforeUpdate() error
- func (d *DLQMessage) CanReprocess() bool
- func (d *DLQMessage) GetMetadata(key string) (interface{}, bool)
- func (d *DLQMessage) GetPK() string
- func (d *DLQMessage) GetSK() string
- func (d *DLQMessage) GetTotalCost() int64
- func (d *DLQMessage) MarkAbandoned()
- func (d *DLQMessage) MarkFailed(errorMsg string)
- func (d *DLQMessage) MarkForReprocessing()
- func (d *DLQMessage) MarkResolved()
- func (d *DLQMessage) SetMetadata(key string, value interface{})
- func (d *DLQMessage) ShouldAbandon() bool
- func (DLQMessage) TableName() string
- func (d *DLQMessage) UpdateCosts(processingCost, reprocessingCost int64)
- func (d *DLQMessage) UpdateKeys() error
- func (d *DLQMessage) Validate() error
- type DLQMessageBuilder
- func (b *DLQMessageBuilder) Build() *DLQMessage
- func (b *DLQMessageBuilder) ForService(service string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) MarkAsPermanent() *DLQMessageBuilder
- func (DLQMessageBuilder) TableName() string
- func (b *DLQMessageBuilder) WithAttributes(attributes map[string]string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithBusinessImpact(impact string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithContext(functionName, logGroup, logStream, requestID string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithError(errorType, errorMessage, errorStack string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithFailureReason(reason string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithMetadata(metadata map[string]interface{}) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithOriginalMessage(messageID, body string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithPriority(priority string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithQueue(queueName, sourceQueue string) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithRetryInfo(originalRetryCount, maxReprocessAttempts int) *DLQMessageBuilder
- func (b *DLQMessageBuilder) WithTags(tags ...string) *DLQMessageBuilder
- type DNSCache
- type DeadLetterMessage
- type DeliveryStatus
- type Device
- type DimensionStats
- type DirectMessageMigrationState
- func (s *DirectMessageMigrationState) BeforeCreate() error
- func (s *DirectMessageMigrationState) BeforeUpdate() error
- func (s *DirectMessageMigrationState) GetPK() string
- func (s *DirectMessageMigrationState) GetSK() string
- func (DirectMessageMigrationState) TableName() string
- func (s *DirectMessageMigrationState) UpdateKeys() error
- type DirectMessageSendTransition
- type DirectMessageTombstone
- type DmRequestState
- type DomainAllow
- type DomainCounter
- type Draft
- type DraftMediaUsage
- type DraftReviewGrant
- type DraftReviewVerdict
- type Driver
- func (c *Driver) CalculateTrend()
- func (c *Driver) DetermineCostType()
- func (c *Driver) FormatCostSummary() string
- func (c *Driver) GetCostPerUnit(metric string) float64
- func (c *Driver) IsSignificant() bool
- func (c *Driver) SetVolumeMetric(metric string, value int64)
- func (Driver) TableName() string
- func (c *Driver) UpdateKeys()
- type DynamoDBCostAggregation
- func (act *DynamoDBCostAggregation) BeforeCreate() error
- func (act *DynamoDBCostAggregation) BeforeUpdate() error
- func (act *DynamoDBCostAggregation) GetPK() string
- func (act *DynamoDBCostAggregation) GetSK() string
- func (DynamoDBCostAggregation) TableName() string
- func (act *DynamoDBCostAggregation) UpdateKeys() error
- func (act *DynamoDBCostAggregation) Validate() error
- type DynamoDBCostRecord
- func (ct *DynamoDBCostRecord) AddTag(key, value string)
- func (ct *DynamoDBCostRecord) BeforeCreate() error
- func (ct *DynamoDBCostRecord) BeforeUpdate() error
- func (ct *DynamoDBCostRecord) GetPK() string
- func (ct *DynamoDBCostRecord) GetProperty(key string) (interface{}, bool)
- func (ct *DynamoDBCostRecord) GetSK() string
- func (ct *DynamoDBCostRecord) SetProperty(key string, value interface{})
- func (DynamoDBCostRecord) TableName() string
- func (ct *DynamoDBCostRecord) UpdateKeys() error
- func (ct *DynamoDBCostRecord) Validate() error
- type DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) Build() *DynamoDBCostRecord
- func (ctb *DynamoDBCostRecordBuilder) ForOperation(operationType string) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) OnTable(tableName string) *DynamoDBCostRecordBuilder
- func (DynamoDBCostRecordBuilder) TableName() string
- func (ctb *DynamoDBCostRecordBuilder) WithCapacityUnits(readUnits, writeUnits float64) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithConsistentRead(consistent bool) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithCostMicroCents(readCost, writeCost int64) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithDuration(durationMs int64) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithIndex(indexName string) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithItemCount(count int) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithPeriod(period string) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithRequestID(requestID string) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithService(serviceName, functionName string) *DynamoDBCostRecordBuilder
- func (ctb *DynamoDBCostRecordBuilder) WithTag(key, value string) *DynamoDBCostRecordBuilder
- type DynamoDBServiceCostStats
- type DynamoDBTableCostStats
- type EditorialLifecycle
- type EditorialMediaOrigin
- type EditorialMediaRole
- type EffectiveAIInstanceConfig
- type EffectiveTipsConfig
- type EffectiveTrustConfig
- type EmailDomainBlock
- type EmojiModel
- type EngagementMetrics
- type EnhancedModerationPattern
- func (p *EnhancedModerationPattern) CalculateEffectiveness()
- func (p *EnhancedModerationPattern) GetPK() string
- func (p *EnhancedModerationPattern) GetSK() string
- func (p *EnhancedModerationPattern) IsExpired() bool
- func (p *EnhancedModerationPattern) ShouldEscalate() bool
- func (EnhancedModerationPattern) TableName() string
- func (p *EnhancedModerationPattern) UpdateKeys() error
- type ErrorFrequency
- type Export
- type ExportCostSummary
- type ExportCostTracking
- func (e *ExportCostTracking) BeforeCreate() error
- func (e *ExportCostTracking) BeforeUpdate() error
- func (e *ExportCostTracking) CalculateTotalCost()
- func (e *ExportCostTracking) GetTimestamp() time.Time
- func (e *ExportCostTracking) GetTotalCostDollars() float64
- func (e *ExportCostTracking) GetTotalCostMicroCents() int64
- func (e *ExportCostTracking) TableName() string
- func (e *ExportCostTracking) UpdateKeys()
- type ExportDateRange
- type ExportTypeCostStats
- type FeaturedTag
- type FederationActivity
- func (fa *FederationActivity) BeforeCreate() error
- func (fa *FederationActivity) BeforeUpdate() error
- func (fa *FederationActivity) GetHeader(key string) (string, bool)
- func (fa *FederationActivity) GetPK() string
- func (fa *FederationActivity) GetProperty(key string) (interface{}, bool)
- func (fa *FederationActivity) GetSK() string
- func (fa *FederationActivity) IsRemote(localDomain string) bool
- func (fa *FederationActivity) MarkFailed(errorMsg string)
- func (fa *FederationActivity) MarkSuccess()
- func (fa *FederationActivity) SetHeader(key, value string)
- func (fa *FederationActivity) SetProperty(key string, value interface{})
- func (FederationActivity) TableName() string
- func (fa *FederationActivity) UpdateKeys() error
- func (fa *FederationActivity) Validate() error
- type FederationActivityBuilder
- func (fab *FederationActivityBuilder) Build() *FederationActivity
- func (fab *FederationActivityBuilder) FromDomain(domain string) *FederationActivityBuilder
- func (FederationActivityBuilder) TableName() string
- func (fab *FederationActivityBuilder) WithActor(actorID string) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithError(err error) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithInstanceInfo(info *InstanceInfo) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithObject(objectID, objectType string) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithResponseTime(ms float64) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithType(activityType string) *FederationActivityBuilder
- func (fab *FederationActivityBuilder) WithVolume(inbound, outbound int64) *FederationActivityBuilder
- type FederationAlert
- type FederationAnalyticsTimeSeries
- func (f *FederationAnalyticsTimeSeries) Aggregate(rawMetrics []*FederationAnalyticsTimeSeries)
- func (f *FederationAnalyticsTimeSeries) CalculateHealthScore()
- func (f *FederationAnalyticsTimeSeries) IsCritical() bool
- func (f *FederationAnalyticsTimeSeries) IsDegraded() bool
- func (f *FederationAnalyticsTimeSeries) IsHealthy() bool
- func (f *FederationAnalyticsTimeSeries) IsUnhealthy() bool
- func (f *FederationAnalyticsTimeSeries) ShouldTriggerAlert() (bool, string)
- func (FederationAnalyticsTimeSeries) TableName() string
- func (f *FederationAnalyticsTimeSeries) UpdateKeys()
- type FederationBudget
- func (f *FederationBudget) AddUsage(activityType, direction string, cost int64)
- func (f *FederationBudget) BeforeCreate() error
- func (f *FederationBudget) BeforeUpdate() error
- func (f *FederationBudget) GetActivityTypeUsagePercent(activityType string) float64
- func (f *FederationBudget) GetCombinedUsagePercent() float64
- func (f *FederationBudget) GetInboundUsagePercent() float64
- func (f *FederationBudget) GetOutboundUsagePercent() float64
- func (f *FederationBudget) GetPK() string
- func (f *FederationBudget) GetSK() string
- func (f *FederationBudget) IsOverActivityTypeLimit(activityType string) bool
- func (f *FederationBudget) IsOverCombinedLimit() bool
- func (f *FederationBudget) IsOverInboundLimit() bool
- func (f *FederationBudget) IsOverOutboundLimit() bool
- func (f *FederationBudget) ResetPeriod(newPeriodStart, newPeriodEnd time.Time)
- func (f *FederationBudget) ShouldBlock() bool
- func (f *FederationBudget) ShouldRateLimit() bool
- func (f *FederationBudget) ShouldSendAlert() bool
- func (FederationBudget) TableName() string
- func (f *FederationBudget) UpdateKeys() error
- type FederationCost
- type FederationCostActivity
- type FederationCostTracking
- func (f *FederationCostTracking) AddRetryDelay(delaySeconds int64)
- func (f *FederationCostTracking) AddRouteDeliveryAttempt(routeID string, bytes int64, latencyMs int64, success bool, errorMsg string)
- func (f *FederationCostTracking) BeforeCreate() error
- func (f *FederationCostTracking) BeforeUpdate() error
- func (f *FederationCostTracking) CalculateTotalCost()
- func (f *FederationCostTracking) GetAverageRouteLatency() int64
- func (f *FederationCostTracking) GetMostExpensiveRoute() (string, int64)
- func (f *FederationCostTracking) GetPK() string
- func (f *FederationCostTracking) GetRetryEfficiency() map[string]interface{}
- func (f *FederationCostTracking) GetSK() string
- func (f *FederationCostTracking) GetTotalCostDollars() float64
- func (f *FederationCostTracking) GetTotalRouteErrors() int
- func (FederationCostTracking) TableName() string
- func (f *FederationCostTracking) UpdateKeys() error
- type FederationEdge
- type FederationHealthReport
- type FederationInstance
- type FederationInstanceConfigTracking
- func (f *FederationInstanceConfigTracking) BeforeCreate() error
- func (f *FederationInstanceConfigTracking) BeforeUpdate() error
- func (f *FederationInstanceConfigTracking) GetBudgetLimit() float64
- func (f *FederationInstanceConfigTracking) GetRateLimit() int
- func (FederationInstanceConfigTracking) TableName() string
- func (f *FederationInstanceConfigTracking) UpdateKeys()
- type FederationInstanceHealthTracking
- func (f *FederationInstanceHealthTracking) BeforeCreate() error
- func (f *FederationInstanceHealthTracking) BeforeUpdate() error
- func (f *FederationInstanceHealthTracking) CalculateHealthScore()
- func (f *FederationInstanceHealthTracking) TableName() string
- func (f *FederationInstanceHealthTracking) UpdateKeys()
- type FederationInstanceRegistry
- type FederationInstanceRegistryHealthHistory
- type FederationIssue
- type FederationNode
- type FederationRelationship
- func (fr *FederationRelationship) GetTrafficRate() float64
- func (fr *FederationRelationship) IsInWarmup() bool
- func (fr *FederationRelationship) ShouldTransitionState() (RelationshipState, bool)
- func (FederationRelationship) TableName() string
- func (fr *FederationRelationship) TransitionToState(newState RelationshipState)
- func (fr *FederationRelationship) UpdateKeys()
- func (fr *FederationRelationship) UpdateSuccessRate(success bool, responseTime float64)
- type FederationRelationshipAggregate
- type FederationRelationshipIndex
- type FederationRouteAggregation
- func (f *FederationRouteAggregation) BeforeCreate() error
- func (f *FederationRouteAggregation) BeforeUpdate() error
- func (f *FederationRouteAggregation) GetRouteComparisonMetrics() map[string]interface{}
- func (FederationRouteAggregation) TableName() string
- func (f *FederationRouteAggregation) UpdateKeys()
- type FederationRouteMetrics
- func (f *FederationRouteMetrics) AddDeliveryAttempt(success bool, latencyMs int64, errorCode string, errorMsg string, ...)
- func (f *FederationRouteMetrics) AddRetryAttempt(delayMs int64)
- func (f *FederationRouteMetrics) BeforeCreate() error
- func (f *FederationRouteMetrics) BeforeUpdate() error
- func (f *FederationRouteMetrics) GetOptimizationRecommendations() []RouteRecommendation
- func (f *FederationRouteMetrics) GetRouteSummary() map[string]interface{}
- func (f *FederationRouteMetrics) IsHealthy() bool
- func (FederationRouteMetrics) TableName() string
- func (f *FederationRouteMetrics) UpdateKeys()
- type FederationSeverance
- type FederationStats
- type FederationTier
- type FederationTimeSeries
- type FederationTimeseriesWindow
- type FieldVerification
- type Filter
- type FilterKeyword
- type FilterStatus
- type Flag
- type Follow
- type FollowRequestState
- type GeographicMetric
- type GlobalMetricsWindow
- type GraphQLStreamSubscription
- type Hashtag
- type HashtagFollow
- type HashtagHistoryEntry
- type HashtagMute
- type HashtagNotificationSettings
- type HashtagSearchCache
- type HashtagSearchResult
- func (h *HashtagSearchResult) AddHistory(trend *TrendingHashtag)
- func (h *HashtagSearchResult) GetLatestUsage() int64
- func (h *HashtagSearchResult) GetTotalUsage() int64
- func (h *HashtagSearchResult) HasRecentActivity() bool
- func (h *HashtagSearchResult) IsFollowing() bool
- func (h *HashtagSearchResult) SetFollowing(following bool)
- func (HashtagSearchResult) TableName() string
- type HashtagStats
- func (h *HashtagStats) AddHistoryEntry(date time.Time, usageCount, userCount int64)
- func (h *HashtagStats) AddUniqueUser()
- func (h *HashtagStats) GetAverageUsage() float64
- func (h *HashtagStats) GetGrowthRate() float64
- func (h *HashtagStats) IncrementUsage()
- func (h *HashtagStats) IsActive() bool
- func (h *HashtagStats) IsTrending(threshold float64) bool
- func (HashtagStats) TableName() string
- func (h *HashtagStats) UpdateKeys()
- func (h *HashtagStats) UpdateTrendingScore()
- type HashtagStatusIndex
- type HashtagTrend
- type HashtagTrendingData
- type HashtagUsage
- type HealthCheckResult
- type HealthCheckSummaryResult
- type Import
- type ImportBudget
- func (b *ImportBudget) BeforeCreate() error
- func (b *ImportBudget) BeforeUpdate() error
- func (b *ImportBudget) GetCombinedUsagePercent() float64
- func (b *ImportBudget) GetExportUsagePercent() float64
- func (b *ImportBudget) GetImportUsagePercent() float64
- func (b *ImportBudget) GetRemainingCombinedBudget() int64
- func (b *ImportBudget) GetRemainingExportBudget() int64
- func (b *ImportBudget) GetRemainingImportBudget() int64
- func (b *ImportBudget) IsCombinedOverLimit(additionalImportCost, additionalExportCost int64) bool
- func (b *ImportBudget) IsExportOverLimit(additionalCost int64) bool
- func (b *ImportBudget) IsImportOverLimit(additionalCost int64) bool
- func (b *ImportBudget) NeedsReset() bool
- func (b *ImportBudget) Reset()
- func (b *ImportBudget) ShouldSendAlert() bool
- func (ImportBudget) TableName() string
- func (b *ImportBudget) UpdateKeys()
- type ImportCostSummary
- type ImportCostTracking
- func (i *ImportCostTracking) BeforeCreate() error
- func (i *ImportCostTracking) BeforeUpdate() error
- func (i *ImportCostTracking) CalculateTotalCost()
- func (i *ImportCostTracking) GetSuccessRate() float64
- func (i *ImportCostTracking) GetTimestamp() time.Time
- func (i *ImportCostTracking) GetTotalCostDollars() float64
- func (i *ImportCostTracking) GetTotalCostMicroCents() int64
- func (i *ImportCostTracking) TableName() string
- func (i *ImportCostTracking) UpdateKeys()
- type ImportTypeCostStats
- type InboxItem
- type InboxProcessingReceipt
- func (r *InboxProcessingReceipt) BeforeCreate() error
- func (r *InboxProcessingReceipt) BeforeUpdate() error
- func (r *InboxProcessingReceipt) GetPK() string
- func (r *InboxProcessingReceipt) GetSK() string
- func (InboxProcessingReceipt) TableName() string
- func (r *InboxProcessingReceipt) UpdateKeys() error
- type InstanceCluster
- type InstanceConfig
- type InstanceConnection
- type InstanceDomainBlock
- type InstanceHealth
- type InstanceHealthReport
- type InstanceHealthSummary
- type InstanceHistory
- func (i *InstanceHistory) CalculateDelta(previousValue int64)
- func (i *InstanceHistory) GetPK() string
- func (i *InstanceHistory) GetSK() string
- func (i *InstanceHistory) SetFederationMetrics(knownInstances, activeInstances int64)
- func (i *InstanceHistory) SetPostMetrics(total, newPosts, local, federated int64)
- func (i *InstanceHistory) SetStorageMetrics(totalBytes, mediaBytes, dbBytes int64)
- func (i *InstanceHistory) SetUserMetrics(total, active, newUsers int64)
- func (i *InstanceHistory) TableName() string
- func (i *InstanceHistory) UpdateKeys() error
- type InstanceInfo
- type InstanceMetadata
- type InstanceMetrics
- type InstanceMetricsWindow
- type InstanceRule
- type InstanceSoulBindingIdempotencyReceipt
- type InstanceSoulBodyBinding
- type InstanceSoulBodyBindingUsername
- type InstanceSoulENSChannel
- type InstanceState
- type InstanceTimeseriesWindow
- type InstanceTipsConfig
- type InstanceTipsConfigManaged
- type InstanceTipsConfigOverride
- type InstanceTipsConfigPatch
- type InstanceTranslationConfig
- type InstanceTranslationConfigManaged
- type InstanceTranslationConfigOverride
- type InstanceTranslationConfigPatch
- type InstanceTrustConfig
- type InstanceTrustConfigManaged
- type InstanceTrustConfigOverride
- type InstanceTrustConfigPatch
- type InstanceWellKnownLesserSoulAgent
- type Like
- type LinkMetadata
- func (l *LinkMetadata) GetDisplayDomain() string
- func (l *LinkMetadata) HasImage() bool
- func (l *LinkMetadata) IsStale(maxAge time.Duration) bool
- func (l *LinkMetadata) RecordAccess()
- func (l *LinkMetadata) SanitizeMetadata()
- func (l *LinkMetadata) SetFromOpenGraph(ogTitle, ogDescription, ogImage string)
- func (l *LinkMetadata) SetFromTwitterCard(twitterTitle, twitterDescription, twitterImage string)
- func (LinkMetadata) TableName() string
- func (l *LinkMetadata) TruncateDescription(maxLength int)
- func (l *LinkMetadata) UpdateKeys()
- type LinkShare
- type LinkTrend
- type List
- type ListMember
- type LoginAttempt
- type MLPollRequest
- type MLPrediction
- type Marker
- type Media
- func (m *Media) AddVariant(name string, variant MediaVariant)
- func (m *Media) BeforeCreate() error
- func (m *Media) BeforeUpdate() error
- func (m *Media) EditorialLifecycleAvailableForPublish() bool
- func (m *Media) GetAvailableVariants() []string
- func (m *Media) GetBestVariant(maxWidth, maxHeight int) MediaVariant
- func (m *Media) GetPK() string
- func (m *Media) GetSK() string
- func (m *Media) GetTotalSize() int64
- func (m *Media) GetVariant(name string) (MediaVariant, bool)
- func (m *Media) IsAudio() bool
- func (m *Media) IsFailed() bool
- func (m *Media) IsImage() bool
- func (m *Media) IsInternalEditorial() bool
- func (m *Media) IsProcessing() bool
- func (m *Media) IsPublished() bool
- func (m *Media) IsReady() bool
- func (m *Media) IsVideo() bool
- func (m *Media) MarkUsed()
- func (m *Media) SetFailed(errorMsg string)
- func (m *Media) SetModeration(isNSFW bool, score float64, labels []string)
- func (m *Media) SetProcessed()
- func (m *Media) SetProcessing()
- func (Media) TableName() string
- func (m *Media) UpdateKeys() error
- func (m *Media) Validate() error
- type MediaAnalytics
- func (m *MediaAnalytics) AddQualityViewer(quality string)
- func (m *MediaAnalytics) AddVariantCost(resolution, codec string, bitrate int, cost MediaVariantCost)
- func (m *MediaAnalytics) GetCostEfficiencyMetrics() map[string]interface{}
- func (m *MediaAnalytics) GetMostPopularQuality() (string, int)
- func (m *MediaAnalytics) GetPK() string
- func (m *MediaAnalytics) GetSK() string
- func (m *MediaAnalytics) RemoveQualityViewer(quality string)
- func (m *MediaAnalytics) SetGeneralEvent(eventType, mediaID, userID string)
- func (m *MediaAnalytics) SetManifestGeneration(mediaID, format string, duration float64)
- func (m *MediaAnalytics) SetQualityChange(mediaID, userID, _, newQuality string)
- func (MediaAnalytics) TableName() string
- func (m *MediaAnalytics) TrackVariantDelivery(variantKey string, bytes int64, latencyMs int64, cacheHit bool, success bool)
- func (m *MediaAnalytics) UpdateKeys() error
- type MediaAttachment
- func (m *MediaAttachment) BeforeCreate() error
- func (m *MediaAttachment) BeforeUpdate() error
- func (m *MediaAttachment) GetFocalPoint() (x, y float64, ok bool)
- func (m *MediaAttachment) IsForScheduledStatus() bool
- func (m *MediaAttachment) IsForUser() bool
- func (m *MediaAttachment) SetFocalPoint(x, y float64)
- func (MediaAttachment) TableName() string
- func (m *MediaAttachment) UpdateKeys(entityType, entityID string)
- func (m *MediaAttachment) Validate() error
- type MediaCategory
- type MediaJob
- func (mj *MediaJob) AddCost(costMicros int64)
- func (mj *MediaJob) AddProcessingTask(task string)
- func (mj *MediaJob) BeforeCreate() error
- func (mj *MediaJob) BeforeUpdate() error
- func (mj *MediaJob) CanRetry() bool
- func (mj *MediaJob) GenerateIdempotencyKey() string
- func (mj *MediaJob) GetPK() string
- func (mj *MediaJob) GetProcessingDuration() time.Duration
- func (mj *MediaJob) GetRemainingProcessingTime() time.Duration
- func (mj *MediaJob) GetSK() string
- func (mj *MediaJob) HasProcessingTask(task string) bool
- func (mj *MediaJob) IsAbandoned(abandonThreshold time.Duration) bool
- func (mj *MediaJob) IsBudgetExceeded() bool
- func (mj *MediaJob) IsCancelled() bool
- func (mj *MediaJob) IsCompleted() bool
- func (mj *MediaJob) IsFailed() bool
- func (mj *MediaJob) IsIdle() bool
- func (mj *MediaJob) IsPending() bool
- func (mj *MediaJob) IsProcessing() bool
- func (mj *MediaJob) IsReadyForRetry() bool
- func (mj *MediaJob) IsRetryableError(errorMsg string) bool
- func (mj *MediaJob) ScheduleRetry(baseDelay time.Duration)
- func (mj *MediaJob) SetCancelled(reason string)
- func (mj *MediaJob) SetCompleted(results map[string]any)
- func (mj *MediaJob) SetFailed(errorMsg string)
- func (mj *MediaJob) SetProcessing()
- func (MediaJob) TableName() string
- func (mj *MediaJob) UpdateKeys() error
- func (mj *MediaJob) UpdateProgress(progress int)
- func (mj *MediaJob) Validate() error
- type MediaMetadata
- func (m *MediaMetadata) AddQuality(quality string)
- func (m *MediaMetadata) BeforeCreate() error
- func (m *MediaMetadata) BeforeUpdate() error
- func (m *MediaMetadata) GetCodecInfo(quality string) (QualityCodecInfo, bool)
- func (m *MediaMetadata) GetPK() string
- func (m *MediaMetadata) GetSK() string
- func (m *MediaMetadata) HasQuality(quality string) bool
- func (m *MediaMetadata) IsComplete() bool
- func (m *MediaMetadata) IsFailed() bool
- func (m *MediaMetadata) IsPending() bool
- func (m *MediaMetadata) IsProcessing() bool
- func (m *MediaMetadata) SetCodecInfo(quality string, info QualityCodecInfo)
- func (m *MediaMetadata) SetComplete()
- func (m *MediaMetadata) SetFailed()
- func (m *MediaMetadata) SetProcessing()
- func (MediaMetadata) TableName() string
- func (m *MediaMetadata) UpdateKeys() error
- func (m *MediaMetadata) Validate() error
- type MediaPopularity
- func (m *MediaPopularity) AddQualityView(quality string, count int64)
- func (m *MediaPopularity) CalculateAvgWatchTime() float64
- func (m *MediaPopularity) CalculateCompletionRate() float64
- func (m *MediaPopularity) GetPK() string
- func (m *MediaPopularity) GetSK() string
- func (m *MediaPopularity) IncrementViews(count int64)
- func (m *MediaPopularity) SetForPeriod(mediaID string, period string, viewCount int64)
- func (MediaPopularity) TableName() string
- func (m *MediaPopularity) UpdateKeys() error
- type MediaProvenance
- type MediaSession
- type MediaSpending
- func (ms *MediaSpending) AddSpending(transaction *MediaSpendingTransaction)
- func (ms *MediaSpending) BeforeCreate() error
- func (ms *MediaSpending) BeforeUpdate() error
- func (ms *MediaSpending) GetCostBreakdown() map[string]int64
- func (ms *MediaSpending) GetEfficiencyMetrics() map[string]float64
- func (ms *MediaSpending) GetPK() string
- func (ms *MediaSpending) GetRemainingBudget() int64
- func (ms *MediaSpending) GetSK() string
- func (ms *MediaSpending) GetServiceBreakdown() map[string]int64
- func (ms *MediaSpending) IsOverBudget() bool
- func (MediaSpending) TableName() string
- func (ms *MediaSpending) UpdateKeys() error
- func (ms *MediaSpending) Validate() error
- type MediaSpendingTransaction
- func (mst *MediaSpendingTransaction) BeforeCreate() error
- func (mst *MediaSpendingTransaction) GetPK() string
- func (mst *MediaSpendingTransaction) GetSK() string
- func (MediaSpendingTransaction) TableName() string
- func (mst *MediaSpendingTransaction) UpdateKeys() error
- func (mst *MediaSpendingTransaction) Validate() error
- type MediaVariant
- type MediaVariantCost
- type MediaVisibility
- type Mention
- type MetricRecord
- func (m *MetricRecord) AddDimension(key, value string)
- func (m *MetricRecord) BeforeCreate() error
- func (m *MetricRecord) BeforeUpdate() error
- func (m *MetricRecord) GetPK() string
- func (m *MetricRecord) GetSK() string
- func (MetricRecord) TableName() string
- func (m *MetricRecord) UpdateKeys() error
- func (m *MetricRecord) Validate() error
- type MetricRecordBuilder
- func (mb *MetricRecordBuilder) Build() *MetricRecord
- func (mb *MetricRecordBuilder) ForService(serviceName string) *MetricRecordBuilder
- func (mb *MetricRecordBuilder) OfType(metricType string) *MetricRecordBuilder
- func (MetricRecordBuilder) TableName() string
- func (mb *MetricRecordBuilder) WithAggregationLevel(level string) *MetricRecordBuilder
- func (mb *MetricRecordBuilder) WithDimension(key, value string) *MetricRecordBuilder
- func (mb *MetricRecordBuilder) WithStats(count int64, sum, minVal, maxVal, p50, p95, p99 float64) *MetricRecordBuilder
- func (mb *MetricRecordBuilder) WithTimestamp(timestamp time.Time) *MetricRecordBuilder
- func (mb *MetricRecordBuilder) WithUnit(unit string) *MetricRecordBuilder
- type Metrics
- func (m *Metrics) AddDimension(key, value string)
- func (m *Metrics) AddTag(key, value string)
- func (m *Metrics) BeforeCreate() error
- func (m *Metrics) BeforeUpdate() error
- func (m *Metrics) GetPK() string
- func (m *Metrics) GetProperty(key string) (interface{}, bool)
- func (m *Metrics) GetSK() string
- func (m *Metrics) SetPercentile(percentile string, value float64)
- func (m *Metrics) SetProperty(key string, value interface{})
- func (Metrics) TableName() string
- func (m *Metrics) UpdateKeys() error
- func (m *Metrics) Validate() error
- type MetricsBuilder
- func (mb *MetricsBuilder) Build() *Metrics
- func (mb *MetricsBuilder) ForService(service string) *MetricsBuilder
- func (mb *MetricsBuilder) OfType(metricType string) *MetricsBuilder
- func (MetricsBuilder) TableName() string
- func (mb *MetricsBuilder) WithDimension(key, value string) *MetricsBuilder
- func (mb *MetricsBuilder) WithPeriod(period string) *MetricsBuilder
- func (mb *MetricsBuilder) WithResource(resourceID, resourceType string) *MetricsBuilder
- func (mb *MetricsBuilder) WithStats(count int64, sum, minVal, maxVal float64) *MetricsBuilder
- func (mb *MetricsBuilder) WithTag(key, value string) *MetricsBuilder
- func (mb *MetricsBuilder) WithUnit(unit string) *MetricsBuilder
- func (mb *MetricsBuilder) WithValue(value float64) *MetricsBuilder
- type MetricsCompression
- type MissingReply
- func (m *MissingReply) GetPK() string
- func (m *MissingReply) GetSK() string
- func (m *MissingReply) IsPermanentFailure() bool
- func (m *MissingReply) MarkFailed(errorMsg, failureReason string)
- func (m *MissingReply) MarkFetching()
- func (m *MissingReply) MarkResolved()
- func (m *MissingReply) SetPriority(priority int)
- func (m *MissingReply) ShouldRetry() bool
- func (MissingReply) TableName() string
- func (m *MissingReply) UpdateKeys() error
- type ModelTrainingJob
- type Moderation
- type ModerationAction
- type ModerationAnalysisResult
- type ModerationAnalytics
- type ModerationContentType
- type ModerationDecision
- type ModerationDecisionResult
- type ModerationDecisionSample
- type ModerationEffectivenessMetric
- type ModerationEvent
- type ModerationEvidence
- type ModerationFalsePositive
- type ModerationHistoryEntry
- type ModerationMetricsEntry
- type ModerationMetricsStats
- type ModerationMetricsTimeRange
- type ModerationModelVersion
- type ModerationPattern
- type ModerationPatternStats
- type ModerationReason
- type ModerationReview
- type ModerationReviewQueue
- type ModerationSample
- type ModerationStatus
- type Move
- type Mute
- type Notification
- func NewFavouriteNotification(userID, likerID, statusID string) *Notification
- func NewFollowNotification(userID, followerID string) *Notification
- func NewFollowRequestNotification(userID, requesterID string) *Notification
- func NewMentionNotification(userID, actorID, statusID string) *Notification
- func NewReblogNotification(userID, rebloggerID, statusID string) *Notification
- func NewReplyNotification(userID, actorID, statusID string) *Notification
- func (n *Notification) BeforeCreate() error
- func (n *Notification) BeforeUpdate() error
- func (n *Notification) GetData(key string) (interface{}, bool)
- func (n *Notification) GetPK() string
- func (n *Notification) GetSK() string
- func (n *Notification) IncrementGroupCount()
- func (n *Notification) MarkPushFailed(errorMsg string)
- func (n *Notification) MarkPushSent()
- func (n *Notification) MarkRead()
- func (n *Notification) MarkUnread()
- func (n *Notification) SetData(key string, value interface{})
- func (n *Notification) ShouldSendPush() bool
- func (Notification) TableName() string
- func (n *Notification) UpdateKeys() error
- func (n *Notification) Validate() error
- type NotificationBudget
- func (n *NotificationBudget) AddSpending(costMicroCents int64) bool
- func (n *NotificationBudget) BeforeCreate() error
- func (n *NotificationBudget) BeforeUpdate() error
- func (n *NotificationBudget) CalculateDollarAmounts()
- func (n *NotificationBudget) CalculateRemaining()
- func (n *NotificationBudget) GetPK() string
- func (n *NotificationBudget) GetSK() string
- func (n *NotificationBudget) IsMethodAllowed(method string) bool
- func (n *NotificationBudget) ResetPeriod(newPeriodStart, newPeriodEnd time.Time)
- func (n *NotificationBudget) ShouldBlockDelivery() bool
- func (n *NotificationBudget) ShouldSendWarning() bool
- func (NotificationBudget) TableName() string
- func (n *NotificationBudget) UpdateKeys() error
- type NotificationBuilder
- func (nb *NotificationBuilder) AboutTarget(targetID, targetType string) *NotificationBuilder
- func (nb *NotificationBuilder) Build() *Notification
- func (nb *NotificationBuilder) ForUser(userID string) *NotificationBuilder
- func (nb *NotificationBuilder) FromActor(actorID, actorType string) *NotificationBuilder
- func (nb *NotificationBuilder) OfType(notifType string) *NotificationBuilder
- func (NotificationBuilder) TableName() string
- func (nb *NotificationBuilder) WithContent(title, body string) *NotificationBuilder
- func (nb *NotificationBuilder) WithData(key string, value interface{}) *NotificationBuilder
- func (nb *NotificationBuilder) WithGroupKey(groupKey string) *NotificationBuilder
- type NotificationChannelCostStats
- type NotificationCostAggregation
- func (n *NotificationCostAggregation) BeforeCreate() error
- func (n *NotificationCostAggregation) BeforeUpdate() error
- func (n *NotificationCostAggregation) CalculateDollarAmounts()
- func (n *NotificationCostAggregation) CalculateRates()
- func (n *NotificationCostAggregation) GetPK() string
- func (n *NotificationCostAggregation) GetSK() string
- func (NotificationCostAggregation) TableName() string
- func (n *NotificationCostAggregation) UpdateKeys() error
- type NotificationCostTracking
- func (n *NotificationCostTracking) AddCost(method string, costMicroCents int64)
- func (n *NotificationCostTracking) BeforeCreate() error
- func (n *NotificationCostTracking) BeforeUpdate() error
- func (n *NotificationCostTracking) CalculateDollarAmounts()
- func (n *NotificationCostTracking) GetPK() string
- func (n *NotificationCostTracking) GetSK() string
- func (n *NotificationCostTracking) SetError(errorMsg string)
- func (n *NotificationCostTracking) SetSuccess()
- func (NotificationCostTracking) TableName() string
- func (n *NotificationCostTracking) UpdateKeys() error
- type NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) Build() *NotificationCostTracking
- func (NotificationCostTrackingBuilder) TableName() string
- func (b *NotificationCostTrackingBuilder) WithContext(requestID, serviceName, functionName, lambdaRequestID string) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithCosts(pushCost, websocketCost, lambdaCost, dynamodbCost int64) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithDelivery(method, channel string, success bool, retryCount int) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithError(errorMsg string) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithNotification(notificationID, userID, username, notificationType string) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithPerformance(processingTimeMs, deliveryTimeMs int64, responseCode int, responseSize int64) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithProperty(key string, value interface{}) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithTag(key, value string) *NotificationCostTrackingBuilder
- func (b *NotificationCostTrackingBuilder) WithTimestamp(timestamp time.Time) *NotificationCostTrackingBuilder
- type NotificationDelivery
- func (n *NotificationDelivery) BeforeCreate() error
- func (n *NotificationDelivery) BeforeUpdate() error
- func (n *NotificationDelivery) CanRetry() bool
- func (n *NotificationDelivery) IncrementAttempt()
- func (n *NotificationDelivery) MarkFailed(errorMsg string)
- func (n *NotificationDelivery) MarkPending()
- func (n *NotificationDelivery) MarkSent()
- func (NotificationDelivery) TableName() string
- func (n *NotificationDelivery) UpdateKeys()
- func (n *NotificationDelivery) Validate() error
- type NotificationFilter
- type NotificationLegacy
- type NotificationPreferences
- type NotificationTypeCostStats
- type NotificationUserCostStats
- type NumericIDMapping
- type OAuthApp
- type OAuthAuthSession
- func (o *OAuthAuthSession) Authorize()
- func (o *OAuthAuthSession) BeforeCreate() error
- func (o *OAuthAuthSession) BeforeUpdate() error
- func (o *OAuthAuthSession) CanAuthorize() bool
- func (o *OAuthAuthSession) GetContext(key string) (interface{}, bool)
- func (o *OAuthAuthSession) GetPK() string
- func (o *OAuthAuthSession) GetSK() string
- func (o *OAuthAuthSession) IsExpired() bool
- func (o *OAuthAuthSession) IsValid() bool
- func (o *OAuthAuthSession) RemainingTime() time.Duration
- func (o *OAuthAuthSession) SetContext(key string, value interface{})
- func (o *OAuthAuthSession) SetFlowStep(step string, data map[string]interface{})
- func (o *OAuthAuthSession) SetUser(username string)
- func (OAuthAuthSession) TableName() string
- func (o *OAuthAuthSession) Touch()
- func (o *OAuthAuthSession) UpdateKeys() error
- func (o *OAuthAuthSession) Validate() error
- type OAuthClient
- type OAuthDeviceSession
- type OAuthRefreshAuthority
- type OAuthRefreshFamilySlot
- type OAuthRefreshSuccessorArtifact
- type OAuthRefreshWalkBudget
- type OAuthState
- type Object
- type OptimizationDecision
- type OutboxItem
- type PasskeyRegistrationProof
- func (p *PasskeyRegistrationProof) BeforeCreate() error
- func (p *PasskeyRegistrationProof) BeforeUpdate() error
- func (p *PasskeyRegistrationProof) GetPK() string
- func (p *PasskeyRegistrationProof) GetSK() string
- func (p *PasskeyRegistrationProof) IsExpired(now time.Time) bool
- func (PasskeyRegistrationProof) TableName() string
- func (p *PasskeyRegistrationProof) UpdateKeys() error
- func (p *PasskeyRegistrationProof) Validate() error
- type PasswordReset
- type PatternCache
- type PatternFeedback
- type PatternPerformanceMetric
- type PatternStats
- type PatternTestResult
- type Poll
- type PollVote
- type PopularQueryCounter
- type PromoPackage
- type PromoPackageAsset
- type PromoReviewGrant
- type PromoReviewVerdict
- type ProviderAccount
- func (pa *ProviderAccount) BeforeCreate() error
- func (pa *ProviderAccount) BeforeUpdate() error
- func (pa *ProviderAccount) ClearPrimary()
- func (pa *ProviderAccount) GetDisplayName() string
- func (pa *ProviderAccount) HasValidToken() bool
- func (pa *ProviderAccount) IsTokenExpired() bool
- func (pa *ProviderAccount) MarkUsed()
- func (pa *ProviderAccount) NeedsRefresh() bool
- func (pa *ProviderAccount) SetPrimary()
- func (ProviderAccount) TableName() string
- func (pa *ProviderAccount) Validate() error
- type PublicKeyCache
- func (p *PublicKeyCache) ExtendTTL(duration time.Duration)
- func (p *PublicKeyCache) GetPK() string
- func (p *PublicKeyCache) GetPublicKeyPEM() []byte
- func (p *PublicKeyCache) GetSK() string
- func (p *PublicKeyCache) IsValid() bool
- func (p *PublicKeyCache) RecordFailure()
- func (p *PublicKeyCache) RecordSuccess()
- func (p *PublicKeyCache) ShouldRefresh() bool
- func (PublicKeyCache) TableName() string
- func (p *PublicKeyCache) UpdateKeys() error
- type Publication
- type PublicationMember
- type PushSubscription
- func (p *PushSubscription) BeforeCreate() error
- func (p *PushSubscription) BeforeUpdate() error
- func (p *PushSubscription) GetPK() string
- func (p *PushSubscription) GetSK() string
- func (PushSubscription) TableName() string
- func (p *PushSubscription) UpdateKeys() error
- func (p *PushSubscription) UpdateLastUsed()
- func (p *PushSubscription) Validate() error
- type PushSubscriptionAlerts
- type QualityChange
- type QualityCodecInfo
- type QualityMetric
- type QueryCacheEntry
- type QuotePermissions
- func (q *QuotePermissions) AddToBlockList(username string)
- func (q *QuotePermissions) ApplyVisibilityDefaults(visibility string)
- func (q *QuotePermissions) GetPK() string
- func (q *QuotePermissions) GetSK() string
- func (q *QuotePermissions) IsAllowed(quoterUsername string, isFollower bool, isMentioned bool) bool
- func (q *QuotePermissions) RemoveFromBlockList(username string)
- func (q *QuotePermissions) SetDefaults()
- func (QuotePermissions) TableName() string
- func (q *QuotePermissions) UpdateKeys() error
- type QuoteRelationship
- func (q *QuoteRelationship) GenerateID()
- func (q *QuoteRelationship) GetPK() string
- func (q *QuoteRelationship) GetSK() string
- func (q *QuoteRelationship) IsActive() bool
- func (QuoteRelationship) TableName() string
- func (q *QuoteRelationship) UpdateKeys() error
- func (q *QuoteRelationship) Withdraw()
- type RateLimitLockout
- type RateLimitViolation
- type Reaction
- type RealtimeStats
- type ReconnectionAttempt
- type RecoveryCode
- type RecoveryRequest
- type RecoveryToken
- type RefreshToken
- type RelationshipRecord
- func (r *RelationshipRecord) Accept()
- func (r *RelationshipRecord) BeforeCreate() error
- func (r *RelationshipRecord) BeforeUpdate() error
- func (r *RelationshipRecord) ExtractFollowerFromGSI() string
- func (r *RelationshipRecord) ExtractFollowerUsername() string
- func (r *RelationshipRecord) ExtractFollowingUsername() string
- func (r *RelationshipRecord) GetPK() string
- func (r *RelationshipRecord) GetSK() string
- func (r *RelationshipRecord) Reject()
- func (RelationshipRecord) TableName() string
- func (r *RelationshipRecord) UpdateKeys() error
- type RelationshipState
- type Relay
- type RelayBudget
- type RelayCost
- type RelayInfo
- type RelayMetrics
- type RelayOperationStats
- type RemoteActor
- type ReplySyncRecord
- func (r *ReplySyncRecord) BeforeCreate() error
- func (r *ReplySyncRecord) BeforeUpdate() error
- func (r *ReplySyncRecord) IsExpired() bool
- func (r *ReplySyncRecord) MarkFailed(errorMsg string)
- func (r *ReplySyncRecord) MarkPartial(fetched, failed int)
- func (r *ReplySyncRecord) MarkSuccess(fetched int)
- func (r *ReplySyncRecord) ShouldRetry() bool
- func (ReplySyncRecord) TableName() string
- func (r *ReplySyncRecord) UpdateKeys()
- type Report
- type ReportStats
- type Reputation
- type RetryPolicy
- type ReviewerStats
- func (r *ReviewerStats) CalculateAccuracyRate()
- func (r *ReviewerStats) CalculateTrustScore()
- func (r *ReviewerStats) EarnBadge(badge string) bool
- func (r *ReviewerStats) GetSpecialization() (category string, score float64)
- func (r *ReviewerStats) IsExperienced() bool
- func (r *ReviewerStats) IsTrusted() bool
- func (r *ReviewerStats) NeedsTraining() bool
- func (r *ReviewerStats) RecordReview(category string, wasAccurate bool, responseTime float64)
- func (ReviewerStats) TableName() string
- func (r *ReviewerStats) UpdateKeys()
- func (r *ReviewerStats) UpdateSpecializationScore(category string, recentAccuracy float64)
- type Revision
- type RevokedAccessToken
- type RouteDeliveryResult
- type RouteMetricsWindow
- type RouteRecommendation
- type ScheduledJobCategoryStats
- type ScheduledJobCostAggregation
- func (sjca *ScheduledJobCostAggregation) BeforeCreate() error
- func (sjca *ScheduledJobCostAggregation) BeforeUpdate() error
- func (sjca *ScheduledJobCostAggregation) GetPK() string
- func (sjca *ScheduledJobCostAggregation) GetSK() string
- func (ScheduledJobCostAggregation) TableName() string
- func (sjca *ScheduledJobCostAggregation) UpdateKeys() error
- func (sjca *ScheduledJobCostAggregation) Validate() error
- type ScheduledJobCostRecord
- func (sjcr *ScheduledJobCostRecord) AddTag(key, value string)
- func (sjcr *ScheduledJobCostRecord) BeforeCreate() error
- func (sjcr *ScheduledJobCostRecord) BeforeUpdate() error
- func (sjcr *ScheduledJobCostRecord) GetJobProperty(key string) (interface{}, bool)
- func (sjcr *ScheduledJobCostRecord) GetPK() string
- func (sjcr *ScheduledJobCostRecord) GetPerformanceMetric(key string) (float64, bool)
- func (sjcr *ScheduledJobCostRecord) GetSK() string
- func (sjcr *ScheduledJobCostRecord) SetJobProperty(key string, value interface{})
- func (sjcr *ScheduledJobCostRecord) SetPerformanceMetric(key string, value float64)
- func (ScheduledJobCostRecord) TableName() string
- func (sjcr *ScheduledJobCostRecord) UpdateKeys() error
- func (sjcr *ScheduledJobCostRecord) Validate() error
- type ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) Build() *ScheduledJobCostRecord
- func (builder *ScheduledJobCostRecordBuilder) ForJob(jobName, schedule string) *ScheduledJobCostRecordBuilder
- func (ScheduledJobCostRecordBuilder) TableName() string
- func (builder *ScheduledJobCostRecordBuilder) WithCascadingCosts(triggeredJobs []string, cascadingCost int64, downstreamOps int64) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithCategory(category, priority string) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithContext(environment, region, functionName, requestID string) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithCosts(...) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithDynamoDBUsage(readOps, writeOps int64, readCapacity, writeCapacity float64) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithError(errorMessage string, retryCount, maxRetries int) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithItemsProcessed(processed, skipped, errored int64) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithJobProperty(key string, value interface{}) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithLambdaUsage(invocations, durationMs int64, memoryMB int) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithPerformanceMetric(key string, value float64) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithStatus(status string) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithTag(key, value string) *ScheduledJobCostRecordBuilder
- func (builder *ScheduledJobCostRecordBuilder) WithTiming(scheduledTime, startTime, endTime time.Time) *ScheduledJobCostRecordBuilder
- type ScheduledJobEnvironmentStats
- type ScheduledJobScheduleStats
- type ScheduledStatus
- type SearchAnalytics
- type SearchBudget
- func (sb *SearchBudget) CanMakeRequest(operationType string, estimatedCostMicros int64) bool
- func (sb *SearchBudget) GetPK() string
- func (sb *SearchBudget) GetSK() string
- func (sb *SearchBudget) RecordUsage(operationType string, costMicros int64)
- func (SearchBudget) TableName() string
- func (sb *SearchBudget) UpdateKeys() error
- type SearchCache
- type SearchClickRate
- type SearchCostAggregation
- type SearchCostTracking
- type SearchEmbedding
- type SearchHistoryEntry
- type SearchQuery
- type SearchQueryStats
- type SearchResults
- func (s *SearchResults) AddAccount(account *activitypub.Actor)
- func (s *SearchResults) AddHashtag(hashtag *HashtagSearchResult)
- func (s *SearchResults) AddStatus(status *StatusSearchResult)
- func (s *SearchResults) Count() int
- func (s *SearchResults) IsEmpty() bool
- func (s *SearchResults) Merge(other *SearchResults)
- func (SearchResults) TableName() string
- func (s *SearchResults) TruncateToLimit(limit int)
- type SearchSuggestion
- type Series
- type Session
- func (s *Session) BeforeCreate() error
- func (s *Session) BeforeUpdate() error
- func (s *Session) GetContext(key string) (interface{}, bool)
- func (s *Session) HasScope(scope string) bool
- func (s *Session) IsExpired() bool
- func (s *Session) IsValid() bool
- func (s *Session) RemainingTime() time.Duration
- func (s *Session) Revoke(reason string)
- func (s *Session) SetContext(key string, value interface{})
- func (Session) TableName() string
- func (s *Session) Touch()
- func (s *Session) Validate() error
- func (s *Session) ValidateRequest(_, _ string) bool
- type SetupSession
- type SeveranceReason
- type SeveranceReconnectionAttempt
- func (r *SeveranceReconnectionAttempt) GetPK() string
- func (r *SeveranceReconnectionAttempt) GetSK() string
- func (r *SeveranceReconnectionAttempt) MarkCompleted(successCount, failureCount int)
- func (r *SeveranceReconnectionAttempt) MarkFailed(errorMessage string)
- func (r *SeveranceReconnectionAttempt) MarkInProgress()
- func (SeveranceReconnectionAttempt) TableName() string
- func (r *SeveranceReconnectionAttempt) UpdateKeys() error
- type SeveranceStatus
- type SeveredRelationship
- type Skill
- type SkillAssignment
- type SkillProposal
- type SkillProvenanceRef
- type SkillRevision
- type SkillRevisionFile
- type SocialRecoveryRequest
- func (s *SocialRecoveryRequest) AddVote(trusteeID string) bool
- func (s *SocialRecoveryRequest) Cancel()
- func (s *SocialRecoveryRequest) GetProgress() float64
- func (s *SocialRecoveryRequest) GetVoteCount() int
- func (s *SocialRecoveryRequest) IsActive() bool
- func (s *SocialRecoveryRequest) IsExpired() bool
- func (s *SocialRecoveryRequest) MarkExpired()
- func (SocialRecoveryRequest) TableName() string
- func (s *SocialRecoveryRequest) UpdateKeys()
- type Status
- func (s *Status) BeforeCreate() error
- func (s *Status) BeforeUpdate() error
- func (s *Status) CanBeReblogged() bool
- func (s *Status) CreateHashtagIndexRecords() []*StatusHashtagIndex
- func (s *Status) DeleteHashtagIndexRecords() []map[string]interface{}
- func (s *Status) GetAllHashtagIndexRecords() []*StatusHashtagIndex
- func (s *Status) GetAllRecipients() []string
- func (s *Status) GetPK() string
- func (s *Status) GetPrivacyScore() int
- func (s *Status) GetSK() string
- func (s *Status) GetVisibleRecipients(requestingActorID string) []string
- func (s *Status) HasHashtags() bool
- func (s *Status) HasMedia() bool
- func (s *Status) HasMentions() bool
- func (s *Status) HasSpecificRecipients() bool
- func (s *Status) IsConversation() bool
- func (s *Status) IsDeleted() bool
- func (s *Status) IsDirect() bool
- func (s *Status) IsFlagged() bool
- func (s *Status) IsPrivate() bool
- func (s *Status) IsPublic() bool
- func (s *Status) IsReblog() bool
- func (s *Status) IsRecipient(actorID string) bool
- func (s *Status) IsReply() bool
- func (s *Status) IsVisibleTo(actorID string) bool
- func (s *Status) RequiresFollowCheck() bool
- func (s *Status) SanitizeForActor(viewerID string) *Status
- func (s *Status) ShouldAppearInTimeline(timelineType string, viewerID string) bool
- func (s *Status) SyncTagFieldsFromNote()
- func (Status) TableName() string
- func (s *Status) UpdateKeys() error
- type StatusAttachment
- type StatusEngagement
- type StatusHashtagIndex
- type StatusMetadata
- func (sm *StatusMetadata) AddModerationFlag(flag string)
- func (sm *StatusMetadata) BeforeCreate() error
- func (sm *StatusMetadata) BeforeUpdate() error
- func (sm *StatusMetadata) DecrementReplyCount()
- func (sm *StatusMetadata) HasModerationFlag(flag string) bool
- func (sm *StatusMetadata) IncrementReplyCount()
- func (sm *StatusMetadata) IsPubliclyQuotable() bool
- func (sm *StatusMetadata) IsQuotable() bool
- func (sm *StatusMetadata) RemoveModerationFlag(flag string)
- func (sm *StatusMetadata) RestoreToQuotes()
- func (sm *StatusMetadata) SetQuoteType(quoteType string)
- func (sm *StatusMetadata) SetReplyCount(count int)
- func (StatusMetadata) TableName() string
- func (sm *StatusMetadata) UpdateKeys()
- func (sm *StatusMetadata) WithdrawFromQuotes()
- type StatusPin
- type StatusSearchOptions
- func (StatusSearchOptions) TableName() string
- func (o *StatusSearchOptions) Validate() error
- func (o *StatusSearchOptions) WithAccountID(accountID string) *StatusSearchOptions
- func (o *StatusSearchOptions) WithFollowingOnly() *StatusSearchOptions
- func (o *StatusSearchOptions) WithLanguage(language string) *StatusSearchOptions
- func (o *StatusSearchOptions) WithLimit(limit int) *StatusSearchOptions
- func (o *StatusSearchOptions) WithLocalOnly() *StatusSearchOptions
- func (o *StatusSearchOptions) WithMediaOnly() *StatusSearchOptions
- func (o *StatusSearchOptions) WithMinEngagement(minVal int) *StatusSearchOptions
- func (o *StatusSearchOptions) WithOffset(offset int) *StatusSearchOptions
- func (o *StatusSearchOptions) WithTimeRange(start, end time.Time) *StatusSearchOptions
- type StatusSearchResult
- type StatusTag
- type StatusTrend
- type StreamingCloudWatchMetrics
- func (s *StreamingCloudWatchMetrics) GetBestQuality() string
- func (s *StreamingCloudWatchMetrics) GetBestRegionQuality(region string) string
- func (s *StreamingCloudWatchMetrics) GetPK() string
- func (s *StreamingCloudWatchMetrics) GetSK() string
- func (s *StreamingCloudWatchMetrics) IsExpired() bool
- func (s *StreamingCloudWatchMetrics) SetConcurrentViewers(mediaID string, metrics ConcurrentViewerMetrics)
- func (s *StreamingCloudWatchMetrics) SetGeographicData(mediaID string, metrics map[string]GeographicMetric)
- func (s *StreamingCloudWatchMetrics) SetPerformanceMetrics(mediaID string, metrics StreamingPerformanceMetrics)
- func (s *StreamingCloudWatchMetrics) SetQualityBreakdown(mediaID string, metrics map[string]QualityMetric)
- func (s *StreamingCloudWatchMetrics) ShouldAdaptQuality(currentQuality string) (bool, string)
- func (StreamingCloudWatchMetrics) TableName() string
- func (s *StreamingCloudWatchMetrics) UpdateFreshness()
- func (s *StreamingCloudWatchMetrics) UpdateKeys() error
- type StreamingEvent
- type StreamingPerformanceMetrics
- type StreamingPreferences
- func (s *StreamingPreferences) GetPK() string
- func (s *StreamingPreferences) GetSK() string
- func (s *StreamingPreferences) SetBackupPreference()
- func (s *StreamingPreferences) SetCurrentPreference()
- func (s *StreamingPreferences) SetDevicePreference(deviceID string)
- func (s *StreamingPreferences) SetVersionedPreference()
- func (StreamingPreferences) TableName() string
- func (s *StreamingPreferences) UpdateKeys() error
- type TOCEntry
- type ThreadContext
- type ThreadNode
- func (n *ThreadNode) AddChild(childID string)
- func (n *ThreadNode) GetPK() string
- func (n *ThreadNode) GetSK() string
- func (n *ThreadNode) IncrementDescendantCount(count int)
- func (n *ThreadNode) IsLeaf() bool
- func (n *ThreadNode) IsRoot() bool
- func (ThreadNode) TableName() string
- func (n *ThreadNode) UpdateKeys() error
- func (n *ThreadNode) UpdatePath(parentPath string)
- type ThreadSync
- func (t *ThreadSync) AddMissingReply(replyID string)
- func (t *ThreadSync) GetPK() string
- func (t *ThreadSync) GetSK() string
- func (t *ThreadSync) IsRecentlyCompleted() bool
- func (t *ThreadSync) MarkCompleted()
- func (t *ThreadSync) MarkFailed(errorMessage string)
- func (t *ThreadSync) MarkSyncing()
- func (t *ThreadSync) RemoveMissingReply(replyID string)
- func (ThreadSync) TableName() string
- func (t *ThreadSync) UpdateKeys() error
- type ThreatIndicator
- type ThreatIntel
- type TimeRange
- type Timeline
- func (t *Timeline) BeforeCreate() error
- func (t *Timeline) BeforeUpdate() error
- func (t *Timeline) GetPK() string
- func (t *Timeline) GetSK() string
- func (t *Timeline) GetSortKey() string
- func (t *Timeline) GetTimelineKey() string
- func (t *Timeline) IsDirect() bool
- func (t *Timeline) IsDirectTimeline() bool
- func (t *Timeline) IsExpired() bool
- func (t *Timeline) IsHashtagTimeline() bool
- func (t *Timeline) IsHomeTimeline() bool
- func (t *Timeline) IsListTimeline() bool
- func (t *Timeline) IsPrivate() bool
- func (t *Timeline) IsPublic() bool
- func (t *Timeline) IsPublicTimeline() bool
- func (t *Timeline) IsUnlisted() bool
- func (t *Timeline) SetTTL(expiresAt time.Time)
- func (Timeline) TableName() string
- func (t *Timeline) UpdateKeys() error
- type TimelineEntry
- type TimelineMarker
- type Tombstone
- func (t *Tombstone) BeforeCreate() error
- func (t *Tombstone) GetDeletedBy() string
- func (t *Tombstone) GetFormerType() string
- func (t *Tombstone) GetOriginalID() string
- func (t *Tombstone) GetPK() string
- func (t *Tombstone) GetSK() string
- func (t *Tombstone) IsTombstone() bool
- func (t *Tombstone) ShouldCleanup() bool
- func (Tombstone) TableName() string
- func (t *Tombstone) UpdateKeys() error
- type TrainingMetrics
- type TranscodingJob
- func (tj *TranscodingJob) AddCost(service string, costMicros int64)
- func (tj *TranscodingJob) AddOutputVariant(quality, format string, size int64, s3Key string)
- func (tj *TranscodingJob) BeforeCreate() error
- func (tj *TranscodingJob) BeforeUpdate() error
- func (tj *TranscodingJob) Duration() time.Duration
- func (tj *TranscodingJob) GetCostEfficiency() map[string]float64
- func (tj *TranscodingJob) GetPK() string
- func (tj *TranscodingJob) GetQualityBreakdown() map[string]map[string]interface{}
- func (tj *TranscodingJob) GetSK() string
- func (tj *TranscodingJob) GetServiceCostBreakdown() map[string]int64
- func (tj *TranscodingJob) IsCompleted() bool
- func (tj *TranscodingJob) SetCompleted()
- func (tj *TranscodingJob) SetFailed(errorMessage string)
- func (TranscodingJob) TableName() string
- func (tj *TranscodingJob) UpdateKeys() error
- func (tj *TranscodingJob) Validate() error
- type TrendingHashtag
- type TrendingLink
- func (t *TrendingLink) CalculateTrendingScore()
- func (t *TrendingLink) FormatTrendingSummary() string
- func (t *TrendingLink) GetDisplayTitle() string
- func (t *TrendingLink) IsStillTrending(minScore float64, maxAge time.Duration) bool
- func (TrendingLink) TableName() string
- func (t *TrendingLink) UpdateKeys()
- type TrendingStatus
- type TrustCategory
- type TrustEvidence
- type TrustRelationship
- type TrustScore
- type TrustUpdate
- type Trustee
- type TrusteeConfig
- func (t *TrusteeConfig) AddPermission(permission string) bool
- func (t *TrusteeConfig) CanPerformAction(action string) bool
- func (t *TrusteeConfig) Confirm()
- func (t *TrusteeConfig) FormatDisplayName() string
- func (t *TrusteeConfig) GetTrustLevelPriority() int
- func (t *TrusteeConfig) IsActive() bool
- func (t *TrusteeConfig) IsModerationTrustee() bool
- func (t *TrusteeConfig) IsRecoveryTrustee() bool
- func (t *TrusteeConfig) RecordUsage()
- func (t *TrusteeConfig) RemovePermission(permission string) bool
- func (t *TrusteeConfig) SetPermissions(permissions []string)
- func (TrusteeConfig) TableName() string
- func (t *TrusteeConfig) UpdateKeys()
- type UpdateHistory
- type UploadGrant
- func (g *UploadGrant) Expired(now time.Time) bool
- func (g *UploadGrant) GetPK() string
- func (g *UploadGrant) GetSK() string
- func (g *UploadGrant) IsFailedDigest() bool
- func (g *UploadGrant) IsMinted() bool
- func (g *UploadGrant) IsUsed() bool
- func (g *UploadGrant) StatusClassification(now time.Time) string
- func (UploadGrant) TableName() string
- func (g *UploadGrant) UpdateKeys() error
- type User
- func (u *User) BeforeCreate() error
- func (u *User) BeforeUpdate() error
- func (u *User) GetPK() string
- func (u *User) GetSK() string
- func (u *User) HasEmail() bool
- func (u *User) HasPassword() bool
- func (u *User) IsActive() bool
- func (u *User) IsAdmin() bool
- func (u *User) IsModerator() bool
- func (User) TableName() string
- func (u *User) UpdateKeys() error
- type UserAppConsent
- type UserConversationFolder
- type UserConversationState
- func (s *UserConversationState) BeforeCreate() error
- func (s *UserConversationState) BeforeUpdate() error
- func (s *UserConversationState) GetPK() string
- func (s *UserConversationState) GetSK() string
- func (s *UserConversationState) LegacyListCursor() string
- func (UserConversationState) TableName() string
- func (s *UserConversationState) UnreadQueryVisible() bool
- func (s *UserConversationState) UpdateKeys() error
- type UserDomainBlock
- type UserLogin
- type UserMediaConfig
- func (umc *UserMediaConfig) AddMonthlyUsage(bytes int64)
- func (umc *UserMediaConfig) BeforeCreate() error
- func (umc *UserMediaConfig) BeforeUpdate() error
- func (umc *UserMediaConfig) CanAfford(costMicros int64, costType string) bool
- func (umc *UserMediaConfig) GetMaxSizeForType(contentType string) int64
- func (umc *UserMediaConfig) GetPK() string
- func (umc *UserMediaConfig) GetSK() string
- func (umc *UserMediaConfig) IsAllowedContentType(contentType string) bool
- func (umc *UserMediaConfig) IsExpired() bool
- func (umc *UserMediaConfig) IsTrialExpired() bool
- func (umc *UserMediaConfig) IsWithinStorageLimit(additionalBytes int64) bool
- func (umc *UserMediaConfig) ResetMonthlyCounters()
- func (umc *UserMediaConfig) ShouldResetCounters() bool
- func (UserMediaConfig) TableName() string
- func (umc *UserMediaConfig) UpdateKeys() error
- func (umc *UserMediaConfig) UpdateStorageUsage(deltaBytes int64)
- func (umc *UserMediaConfig) UpgradePlan(newTier string, expiresAt *time.Time) error
- func (umc *UserMediaConfig) Validate() error
- type UserPreference
- type UserPreferences
- type UserPreferencesStorage
- type VAPIDKeyRecord
- type Vouch
- type WalletChallenge
- type WalletCredential
- type WalletIndex
- type WebAuthnChallenge
- type WebAuthnCredential
- type WebSocketConnection
- func (w *WebSocketConnection) CalculateConnectionQuality() float64
- func (w *WebSocketConnection) GetPK() string
- func (w *WebSocketConnection) GetSK() string
- func (w *WebSocketConnection) IncrementError(errorMsg string)
- func (w *WebSocketConnection) IsActive(threshold time.Duration) bool
- func (w *WebSocketConnection) IsHealthy() bool
- func (w *WebSocketConnection) RecordMessage(sent bool, bytes int64)
- func (w *WebSocketConnection) RecordPing()
- func (w *WebSocketConnection) RecordPong()
- func (w *WebSocketConnection) ShouldRetry() bool
- func (w *WebSocketConnection) TableName() string
- func (w *WebSocketConnection) UpdateKeys() error
- func (w *WebSocketConnection) UpdateState(newState ConnectionState)
- type WebSocketCostAggregation
- func (w *WebSocketCostAggregation) BeforeCreate() error
- func (w *WebSocketCostAggregation) BeforeUpdate() error
- func (w *WebSocketCostAggregation) GetPK() string
- func (w *WebSocketCostAggregation) GetSK() string
- func (WebSocketCostAggregation) TableName() string
- func (w *WebSocketCostAggregation) UpdateKeys() error
- func (w *WebSocketCostAggregation) Validate() error
- type WebSocketCostBreakdown
- type WebSocketCostBudget
- func (w *WebSocketCostBudget) BeforeCreate() error
- func (w *WebSocketCostBudget) BeforeUpdate() error
- func (w *WebSocketCostBudget) GetPK() string
- func (w *WebSocketCostBudget) GetSK() string
- func (WebSocketCostBudget) TableName() string
- func (w *WebSocketCostBudget) UpdateKeys() error
- func (w *WebSocketCostBudget) Validate() error
- type WebSocketCostRecord
- func (w *WebSocketCostRecord) AddTag(key, value string)
- func (w *WebSocketCostRecord) BeforeCreate() error
- func (w *WebSocketCostRecord) BeforeUpdate() error
- func (w *WebSocketCostRecord) GetPK() string
- func (w *WebSocketCostRecord) GetProperty(key string) (interface{}, bool)
- func (w *WebSocketCostRecord) GetSK() string
- func (w *WebSocketCostRecord) SetProperty(key string, value interface{})
- func (WebSocketCostRecord) TableName() string
- func (w *WebSocketCostRecord) UpdateKeys() error
- func (w *WebSocketCostRecord) Validate() error
- type WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) Build() *WebSocketCostRecord
- func (b *WebSocketCostRecordBuilder) ForOperation(operationType string) *WebSocketCostRecordBuilder
- func (WebSocketCostRecordBuilder) TableName() string
- func (b *WebSocketCostRecordBuilder) WithClient(clientIP, userAgent, source, authMethod string) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithConnection(connectionID, userID, username string) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithCosts(breakdown *WebSocketCostBreakdown) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithDuration(durationMs int64) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithMessages(count int, sizeBytes int64) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithPerformance(processingTimeMs, responseLatencyMs int64, memoryMB float64) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithProperty(key string, value interface{}) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithService(serviceName, functionName, requestID string) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithStreams(activeStreams, streamTypes []string) *WebSocketCostRecordBuilder
- func (b *WebSocketCostRecordBuilder) WithTag(key, value string) *WebSocketCostRecordBuilder
- type WebSocketEventConnection
- type WebSocketEventSubscription
- type WebSocketSubscription
- type WebSocketTierCostStats
- type WebhookDelivery
- func (w *WebhookDelivery) CanRetry() bool
- func (w *WebhookDelivery) GetPK() string
- func (w *WebhookDelivery) GetSK() string
- func (w *WebhookDelivery) IsComplete() bool
- func (w *WebhookDelivery) MarkFailed(errorMessage, errorType string, responseCode int, responseBody string, ...)
- func (w *WebhookDelivery) MarkStarted()
- func (w *WebhookDelivery) MarkSuccess(responseCode int, responseBody string, responseHeaders map[string]string, ...)
- func (w *WebhookDelivery) ShouldRetry() bool
- func (WebhookDelivery) TableName() string
- func (w *WebhookDelivery) UpdateKeys() error
- type WeeklyActivity
- func (w *WeeklyActivity) GetAverageDaily() float64
- func (w *WeeklyActivity) GetPK() string
- func (w *WeeklyActivity) GetSK() string
- func (w *WeeklyActivity) GetTotalActivity() int64
- func (w *WeeklyActivity) GetWeekEnd() time.Time
- func (w *WeeklyActivity) GetWeekStart() time.Time
- func (w *WeeklyActivity) IncrementLogins(count int64)
- func (w *WeeklyActivity) IncrementRegistrations(count int64)
- func (w *WeeklyActivity) IncrementStatuses(count int64)
- func (w *WeeklyActivity) IsActive() bool
- func (w *WeeklyActivity) Merge(other *WeeklyActivity)
- func (WeeklyActivity) TableName() string
- func (w *WeeklyActivity) UpdateKeys() error
Constants ¶
const ( MemoryEventCreate = "create" MemoryEventCorrection = "correction" MemoryEventRetraction = "retraction" MemoryEventTombstone = "tombstone" )
Memory event types for agent timeline-as-memory indexing.
const ( AgentShareGrantSKPrefix = "AGENT_SHARE#GRANTEE#" AgentShareGrantGranteeGSI2Prefix = "AGENT_SHARE#GRANTEE#" )
const ( BookmarkRecordTypeTime = "TIME" BookmarkRecordTypeObject = "OBJECT" )
BookmarkRecordType identifies the storage strategy used for a bookmark record.
const ( BookmarkSortKeyPrefixTime = bookmarkKeyPrefixTime BookmarkSortKeyPrefixObject = bookmarkKeyPrefixObject BookmarkPartitionPrefix = bookmarkKeyPrefixPK )
Bookmark key prefixes exported for repository logic.
const ( CollectionFollowers = "followers" CollectionFollowing = "following" CollectionFeatured = "featured" CollectionLikes = "likes" )
Common collection types
const ( // SKMetadata is used for metadata records SKMetadata = "METADATA" // SKConfig is used for configuration records SKConfig = "CONFIG" // SKToken is used for token records SKToken = "TOKEN" // SKStats is used for statistics records SKStats = "STATS" // SKState is used for state records SKState = "STATE" // SKProfile is used for profile records SKProfile = "PROFILE" // SKInfo is used for info records SKInfo = "INFO" // SKEntry is used for entry records SKEntry = "ENTRY" // SKCurrent is used for current/active records SKCurrent = "CURRENT" // SKCode is used for code records SKCode = "CODE" )
Common SK (Sort Key) constants used across multiple models
const ( // User-related key patterns KeyPatternUser = "USER#%s" KeyPatternUserPins = "USER#%s#PINS" KeyPatternUserScheduled = "USER#%s#SCHEDULED" // Actor-related key patterns KeyPatternActor = "ACTOR#%s" KeyPatternActorBlocks = "ACTOR#%s#BLOCKS" // Status-related key patterns KeyPatternStatus = "STATUS#%s" KeyPatternStatusMeta = "STATUS_META#%s" // Object-related key patterns KeyPatternObject = "OBJECT#%s" KeyPatternObjectNotes = "OBJECT#%s#NOTES" // Note-related key patterns KeyPatternNote = "NOTE#%s" // Device-related key patterns KeyPatternDevice = "DEVICE#%s" // Connection-related key patterns KeyPatternConnection = "CONNECTION#%s" // Session-related key patterns KeyPatternSession = "SESSION#%s" // Conversation-related key patterns KeyPatternConversation = "CONVERSATION#%s" // List-related key patterns KeyPatternList = "LIST#%s" // Hashtag-related key patterns KeyPatternHashtag = "HASHTAG#%s" KeyPatternHashtagSearch = "HASHTAG_SEARCH#%s" // Media-related key patterns KeyPatternMedia = "MEDIA#%s" KeyPatternMediaJob = "JOB#%s" KeyPatternMediaSpending = "MEDIA_SPENDING#%s" KeyPatternSpendingTxn = "SPENDING_TXN#%s" KeyPatternTranscodingJob = "TRANSCODING_JOB#%s" KeyPatternMediaIdempotency = "MEDIA_IDEM#%s" KeyPatternMediaBudget = "MEDIA_BUDGET#%s" )
Common key pattern prefixes used for PK and GSI keys
const ( // CostDriverPK is the partition key for cost drivers CostDriverPK = "COST#DRIVER" // CostProjectionPK is the partition key for cost projections CostProjectionPK = "COST#PROJECTION" // FederationStatsPK is the partition key for federation stats FederationStatsPK = "FEDERATION#STATS" // TrendIncreasing indicates an increasing trend TrendIncreasing = "increasing" // TrendDecreasing indicates a decreasing trend TrendDecreasing = "decreasing" // TrendStable indicates a stable trend TrendStable = "stable" )
Cost tracking key patterns
const ( ResourceStorage = "storage" ResourceCompute = "compute" ResourceBandwidth = "bandwidth" ResourceLambda = "lambda" ResourceProcessing = "processing" )
Resource category constants
const ( PeriodRaw = "raw" Period5Min = "5min" PeriodHour = "hour" PeriodDay = "day" PeriodWeek = "week" PeriodMonth = "month" PeriodMonthly = "monthly" PeriodHourly = "hourly" PeriodDaily = "daily" PeriodWeekly = "weekly" )
Period constants
const ( StatusActive = "active" StatusPending = "pending" StatusHealthy = "healthy" StatusWarning = "warning" StatusCritical = "critical" StatusFailed = "failed" StatusProcessing = "processing" StatusCompleted = "completed" StatusComplete = "complete" StatusSuccess = "success" StatusDisabled = "disabled" StatusTimeout = "timeout" StatusError = "error" StatusCancelled = "cancelled" StatusReady = "ready" StatusRetry = "retry" )
Status constants
const ( MediaStatusPending = "pending" MediaStatusProcessing = "processing" MediaStatusCompleted = "completed" MediaStatusFailed = "failed" MediaStatusCancelled = "cancelled" MediaStatusReady = "ready" )
Media processing status constants
const ( MediaCostUpload = "upload" MediaCostStorage = "storage" MediaCostTranscode = "transcode" MediaCostThumbnail = "thumbnail" MediaCostModeration = "moderation" MediaCostAnalysis = "analysis" MediaCostDelivery = "delivery" )
Media processing cost categories
const ( MediaTaskUpload = "upload" MediaTaskResize = "resize" MediaTaskThumbnail = "thumbnail" MediaTaskBlurhash = "blurhash" MediaTaskDimensions = "dimensions" MediaTaskDuration = "duration" MediaTaskTranscode = "transcode" MediaTaskWaveform = "waveform" MediaTaskMetadata = "metadata" MediaTaskEXIF = "exif" MediaTaskModeration = "moderation" )
Media processing task types
const ( CostTierLow = "low" CostTierMedium = "medium" CostTierHigh = "high" CostTierPremium = "premium" )
Cost tier constants
const ( TrusteeConfigPK = "TRUSTEE#CONFIG" ModerationTypeEvent = "EVENT" TypeFollowed = "followed" TypeEmail = "email" TimelinePublic = "PUBLIC" )
Other constants
const ( EntityTypeUser = "user" EntityTypeScheduledStatus = "scheduled_status" EntityTypeStatus = "status" EntityTypeAccount = "account" )
Entity type constants
const ( // On-demand pricing (as of 2024) // Read: $0.25 per million read request units = 0.025 cents per 1000 = 25 microcents per 1000 ReadCostMicroCentsPerUnit = 25 // per 1000 units // Write: $1.25 per million write request units = 0.125 cents per 1000 = 125 microcents per 1000 WriteCostMicroCentsPerUnit = 125 // per 1000 units )
CalculateDynamoDBCost calculates the cost based on AWS pricing Prices are in microcents per unit for precision
const ( DeliveryStatusPending = "pending" DeliveryStatusDelivered = "delivered" DeliveryStatusFailed = "failed" )
Delivery status constants
const ( // DirectMessageMigrationStatePK is the singleton partition key for DM migration state. DirectMessageMigrationStatePK = "DM_MIGRATION#DIRECT_MESSAGE_STATE" // DirectMessageMigrationStateSK is the singleton sort key for DM migration state. DirectMessageMigrationStateSK = "STATE" )
const ( DomainBlockSeveritySilence = "silence" DomainBlockSeveritySuspend = "suspend" )
Domain block severity constants
const ( // CircuitBreakerStateOpen represents an open circuit breaker state CircuitBreakerStateOpen = "open" // CircuitBreakerStateClosed represents a closed circuit breaker state CircuitBreakerStateClosed = "closed" // CircuitBreakerStateHalfOpen represents a half-open circuit breaker state CircuitBreakerStateHalfOpen = "half-open" )
const ( FollowStatePending = "pending" FollowStateAccepted = "accepted" FollowStateRejected = "rejected" )
Follow state constants
const ( // IndexGSI1 is the shared "gsi1" index used by models for state/time queries (e.g., username search, inbox/timeline, alert and federation state) as documented in struct tags. IndexGSI1 = "gsi1" // IndexGSI2 is the shared "gsi2" index used where models tag status/retry or secondary time-series lookups. IndexGSI2 = "gsi2" // IndexGSI3 is the shared "gsi3" index used by models for role/feature and alert status groupings. IndexGSI3 = "gsi3" // IndexGSI4 is the shared "gsi4" index used by models for reply/popularity timelines and related ranking buckets. IndexGSI4 = "gsi4" // IndexGSI5 is the shared "gsi5" index used by models for handle prefix search and recency windows. IndexGSI5 = "gsi5" // IndexGSI6 is the shared "gsi6" index reserved by models for retry/backoff tracking. IndexGSI6 = "gsi6" // IndexGSI7 is the shared "gsi7" index used by models for URL/canonical resource lookups. IndexGSI7 = "gsi7" // IndexGSI8 is the shared "gsi8" index used by models for analytics/time-window queries. IndexGSI8 = "gsi8" // IndexGSI9 is the shared "gsi9" index reserved for future model metadata and rollout gating. IndexGSI9 = "gsi9" // IndexOAuthClients is the dedicated index for OAuth client listings as provisioned in infrastructure. IndexOAuthClients = "oauth-clients-index" )
Central registry of DynamoDB GSI names to prevent drift between CDK (gsi1...gsi9) and DynamORM callers. Names mirror the lowercase index identifiers used in struct tags under pkg/storage/models.
const ( // SKTrustConfig is the sort key for the trust configuration record (PK="INSTANCE#CONFIG"). SKTrustConfig = "TRUST_CONFIG" // SKTranslationConfig is the sort key for the translation configuration record (PK="INSTANCE#CONFIG"). SKTranslationConfig = "TRANSLATION_CONFIG" // SKTipsConfig is the sort key for the tips configuration record (PK="INSTANCE#CONFIG"). SKTipsConfig = "TIPS_CONFIG" // SKAIConfig is the sort key for the AI configuration record (PK="INSTANCE#CONFIG"). SKAIConfig = "AI_CONFIG" // SKWellKnownLesserSoulAgent is the sort key for the soul HTTPS proof record (PK="INSTANCE#CONFIG"). SKWellKnownLesserSoulAgent = "WELL_KNOWN_LESSER_SOUL_AGENT" // SKSoulENSChannelPrefix is the sort-key prefix for per-agent soul ENS channel config records. SKSoulENSChannelPrefix = "SOUL_ENS_CHANNEL#" // SKSoulBodyBindingPrefix is the sort-key prefix for per-agent soul/body binding records. SKSoulBodyBindingPrefix = "SOUL_BODY_BINDING#" // SKSoulBodyBindingUsername is the sort key for username reverse-index records. SKSoulBodyBindingUsername = "SOUL_BODY_BINDING" )
const ( // PKSoulBindingIdempotencyPrefix scopes soul-binding idempotency receipts by authenticated caller. PKSoulBindingIdempotencyPrefix = "SOUL_BINDING_IDEMPOTENCY#" // SKSoulBindingIdempotencyKeyPrefix scopes one idempotency key receipt under a caller partition. SKSoulBindingIdempotencyKeyPrefix = "KEY#" )
const ( // SoulENSChainSepolia publishes the ENS channel for Sepolia CCIP-read resolution. SoulENSChainSepolia = "sepolia" // SoulENSChainMainnet publishes the ENS channel for Ethereum mainnet CCIP-read resolution. SoulENSChainMainnet = "mainnet" )
const ( // MissingReplyStatusPending indicates the reply hasn't been fetched yet MissingReplyStatusPending = "pending" // MissingReplyStatusFetching indicates the reply is currently being fetched MissingReplyStatusFetching = "fetching" // MissingReplyStatusFailed indicates the reply fetch failed MissingReplyStatusFailed = "failed" // MissingReplyStatusResolved indicates the reply was successfully fetched MissingReplyStatusResolved = "resolved" )
const ( // FailureReasonDeleted indicates the reply was deleted (410 Gone) FailureReasonDeleted = "deleted" // FailureReasonNotFound indicates the reply was not found (404) FailureReasonNotFound = "not_found" // FailureReasonForbidden indicates access was forbidden (403) FailureReasonForbidden = "forbidden" // FailureReasonTimeout indicates the request timed out FailureReasonTimeout = "timeout" // FailureReasonUnreachable indicates the instance was unreachable FailureReasonUnreachable = "unreachable" // FailureReasonInvalid indicates the response was invalid FailureReasonInvalid = "invalid" )
Failure reason constants
const ( // Push notification costs (estimates) PushCostPerMessage = 5000 // $0.00005 per notification = 5 micro-cents // WebSocket costs (API Gateway + Lambda) WebSocketCostPerMessage = 1000 // $0.00001 per message = 1 micro-cent // Lambda costs (per invocation + duration) LambdaCostPerInvocation = 20 // $0.0000002 per invocation = 0.02 micro-cents (rounded to 0.2) LambdaCostPerGBSecond = 1667 // $0.0000166667 per GB-second = 1.67 micro-cents // DynamoDB costs (on-demand pricing) DynamoDBReadCostPerRCU = 25 // $0.25 per million RCUs = 0.25 micro-cents per RCU DynamoDBWriteCostPerWCU = 125 // $1.25 per million WCUs = 1.25 micro-cents per WCU )
Predefined cost constants (in micro-cents)
const ( // KeyPatternPasskeyRegistrationProof is the canonical PK pattern for passkey signup proofs. //nolint:gosec // This is a DynamoDB partition-key format string, not credential material. KeyPatternPasskeyRegistrationProof = "PASSKEY_REGISTRATION_PROOF#%s" // SKPasskeyRegistrationProof is the canonical SK for passkey signup proofs. SKPasskeyRegistrationProof = "PROOF" // DefaultPasskeyRegistrationProofTTL keeps proofs short-lived and self-cleaning. DefaultPasskeyRegistrationProofTTL = 10 * time.Minute )
const ( PromoPackageStatusDraft = "draft" PromoPackageStatusReleasing = "releasing" PromoPackageStatusReleased = "released" )
Promo package status values. A package is composed in DRAFT and moves to RELEASED exactly once when the release transition stamps the created outbound Status ID; re-release of a released package is refused. RELEASING is the transient pre-stamp state held between the version-conditioned release reservation and the final released stamp. A package left in RELEASING is in one of two windows: before the outbound Status was created (crash or create failure — no post exists, revert to DRAFT), or after the Status was created but before the final stamp (stamp failure — the post IS live and its ID is surfaced via PromoPackageStampError for operator reconciliation). Release is refused while the reservation is held; see the release recovery runbook.
const ( PromoPackageVisibilityPublic = "public" PromoPackageVisibilityUnlisted = "unlisted" )
Promo package visibility values. Issue #1446 scopes promo attachment to public and unlisted posts only; private and direct posts are structurally rejected at compose and re-checked at release.
const ( PromoPackageReviewApproved = "APPROVED" PromoPackageReviewChangesRequested = "CHANGES_REQUESTED" // PromoPackageGrantLifetime bounds every promo review grant, matching the // M2 draft-review posture: grants are cheap, ephemeral assignments refreshed // on re-share, and an unbounded grant would let a stale reviewer assignment // authorize package reads and approval forever. PromoPackageGrantLifetime = 7 * 24 * time.Hour )
Promo review verdict values mirror the draft-review vocabulary.
const ( RelationshipPending = "pending" RelationshipAccepted = "accepted" RelationshipRejected = "rejected" )
Follow relationship state constants (from legacy)
const ( // Lambda pricing (per 1ms, 128MB) LambdaCostPerMSMicroCents = 2 // Approximately $0.0000000021 per ms // DynamoDB on-demand pricing (per 1000 units) DynamoDBReadCostMicroCentsPerUnit = 25 // $0.25 per million reads = 25 microcents per 1000 DynamoDBWriteCostMicroCentsPerUnit = 125 // $1.25 per million writes = 125 microcents per 1000 // SQS pricing (per 1 million requests) SQSCostMicroCentsPerMessage = 40 // $0.40 per million = 40 microcents per 1000 // S3 pricing (per 1000 requests) S3GetCostMicroCentsPerRequest = 40 // $0.0004 per 1000 GET requests S3PutCostMicroCentsPerRequest = 500 // $0.005 per 1000 PUT requests // CloudWatch Logs pricing (per GB) CloudWatchLogsCostMicroCentsPerMB = 50 // $0.50 per GB = 50 microcents per MB // Data transfer pricing (per GB) DataTransferCostMicroCentsPerMB = 9 // $0.09 per GB = 9 microcents per MB )
Common AWS pricing constants for cost calculations (in microcents)
const ( // SKSkill is the root sort key for a canonical skill authority record. SKSkill = "SKILL" // SKSkillRevisionPrefix is the sort-key prefix for canonical skill revisions. SKSkillRevisionPrefix = "REVISION#" // SKSkillProposal is the sort key for proposal records. SKSkillProposal = "PROPOSAL" // SKSkillAssignmentPrefix is the sort-key prefix for skill assignments under a subject partition. SKSkillAssignmentPrefix = "SKILL#" )
const ( // SkillStatusDraft indicates a canonical skill record exists but has no exposed approved revision yet. SkillStatusDraft = "draft" // SkillStatusActive indicates a canonical skill has at least one active revision or assignment path. SkillStatusActive = "active" // SkillStatusArchived indicates a canonical skill is retained but no longer assignable by default. SkillStatusArchived = "archived" )
const ( // SkillRevisionStatusDraft indicates a revision is still being formed inside Lesser. SkillRevisionStatusDraft = "draft" // SkillRevisionStatusProposed indicates a revision is ready for a later approval flow. SkillRevisionStatusProposed = "proposed" // SkillRevisionStatusApproved indicates a revision has passed a later approval flow. SkillRevisionStatusApproved = "approved" // SkillRevisionStatusSuperseded indicates a revision was replaced by a newer approved revision. SkillRevisionStatusSuperseded = "superseded" // SkillRevisionStatusRevoked indicates a revision should no longer be used. SkillRevisionStatusRevoked = "revoked" )
const ( // SkillProposalStatusProposed indicates a proposal is awaiting review. SkillProposalStatusProposed = "proposed" // SkillProposalStatusAccepted indicates a proposal produced or will produce a canonical revision. SkillProposalStatusAccepted = "accepted" // SkillProposalStatusRejected indicates a proposal was rejected. SkillProposalStatusRejected = "rejected" // SkillProposalStatusWithdrawn indicates a proposal was withdrawn before approval. SkillProposalStatusWithdrawn = "withdrawn" )
const ( // SkillAssignmentStatusActive indicates an assignment currently participates in effective resolution. SkillAssignmentStatusActive = "active" // SkillAssignmentStatusPending indicates an assignment is staged but not effective yet. SkillAssignmentStatusPending = "pending" // SkillAssignmentStatusRevoked indicates an assignment was explicitly revoked. SkillAssignmentStatusRevoked = "revoked" )
const ( // SkillExposurePublic means the skill can be exposed publicly once approved. SkillExposurePublic = "public" // SkillExposureInstance means the skill is visible within the local Lesser instance. SkillExposureInstance = "instance" // SkillExposurePrivate means the skill is only visible to explicitly assigned/private principals. SkillExposurePrivate = "private" )
const ( // SkillSourceTypeLocalFile records SKILL.md seed material imported from a repo/workspace. SkillSourceTypeLocalFile = "local_file" // SkillSourceTypeHostConversation records lesser-host mint conversation provenance without making host canonical. SkillSourceTypeHostConversation = "host_conversation" // SkillSourceTypeManual records operator or maintainer-created skill material. SkillSourceTypeManual = "manual" // SkillSourceTypeProposal records provenance that points at a Lesser-owned SkillProposal. SkillSourceTypeProposal = "proposal" // SkillSourceTypeApproval records provenance that points at a principal approval artifact. SkillSourceTypeApproval = "approval" )
const ( // SkillAssignmentSubjectInstance assigns a skill at instance scope. SkillAssignmentSubjectInstance = "instance" // SkillAssignmentSubjectActor assigns a skill to a local actor/body. SkillAssignmentSubjectActor = "actor" // SkillAssignmentSubjectPrincipal assigns a skill to an approving or owning principal. SkillAssignmentSubjectPrincipal = "principal" )
const ( // SkillApprovalAuthorityAdmin means a local Lesser admin approved the revision. SkillApprovalAuthorityAdmin = "admin" // SkillApprovalAuthorityPrincipal means the named principal approved the revision. SkillApprovalAuthorityPrincipal = "principal" // SkillApprovalAuthorityInstance means instance-level governance approved the revision. SkillApprovalAuthorityInstance = "instance" )
const ( VisibilityPublic = "public" VisibilityUnlisted = "unlisted" VisibilityPrivate = "private" VisibilityDirect = "direct" )
Visibility constants
const ( // UploadGrantStatusMinted is the initial state: the presigned PUT is valid // and a finalize may still consume the grant. UploadGrantStatusMinted = "MINTED" // UploadGrantStatusUsed records a successful finalize: the grant was // consumed exactly once and the verified bytes became an editorial asset. UploadGrantStatusUsed = "USED" // UploadGrantStatusFailedDigest records a finalize whose uploaded bytes did // not match the declared hash (or violated the declared size/type bounds). // The grant is consumed and the unverified object is deleted. UploadGrantStatusFailedDigest = "FAILED_DIGEST" )
Upload grant lifecycle states. EXPIRED is derived at read time from the bounded expiry (mirroring the review-grant fail-closed discipline); the stored states are MINTED, USED, and FAILED_DIGEST.
const ( // API Gateway WebSocket pricing (as of 2024) // Connection minutes: $0.25 per million minutes = 0.00000025 per minute = 0.25 microcents per minute APIGatewayConnectionCostPerMinute = 25 // microcents per 100 minutes (for precision) // Messages: $1.00 per million messages = 0.000001 per message = 1 microcent per message APIGatewayMessageCostPerMessage = 1 // microcent per message // Lambda costs (example: $0.0000166667 per GB-second) // For 512MB Lambda: $0.0000083334 per invocation-second = 8.3334 microcents per second LambdaCostPerSecond512MB = 8334 // microcents per 1000 seconds (for precision) // Data transfer: $0.09 per GB = 90 microcents per MB DataTransferCostPerMB = 90 // microcents per MB )
WebSocket Cost Constants (in microcents for precision)
const ActiveMonthSeedMetricSK = "SEED#ACTIVE_MONTH"
ActiveMonthSeedMetricSK is the SK of the one-time active-month seed marker.
const (
// CMSArticleIndexSKPrefix is the prefix used for sortable published-time keys.
CMSArticleIndexSKPrefix = "TIME#"
)
const DayCounterSK = "COUNTER"
DayCounterSK is the SK of the per-day counter item.
const (
// DefaultBootstrapUsername is the reserved username used during instance setup.
DefaultBootstrapUsername = "bootstrap"
)
const InstanceMetricsPK = "INSTANCE#METRICS"
InstanceMetricsPK is the partition key of the shared instance-metrics item family that holds the TOTAL_* counters.
const (
PeriodTimeHour = "hour"
)
Period time constants
const SKAgentGovernance = "AGENT_GOVERNANCE"
SKAgentGovernance is the sort key for typed agent-governance rows.
const TotalDomainsMetricSK = "TOTAL_DOMAINS"
TotalDomainsMetricSK is the SK of the maintained TOTAL_DOMAINS counter.
const TotalStatusesMetricSK = "TOTAL_STATUSES"
TotalStatusesMetricSK is the SK of the maintained TOTAL_STATUSES counter.
const TotalUsersMetricSK = "TOTAL_USERS"
TotalUsersMetricSK is the SK of the maintained TOTAL_USERS counter.
const (
VisibilityDisabled = "disabled"
)
Visibility constants for activity permissions
Variables ¶
var ( // User Media Config errors ErrInvalidPlanTier = centralErrors.InvalidPlanTier() ErrInvalidFileSize = centralErrors.InvalidFileSize() ErrFileSizeTooLarge = centralErrors.FileSizeExceedsLimit(0, 0) ErrVideoDurationInvalid = centralErrors.VideoDurationInvalid() ErrUploadLimitsInvalid = centralErrors.UploadLimitsInvalid() ErrBudgetLimitsInvalid = centralErrors.BudgetLimitsInvalid() ErrModerationThresholdInvalid = centralErrors.ModerationThresholdInvalid() ErrInvalidQualitySetting = centralErrors.InvalidQualitySetting() ErrPlanUpgradeFailed = centralErrors.PlanUpgradeFailed(stdErrors.New("plan upgrade failed")) ErrUserIDRequired = centralErrors.UserIDRequired() // Relay Cost errors ErrRelayWindowStartRequired = centralErrors.ValidationFailedWithField("window start is required") ErrInvalidBudgetLimit = centralErrors.ValidationFailedWithField("limit_micro_cents must be positive") // Transcoding Job errors ErrTranscodingJobIDRequired = centralErrors.RequiredFieldMissing("transcoding job ID") ErrTranscodingMediaIDRequired = centralErrors.RequiredFieldMissing("transcoding media ID") ErrTranscodingUserIDRequired = centralErrors.RequiredFieldMissing("transcoding user ID") ErrInvalidJobType = centralErrors.NewValidationError("job_type", "Invalid job type") ErrInvalidJobStatus = centralErrors.NewValidationError("job_status", "Invalid job status") ErrNegativeSize = centralErrors.ValueOutOfRange("size", 0, int64(^uint64(0)>>1), -1) ErrNegativeCost = centralErrors.ValueOutOfRange("cost", 0, int64(^uint64(0)>>1), -1) // Metrics validation errors ErrMetricIDRequired = centralErrors.RequiredFieldMissing("ID") ErrMetricTypeRequired = centralErrors.RequiredFieldMissing("type") ErrMetricServiceRequired = centralErrors.RequiredFieldMissing("service") ErrInvalidMetricType = centralErrors.NewValidationError("metric_type", "Invalid metric type") ErrInvalidPeriod = centralErrors.NewValidationError("period", "Invalid period") ErrMetricWindowStartRequired = centralErrors.RequiredFieldMissing("WindowStart") ErrMetricWindowEndRequired = centralErrors.RequiredFieldMissing("WindowEnd") ErrWindowEndBeforeStart = centralErrors.NewValidationError("window_end", "WindowEnd must be after WindowStart") ErrTimestampRequired = centralErrors.RequiredFieldMissing("timestamp") ErrAggregationLevelRequired = centralErrors.RequiredFieldMissing("AggregationLevel") ErrInvalidAggregationLevel = centralErrors.NewValidationError("aggregation_level", "Invalid aggregation level") ErrFailedToUpdateKeys = centralErrors.FailedToUpdate("keys", stdErrors.New("failed to update keys")) // MetricRecord validation errors ErrMetricRecordTypeRequired = centralErrors.RequiredFieldMissing("MetricType") ErrMetricRecordServiceRequired = centralErrors.RequiredFieldMissing("ServiceName") // WebSocket Cost Tracking errors ErrInvalidWebSocketOperationType = centralErrors.NewValidationError("operation_type", "Invalid operation type") ErrInvalidWebSocketPeriod = centralErrors.NewValidationError("period", "Invalid period") ErrBudgetMicroCentsNegative = centralErrors.ValueOutOfRange("BudgetMicroCents", 0, int64(^uint64(0)>>1), -1) ErrWebSocketWindowStartRequired = centralErrors.RequiredFieldMissing("WindowStart") ErrWebSocketWindowEndRequired = centralErrors.RequiredFieldMissing("WindowEnd") ErrWebSocketWindowEndBeforeStart = centralErrors.NewValidationError("window_end", "WindowEnd must be after WindowStart") // Scheduled Job Cost Tracking errors ErrInvalidScheduledJobStatus = centralErrors.NewValidationError("status", "Invalid status") ErrInvalidScheduledJobSchedule = centralErrors.NewValidationError("schedule", "Invalid schedule") ErrScheduledJobWindowStartRequired = centralErrors.RequiredFieldMissing("WindowStart") ErrScheduledJobWindowEndRequired = centralErrors.RequiredFieldMissing("WindowEnd") ErrScheduledJobWindowEndBeforeStart = centralErrors.NewValidationError("window_end", "WindowEnd must be after WindowStart") ErrInvalidScheduledJobPeriod = centralErrors.NewValidationError("period", "Invalid period") // Media validation errors ErrFileSizeZero = centralErrors.ValueOutOfRange("FileSize", 1, int64(^uint64(0)>>1), 0) ErrUnsupportedContentType = centralErrors.ContentTypeNotAllowed("unknown") ErrInvalidMediaStatus = centralErrors.NewValidationError("media_status", "Invalid media status") ErrInvalidMediaCategory = centralErrors.NewValidationError("media_category", "Invalid media category") ErrMediaIDRequired = centralErrors.RequiredFieldMissing("MediaID") // Media Metadata validation errors ErrMediaMetadataIDRequired = centralErrors.RequiredFieldMissing("MediaID") ErrMediaMetadataInvalidStatus = centralErrors.NewValidationError("status", "Invalid status") ErrMediaMetadataWidthNegative = centralErrors.ValueOutOfRange("width", 0, int64(^uint64(0)>>1), -1) ErrMediaMetadataHeightNegative = centralErrors.ValueOutOfRange("height", 0, int64(^uint64(0)>>1), -1) ErrMediaMetadataDurationNegative = centralErrors.ValueOutOfRange("duration", 0, int64(^uint64(0)>>1), -1) ErrMediaMetadataFileSizeNegative = centralErrors.ValueOutOfRange("file_size", 0, int64(^uint64(0)>>1), -1) // DLQ Message validation errors ErrDLQIDRequired = centralErrors.RequiredFieldMissing("ID") ErrDLQOriginalMessageIDRequired = centralErrors.RequiredFieldMissing("OriginalMessageID") ErrDLQServiceRequired = centralErrors.RequiredFieldMissing("service") ErrDLQMessageBodyRequired = centralErrors.RequiredFieldMissing("MessageBody") ErrDLQErrorTypeRequired = centralErrors.RequiredFieldMissing("ErrorType") ErrDLQErrorMessageRequired = centralErrors.RequiredFieldMissing("ErrorMessage") ErrDLQInvalidStatus = centralErrors.NewValidationError("status", "Invalid status") ErrDLQInvalidPriority = centralErrors.NewValidationError("priority", "Invalid priority") // Reputation validation errors ErrInvalidActorIDFormat = centralErrors.InvalidFormat("actorID", "valid actor ID format") ErrReputationMarshalFailed = centralErrors.MarshalingFailed("reputation", stdErrors.New("reputation marshaling failed")) ErrInvalidReputationJSON = centralErrors.JSONFormatInvalid("invalid reputation structure") ErrReputationUnmarshalFailed = centralErrors.UnmarshalingFailed("reputation to map", stdErrors.New("reputation unmarshaling failed")) ErrCalculatedAtFieldMissing = centralErrors.RequiredFieldMissing("calculatedAt") ErrCalculatedAtParseFailed = centralErrors.ParsingFailed("calculatedAt", stdErrors.New("calculatedAt parsing failed")) ErrInvalidReputationDataJSON = centralErrors.JSONFormatInvalid("invalid reputation data structure") ErrReputationDataUnmarshalFailed = centralErrors.UnmarshalingFailed("reputation data", stdErrors.New("reputation data unmarshaling failed")) // CSRF Token validation errors ErrCSRFTokenRequired = centralErrors.RequiredFieldMissing("token") ErrCSRFUserIDRequired = centralErrors.RequiredFieldMissing("UserID") ErrCSRFExpiresAtRequired = centralErrors.RequiredFieldMissing("ExpiresAt") ErrCSRFCreatedAtRequired = centralErrors.RequiredFieldMissing("CreatedAt") ErrCSRFInvalidTimeRange = centralErrors.NewValidationError("expires_at", "ExpiresAt must be after CreatedAt") // Notification Delivery validation errors ErrNotificationIDRequired = centralErrors.RequiredFieldMissing("notification ID") ErrDeliveryMethodRequired = centralErrors.RequiredFieldMissing("delivery method") ErrInvalidDeliveryMethod = centralErrors.NewValidationError("delivery_method", "Invalid delivery method") ErrInvalidDeliveryStatus = centralErrors.NewValidationError("delivery_status", "Invalid delivery status") // Session validation errors ErrSessionIDGenerationFailed = centralErrors.SessionIDGenerationFailed(stdErrors.New("session ID generation failed")) ErrAccessTokenGenerationFailed = centralErrors.AccessTokenGenerationFailed(stdErrors.New("access token generation failed")) ErrExpiresAtRequired = centralErrors.RequiredFieldMissing("ExpiresAt") // Cost tracking validation errors ErrInvalidOperationType = centralErrors.NewValidationError("operation_type", "Invalid operation type") ErrInvalidCostPeriod = centralErrors.NewValidationError("period", "Invalid period") ErrCostWindowStartRequired = centralErrors.RequiredFieldMissing("WindowStart") ErrCostWindowEndRequired = centralErrors.RequiredFieldMissing("WindowEnd") ErrCostWindowEndBeforeStart = centralErrors.NewValidationError("window_end", "WindowEnd must be after WindowStart") // OAuth Session validation errors ErrOAuthSessionIDGenerationFailed = centralErrors.SessionIDGenerationFailed(stdErrors.New("OAuth session ID generation failed")) ErrOAuthCSRFTokenGenerationFailed = centralErrors.CSRFTokenGenerationFailed(stdErrors.New("OAuth CSRF token generation failed")) // Provider Account validation errors ErrProviderIDRequired = centralErrors.RequiredFieldMissing("provider ID") ErrInvalidProvider = centralErrors.NewValidationError("provider", "Invalid provider") ErrAccessTokenExpired = centralErrors.NewAppError(centralErrors.CodeTokenExpired, centralErrors.CategoryAuth, "Access token has expired") // Conversation validation errors ErrConversationIDRequired = centralErrors.RequiredFieldMissing("conversation ID") ErrConversationDataRequired = centralErrors.RequiredFieldMissing("conversation data") ErrConversationViewerIDRequired = centralErrors.RequiredFieldMissing("viewer ID") ErrConversationCounterpartIDRequired = centralErrors.RequiredFieldMissing("counterpart ID") ErrConversationFolderRequired = centralErrors.RequiredFieldMissing("folder") // Conversation Status validation errors ErrConversationStatusIDRequired = centralErrors.RequiredFieldMissing("conversation ID") ErrConversationStatusUserIDRequired = centralErrors.RequiredFieldMissing("user ID") ErrConversationStatusStatusIDRequired = centralErrors.RequiredFieldMissing("status ID") // Media Attachment validation errors ErrMediaAttachmentIDRequired = centralErrors.RequiredFieldMissing("MediaID") ErrMediaAttachmentEntityTypeRequired = centralErrors.RequiredFieldMissing("EntityType") ErrMediaAttachmentEntityIDRequired = centralErrors.RequiredFieldMissing("EntityID") ErrMediaAttachmentOrderNegative = centralErrors.ValueOutOfRange("order", 0, int64(^uint64(0)>>1), -1) ErrMediaAttachmentInvalidEntityType = centralErrors.NewValidationError("entity_type", "Invalid entity type") ErrMediaAttachmentInvalidFocalPoint = centralErrors.InvalidFormat("focal_point", "x,y format") // Media Spending validation errors ErrInvalidMonthlyPeriodFormat = centralErrors.InvalidFormat("monthly_period", "YYYY-MM format") ErrInvalidDailyPeriodFormat = centralErrors.InvalidFormat("daily_period", "YYYY-MM-DD format") ErrInvalidPeriodType = centralErrors.NewValidationError("period_type", "Invalid period type") ErrInvalidPeriodTypeValue = centralErrors.NewValidationError("period_type", "PeriodType must be 'monthly' or 'daily'") ErrNegativeSpendingAmounts = centralErrors.ValueOutOfRange("spending_amounts", 0, int64(^uint64(0)>>1), -1) ErrNegativeCostMicros = centralErrors.ValueOutOfRange("CostMicros", 0, int64(^uint64(0)>>1), -1) ErrInvalidSpendingCategory = centralErrors.NewValidationError("category", "Invalid category") ErrMediaSpendingUserIDRequired = centralErrors.RequiredFieldMissing("UserID") ErrMediaSpendingPeriodRequired = centralErrors.RequiredFieldMissing("period") ErrMediaSpendingTransactionIDRequired = centralErrors.RequiredFieldMissing("TransactionID") // Alert validation errors ErrAlertIDRequired = centralErrors.RequiredFieldMissing("alert_id") // Webhook Delivery validation errors ErrDeliveryIDRequired = centralErrors.RequiredFieldMissing("delivery_id") ErrWebhookIDRequired = centralErrors.RequiredFieldMissing("webhook_id") // Dead Letter Message validation errors ErrMessageIDRequired = centralErrors.RequiredFieldMissing("message_id") // Conversation Mute validation errors ErrConversationMuteUsernameRequired = centralErrors.RequiredFieldMissing("username") ErrConversationMuteConversationIDRequired = centralErrors.RequiredFieldMissing("conversation ID") // Export validation errors ErrExportInvalidStartDate = centralErrors.InvalidFormat("start_date", "valid date format") ErrExportInvalidEndDate = centralErrors.InvalidFormat("end_date", "valid date format") // Media Job validation errors ErrMediaJobIDRequired = centralErrors.RequiredFieldMissing("JobID") ErrInvalidMediaJobStatus = centralErrors.NewValidationError("job_status", "Invalid job status") // Push Subscription validation errors ErrPushSubscriptionP256dhRequired = centralErrors.RequiredFieldMissing("p256dh public key") ErrPushSubscriptionAuthRequired = centralErrors.RequiredFieldMissing("auth secret") // Block validation errors ErrBlockUpdateKeysFailed = centralErrors.FailedToUpdate("block keys", stdErrors.New("failed to update block keys")) // Mute validation errors ErrMuteUpdateKeysFailed = centralErrors.FailedToUpdate("mute keys", stdErrors.New("failed to update mute keys")) // CloudWatch Metrics validation errors ErrCloudWatchMetricServiceNameRequired = centralErrors.RequiredFieldMissing("ServiceName") // Notification validation errors ErrInvalidNotificationType = centralErrors.NewValidationError("notification_type", "Invalid notification type") )
Legacy error variables for backwards compatibility These are now wrappers around the centralized error system
var ( // MainTableName is the primary DynamoDB table name. // // Most production binaries resolve this from environment (DYNAMODB_TABLE / DYNAMO_TABLE_NAME / STAGE). // Operator CLIs may override it explicitly (for example based on --stage) and should not require STAGE just // to run help/version commands. MainTableName = resolveMainTableName() )
Table names
Functions ¶
func ActivityDayKey ¶ added in v1.6.24
ActivityDayKey returns the PK of the day counter for a UTC date string (common.DateFormat).
func AgentAccessLeaseTokenExpiresAt ¶ added in v1.1.46
func AgentAccessLeaseTokenExpiresAt(now time.Time, lease *AgentAccessLease, idleExpiresAt time.Time) time.Time
AgentAccessLeaseTokenExpiresAt returns the effective bearer-token expiry for a lease renewal after combining lease policy, idle-window renewal, and the absolute lease expiry.
func AgentShareGrantGranteeGSI2PK ¶ added in v1.6.5
AgentShareGrantGranteeGSI2PK returns the active-list partition for one grantee.
func AgentShareGrantPK ¶ added in v1.6.5
AgentShareGrantPK returns the direct-read partition key for an agent.
func AgentShareGrantSK ¶ added in v1.6.5
AgentShareGrantSK returns the direct-read sort key for one grantee.
func CMSArticleIndexExtractArticleID ¶
CMSArticleIndexExtractArticleID extracts the article ID from an index SK.
func CMSArticleIndexPKForAuthor ¶
CMSArticleIndexPKForAuthor returns the PK for author-indexed articles (grouped by actor ID).
func CMSArticleIndexPKForCategory ¶
CMSArticleIndexPKForCategory returns the PK for category-indexed articles (grouped by category ID).
func CMSArticleIndexPKForSeries ¶
CMSArticleIndexPKForSeries returns the PK for series-indexed articles (grouped by GraphQL series ID).
func CMSArticleIndexSK ¶
CMSArticleIndexSK returns the sortable SK for an article based on its published time and ID.
func CMSArticleSlugIndexPK ¶
CMSArticleSlugIndexPK returns the PK for a given article slug.
func CMSArticleSlugIndexSK ¶
func CMSArticleSlugIndexSK() string
CMSArticleSlugIndexSK returns the fixed SK for article slug index entries.
func CMSCategorySlugIndexPK ¶
CMSCategorySlugIndexPK returns the PK for a given category slug.
func CMSCategorySlugIndexSK ¶
func CMSCategorySlugIndexSK() string
CMSCategorySlugIndexSK returns the fixed SK for category slug index entries.
func CMSPublicationSlugIndexPK ¶
CMSPublicationSlugIndexPK returns the PK for a given publication slug.
func CMSPublicationSlugIndexSK ¶
func CMSPublicationSlugIndexSK() string
CMSPublicationSlugIndexSK returns the fixed SK for publication slug index entries.
func CMSSeriesSlugIndexPK ¶
CMSSeriesSlugIndexPK returns the PK for a given series slug.
func CMSSeriesSlugIndexSK ¶
func CMSSeriesSlugIndexSK() string
CMSSeriesSlugIndexSK returns the fixed SK for slug index entries.
func CMSSlugIndexSK ¶
func CMSSlugIndexSK() string
CMSSlugIndexSK returns the fixed SK for slug index entries.
func CMSTenantArticleSlugIndexPK ¶ added in v1.2.53
CMSTenantArticleSlugIndexPK returns the tenant-scoped PK for an article slug.
func CMSTenantCategorySlugIndexPK ¶ added in v1.2.53
CMSTenantCategorySlugIndexPK returns the tenant-scoped PK for a category slug.
func CMSTenantPublicationSlugIndexPK ¶ added in v1.2.53
CMSTenantPublicationSlugIndexPK returns the tenant-scoped PK for a publication slug.
func CMSTenantSeriesSlugIndexPK ¶ added in v1.2.53
CMSTenantSeriesSlugIndexPK returns the tenant-scoped PK for a series slug.
func CalculateCost ¶
func CalculateCost(readUnits, writeUnits float64) (readCostMicroCents, writeCostMicroCents, totalCostMicroCents int64)
CalculateCost calculates the cost for the given capacity units
func CalculateDynamoDBCost ¶
CalculateDynamoDBCost calculates the cost of DynamoDB operations
func CalculateEmailCost ¶
CalculateEmailCost returns 0 since email is not supported by Lesser
func CalculateLambdaCost ¶
CalculateLambdaCost calculates the cost of Lambda execution
func CalculatePatternAccuracy ¶
func CalculatePatternAccuracy(feedbacks []*PatternFeedback) float64
CalculatePatternAccuracy calculates accuracy from a slice of feedback
func CalculatePatternMetrics ¶
func CalculatePatternMetrics(feedbacks []*PatternFeedback) map[string]interface{}
CalculatePatternMetrics calculates detailed metrics from feedback
func CalculatePushCost ¶
CalculatePushCost calculates the cost of sending push notifications
func CalculateSMSCost ¶
CalculateSMSCost returns 0 since SMS is not supported by Lesser
func CalculateScheduledJobCosts ¶
func CalculateScheduledJobCosts(lambdaDurationMs int64, memoryMB int, dynamoDBReadOps, dynamoDBWriteOps int64, sqsMessages int64, s3Operations int64, logSizeMB int64, dataTransferMB int64) (lambdaCost, dynamoDBCost, sqsCost, s3Cost, cloudWatchCost, dataTransferCost, totalCost int64)
CalculateScheduledJobCosts calculates costs for a scheduled job based on resource usage
func CalculateWebSocketCost ¶
CalculateWebSocketCost calculates the cost of sending WebSocket messages
func CanonicalActivityPubObjectIDForStatus ¶ added in v1.2.46
CanonicalActivityPubObjectIDForStatus returns the ActivityPub object ID that should be used when a federated interaction refers to a status. This is intentionally distinct from StatusID: remote statuses use a local remote_* StatusID for storage and counters, while their ActivityPub object identity remains the source instance's Note ID.
func CanonicalConversationParticipantID ¶ added in v1.1.71
CanonicalConversationParticipantID normalizes local conversation participant identifiers to the lowercase form used by conversation lookup keys.
func CanonicalConversationParticipants ¶ added in v1.1.71
CanonicalConversationParticipants returns a sorted, normalized participant list for comparison keys.
func CanonicalStatusID ¶ added in v1.2.25
CanonicalStatusID normalizes local and remote status identifiers into one storage-safe contract. Local status URLs collapse to their path identifier, while remote status URLs hash to a deterministic remote-prefixed ID so different domains cannot collide on the same final path segment.
func CanonicalStatusIDForDomain ¶ added in v1.2.25
CanonicalStatusIDForDomain normalizes a status identifier against the provided local domain instead of the global process config.
func ConversationHasRemoteParticipants ¶ added in v1.2.51
func ConversationHasRemoteParticipants(conversation *Conversation) bool
ConversationHasRemoteParticipants reports whether the conversation includes a remote actor.
func ConversationLocalParticipantIDs ¶ added in v1.2.51
func ConversationLocalParticipantIDs(conversation *Conversation) []string
ConversationLocalParticipantIDs returns local-user participants that should own viewer state rows.
func ConversationParticipantIDsFromRefs ¶ added in v1.2.51
func ConversationParticipantIDsFromRefs(refs []ConversationParticipantRef) []string
ConversationParticipantIDsFromRefs returns the compatibility participant ID list for typed refs.
func DayFormat ¶ added in v1.6.24
DayFormat is the UTC date layout used for all day-bucketed rollup keys.
func ExtractDomain ¶
ExtractDomain extracts the domain from an ActivityPub ID URL
func FormatStatsDate ¶
FormatStatsDate formats a time as a date string for use as sort key
func GetCostDriverKey ¶
GetCostDriverKey returns the key for retrieving a specific driver
func GetCostDriversByCategoryKeys ¶
GetCostDriversByCategoryKeys returns keys for querying all drivers in a category
func GetCostProjectionKey ¶
GetCostProjectionKey returns the key for retrieving a specific projection
func GetFederationStatsKey ¶
GetFederationStatsKey returns the key for retrieving stats for a specific date
func GetFederationStatsRangeKeys ¶
GetFederationStatsRangeKeys returns keys for querying a date range
func GetHealthReportKey ¶
GetHealthReportKey returns the key for retrieving a specific health report
func GetHealthReportRangeKeys ¶
func GetHealthReportRangeKeys(domain string, startTime, endTime time.Time) (pk, skStart, skEnd string)
GetHealthReportRangeKeys returns keys for querying reports in a time range
func GetLatestHealthReportKeys ¶
GetLatestHealthReportKeys returns keys for querying the latest report
func GetLatestProjectionKeys ¶
GetLatestProjectionKeys returns keys for querying the latest projection for a period
func GetLinkMetadataKey ¶
GetLinkMetadataKey returns the key for retrieving link metadata
func GetPatternFeedbackKey ¶
GetPatternFeedbackKey returns the key for retrieving specific feedback
func GetPatternFeedbackKeys ¶
GetPatternFeedbackKeys returns keys for querying all feedback for a pattern
func GetPatternFeedbackRangeKeys ¶
func GetPatternFeedbackRangeKeys(patternID string, startTime, endTime time.Time) (pk, skStart, skEnd string)
GetPatternFeedbackRangeKeys returns keys for querying feedback in a time range
func GetProjectionRangeKeys ¶
func GetProjectionRangeKeys(period string, startTime, endTime time.Time) (pk, skStart, skEnd string)
GetProjectionRangeKeys returns keys for querying projections in a time range
func GetReviewerStatsKey ¶
GetReviewerStatsKey returns the key for retrieving reviewer stats
func GetTimeBucket ¶
GetTimeBucket returns the time bucket for the given aggregation period
func GetTrendingLinkKey ¶
GetTrendingLinkKey returns the key for retrieving a specific trending link
func GetTrendingLinksByDomainKeys ¶
GetTrendingLinksByDomainKeys returns keys for querying trending links from a specific domain
func GetTrendingLinksKeys ¶
GetTrendingLinksKeys returns keys for querying trending links for a date
func GetTrendingStatusKey ¶
GetTrendingStatusKey returns the key for retrieving a specific trending status
func GetTrendingStatusRangeKeys ¶
GetTrendingStatusRangeKeys returns keys for querying top N trending statuses
func GetTrendingStatusesKeys ¶
GetTrendingStatusesKeys returns keys for querying trending statuses for a date
func GetTrusteeConfigKey ¶
GetTrusteeConfigKey returns the key for retrieving a specific trustee config
func GetTrusteeConfigsByCategoryKeys ¶
GetTrusteeConfigsByCategoryKeys returns keys for querying all trustees in a category
func GetTrusteeConfigsByUserKeys ¶
GetTrusteeConfigsByUserKeys returns keys for querying all trustees for a user
func IsCanonicalRemoteStatusID ¶ added in v1.2.25
IsCanonicalRemoteStatusID reports whether the identifier is already using the canonical remote status identity contract.
func IsCanonicalSHA256Digest ¶ added in v1.6.23
IsCanonicalSHA256Digest reports whether value is a canonical sha256:<hex> identifier with exactly 64 lowercase hex characters, matching the M0 pipeline digest, the M3 upload-grant admission (64-lowercase-hex sha256), and the MediaProvenance content-integrity surface.
func IsValidMediaCategory ¶
func IsValidMediaCategory(category MediaCategory) bool
IsValidMediaCategory reports whether the provided category is supported.
func NormalizeAgentAccessLeaseTokenTTLHours ¶ added in v1.1.46
func NormalizeAgentAccessLeaseTokenTTLHours(idleTimeoutHours, absoluteTTLHours, tokenTTLHours int) int
NormalizeAgentAccessLeaseTokenTTLHours clamps a lease token TTL policy to the lease bounds so it remains meaningful to clients.
func NormalizePromoPackageVisibility ¶ added in v1.6.23
NormalizePromoPackageVisibility canonicalizes the intended outbound visibility. Issue #1446 scopes promo attachment to public/unlisted posts; private and direct are structurally rejected here and re-checked at release.
func NormalizeRelationshipIdentity ¶ added in v1.2.26
NormalizeRelationshipIdentity canonicalizes relationship storage identifiers so local actors persist as bare usernames and remote actors persist as user@domain.
func NormalizeRemoteActorHandle ¶ added in v1.2.25
NormalizeRemoteActorHandle canonicalizes remote actor cache identifiers so writes and reads converge on the same durable cache key.
func OAuthRefreshAuthorityPK ¶ added in v1.6.23
OAuthRefreshAuthorityPK hashes a length-delimited tuple so attacker-controlled identifiers never become ambiguous or disclose identity in DynamoDB keys.
func PromoPackageContentHash ¶ added in v1.6.23
func PromoPackageContentHash(p *PromoPackage) string
PromoPackageContentHash binds review verdicts and the release gate to the exact reviewed package content: the outbound post text, the intended visibility, the promoted article reference, and the ordered asset set (identity plus the digest bound at review time). The canonicalization follows the M2 draft-review pattern — every field is length-prefixed so boundaries stay unambiguous even when values contain control characters. Order is meaningful: assets hash in binding order because the order is the attachment order on the outbound post. Any text/visibility/article/asset change re-hashes and makes prior verdicts and principal authorization stale through the verdict-vs-hash comparison, so the exact reviewed package is what releases.
func ReputationActorIDsMatch ¶ added in v1.4.0
ReputationActorIDsMatch reports whether two reputation actor identifiers resolve to the same canonical ActivityPub actor URI.
func ReputationActorPartitionKeyCandidates ¶ added in v1.4.0
ReputationActorPartitionKeyCandidates returns read candidates in canonical order. The legacy username key remains a fallback so local cached reputation rows can be read during the transition; callers must still verify the stored ActorID matches the requested actor before trusting a fallback row.
func ReputationActorPartitionKeyForRecord ¶ added in v1.4.0
ReputationActorPartitionKeyForRecord returns the partition key for a reputation record. Local actor reputations preserve the legacy ACTOR#<username> key because deployed instances already have those rows. Remote actor reputations are keyed by the canonical actor URI to bind the reputation row to the actor's domain.
func SkillAssignmentPartitionKey ¶ added in v1.3.2
SkillAssignmentPartitionKey returns the primary partition for a subject assignment set.
func SkillAssignmentSortKey ¶ added in v1.3.2
SkillAssignmentSortKey returns the sort key for a subject assignment.
func SkillPartitionKey ¶ added in v1.3.2
SkillPartitionKey returns the canonical partition for a skill and its revisions.
func SkillPromotionDigest ¶ added in v1.3.2
func SkillPromotionDigest(proposal *SkillProposal, revision *SkillRevision) (string, error)
SkillPromotionDigest returns the canonical digest that identifies a proposal promotion.
func SkillProposalPartitionKey ¶ added in v1.3.2
SkillProposalPartitionKey returns the primary partition for a proposal.
func SkillRevisionApprovalDigest ¶ added in v1.3.2
func SkillRevisionApprovalDigest(revision *SkillRevision, principalID, authorityType, authorityID string) (string, error)
SkillRevisionApprovalDigest returns the canonical digest an approval signs for a revision.
func SkillRevisionSortKey ¶ added in v1.3.2
SkillRevisionSortKey returns the zero-padded revision sort key.
func SoulBindingIdempotencyKeyHash ¶ added in v1.5.21
SoulBindingIdempotencyKeyHash hashes the caller-supplied idempotency key before storage.
func SoulBindingIdempotencyPartitionKey ¶ added in v1.5.21
SoulBindingIdempotencyPartitionKey returns the caller-scoped receipt partition.
func SoulBindingIdempotencySortKey ¶ added in v1.5.21
SoulBindingIdempotencySortKey returns the key-scoped receipt sort key.
func SoulBindingIdempotencySortKeyFromHash ¶ added in v1.5.21
SoulBindingIdempotencySortKeyFromHash returns the key-scoped receipt sort key from a precomputed hash.
func SoulBodyBindingSortKey ¶ added in v0.1.36
SoulBodyBindingSortKey returns the sort key for an instance-owned soul/body binding record.
func SoulBodyBindingUsernamePartitionKey ¶ added in v0.1.36
SoulBodyBindingUsernamePartitionKey returns the partition key for username reverse-index records.
func SoulENSChannelSortKey ¶ added in v0.1.36
SoulENSChannelSortKey returns the sort key for an instance-owned soul ENS channel config record.
func StatusLookupCandidates ¶ added in v1.2.26
StatusLookupCandidates returns the meaningful status identifiers that should be attempted for a direct status read against the current local domain.
func StatusLookupCandidatesForDomain ¶ added in v1.2.26
StatusLookupCandidatesForDomain returns the meaningful status identifiers that should be attempted for a direct status read against the supplied local domain.
Types ¶
type AIAggregatedCost ¶
type AIAggregatedCost struct {
// Primary keys - aggregated costs use AI_AGG#{period}#{operation_type} pattern
PK string `theorydb:"pk" json:"pk"`
SK string `theorydb:"sk" json:"sk"`
// GSI1 for time-based aggregation queries
GSI1PK string `theorydb:"index:gsi1,pk,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,omitempty" json:"gsi1_sk"`
// Aggregation metadata
Period string `json:"period"` // hour, day, week, month
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
OperationType string `json:"operation_type"`
ModelName string `json:"model_name"`
// Aggregated metrics
TotalOperations int64 `json:"total_operations"`
SuccessfulOperations int64 `json:"successful_operations"`
FailedOperations int64 `json:"failed_operations"`
SuccessRate float64 `json:"success_rate"`
// Token aggregates
TotalInputTokens int64 `json:"total_input_tokens"`
TotalOutputTokens int64 `json:"total_output_tokens"`
AvgInputTokens float64 `json:"avg_input_tokens"`
AvgOutputTokens float64 `json:"avg_output_tokens"`
// Cost aggregates
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
AvgCostMicroCents int64 `json:"avg_cost_micro_cents"`
MinCostMicroCents int64 `json:"min_cost_micro_cents"`
MaxCostMicroCents int64 `json:"max_cost_micro_cents"`
MedianCostMicroCents int64 `json:"median_cost_micro_cents"`
// Performance aggregates
AvgLatencyMs float64 `json:"avg_latency_ms"`
P95LatencyMs float64 `json:"p95_latency_ms"`
P99LatencyMs float64 `json:"p99_latency_ms"`
AvgTokensPerSecond float64 `json:"avg_tokens_per_second"`
AvgComplexityScore float64 `json:"avg_complexity_score"`
AvgEfficiencyScore float64 `json:"avg_efficiency_score"`
// Cost efficiency metrics
CostPerInputToken float64 `json:"cost_per_input_token"`
CostPerOutputToken float64 `json:"cost_per_output_token"`
TotalCostDollars float64 `json:"total_cost_dollars"`
// Quality metrics
AvgQualityScore float64 `json:"avg_quality_score"`
AvgRelevanceScore float64 `json:"avg_relevance_score"`
AvgComprehensivenessScore float64 `json:"avg_comprehensiveness_score"`
// Most frequent complexity factors
TopComplexityFactors []string `json:"top_complexity_factors"`
// Timestamps
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// TTL for automatic cleanup (1 year for aggregated records)
TTL int64 `json:"ttl,omitempty" theorydb:"ttl"`
// contains filtered or unexported fields
}
AIAggregatedCost represents aggregated AI cost metrics for efficient querying
func (*AIAggregatedCost) BeforeCreate ¶
func (a *AIAggregatedCost) BeforeCreate() error
BeforeCreate is called before creating the aggregated record
func (*AIAggregatedCost) BeforeUpdate ¶
func (a *AIAggregatedCost) BeforeUpdate() error
BeforeUpdate is called before updating the aggregated record
func (*AIAggregatedCost) GetPK ¶
func (a *AIAggregatedCost) GetPK() string
GetPK returns the partition key
func (*AIAggregatedCost) GetSK ¶
func (a *AIAggregatedCost) GetSK() string
GetSK returns the sort key
func (*AIAggregatedCost) TableName ¶
func (a *AIAggregatedCost) TableName() string
TableName returns the DynamoDB table backing AIAggregatedCost.
func (*AIAggregatedCost) UpdateKeys ¶
func (a *AIAggregatedCost) UpdateKeys() error
UpdateKeys sets the primary keys for the AIAggregatedCost model
type AIAnalysis ¶
type AIAnalysis struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "AI#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "ANALYSIS#{analysis_id}"
// GSI4 for temporal queries (reusing cost tracking GSI)
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk"` // Format: "AI#ANALYSIS#{date}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk"` // Format: "{timestamp}"
// Core fields
ID string `theorydb:"attr:id" json:"id"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
ObjectType string `theorydb:"attr:objectType" json:"object_type"`
AnalyzedAt time.Time `theorydb:"attr:analyzedAt" json:"analyzed_at"`
Version string `theorydb:"attr:version" json:"version"`
// Analysis results
TextAnalysis *ai.TextAnalysis `theorydb:"attr:textAnalysis" json:"text_analysis,omitempty"`
ImageAnalysis *ai.ImageAnalysis `theorydb:"attr:imageAnalysis" json:"image_analysis,omitempty"`
AIDetection *ai.AIDetection `theorydb:"attr:aiDetection" json:"ai_detection,omitempty"`
SpamAnalysis *ai.SpamAnalysis `theorydb:"attr:spamAnalysis" json:"spam_analysis,omitempty"`
// Composite scores
OverallRisk float64 `theorydb:"attr:overallRisk" json:"overall_risk"`
ModerationAction string `theorydb:"attr:moderationAction" json:"moderation_action"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
// DynamoDB metadata
Type string `theorydb:"attr:type" json:"type"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
AIAnalysis represents an AI analysis result stored in DynamoDB
func (*AIAnalysis) BeforeCreate ¶
func (a *AIAnalysis) BeforeCreate() error
BeforeCreate hook for DynamORM
func (*AIAnalysis) BeforeUpdate ¶
func (a *AIAnalysis) BeforeUpdate() error
BeforeUpdate hook for DynamORM
func (*AIAnalysis) GetPK ¶
func (a *AIAnalysis) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*AIAnalysis) GetSK ¶
func (a *AIAnalysis) GetSK() string
GetSK returns the sort key for BaseModel interface
func (AIAnalysis) TableName ¶
func (AIAnalysis) TableName() string
TableName returns the DynamoDB table backing AIAnalysis.
func (*AIAnalysis) UpdateKeys ¶
func (a *AIAnalysis) UpdateKeys() error
UpdateKeys updates the GSI keys for the AI analysis
type AIAnalysisQueue ¶
type AIAnalysisQueue struct {
// Using object keys for updating
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "OBJECT#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "OBJECT#{object_id}"
// Queue metadata
ForceAnalysis bool `theorydb:"attr:forceAnalysis" json:"force_analysis"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
AIAnalysisQueue represents a queued object for AI analysis
func (*AIAnalysisQueue) BeforeUpdate ¶
func (q *AIAnalysisQueue) BeforeUpdate() error
BeforeUpdate hook for DynamORM
func (*AIAnalysisQueue) GetPK ¶
func (q *AIAnalysisQueue) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*AIAnalysisQueue) GetSK ¶
func (q *AIAnalysisQueue) GetSK() string
GetSK returns the sort key for BaseModel interface
func (AIAnalysisQueue) TableName ¶
func (AIAnalysisQueue) TableName() string
TableName returns the DynamoDB table backing AIAnalysisQueue.
func (*AIAnalysisQueue) UpdateKeys ¶
func (q *AIAnalysisQueue) UpdateKeys() error
UpdateKeys updates the keys for the queue entry
type AICost ¶
type AICost struct {
// Primary keys - AI cost uses AI_COST#{operation_id} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for time-based queries - AI_COSTS#{YYYY-MM}, TS#{unix_millis}#{operation_id}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for operation type queries - AI_TYPE#{operation_type}, MODEL#{model}#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// GSI3 for cost analysis - AI_COST_RANGE#{cost_tier}, COST#{cost_microcents}#{timestamp}
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"`
// Core operation metadata
OperationID string `theorydb:"attr:operationID" json:"operation_id"`
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // sentiment_analysis, content_moderation, text_summarization
RequestID string `theorydb:"attr:requestID" json:"request_id"` // Associated request ID for tracing
UserID string `theorydb:"attr:userID" json:"user_id,omitempty"`
ActorID string `theorydb:"attr:actorID" json:"actor_id,omitempty"`
ObjectID string `theorydb:"attr:objectID" json:"object_id,omitempty"` // Note ID, post ID, etc.
// AI Model details
ModelFamily string `theorydb:"attr:modelFamily" json:"model_family"` // claude, titan, jurassic
ModelName string `theorydb:"attr:modelName" json:"model_name"` // claude-3-haiku, claude-3-sonnet, claude-3-opus
ModelVersion string `theorydb:"attr:modelVersion" json:"model_version"` // 20240307, etc.
ModelRegion string `theorydb:"attr:modelRegion" json:"model_region"` // us-east-1, us-west-2
ModelEndpoint string `theorydb:"attr:modelEndpoint" json:"model_endpoint"` // Bedrock endpoint used
// Input/Output token tracking
InputTokens int64 `theorydb:"attr:inputTokens" json:"input_tokens"`
OutputTokens int64 `theorydb:"attr:outputTokens" json:"output_tokens"`
TotalTokens int64 `theorydb:"attr:totalTokens" json:"total_tokens"`
InputCharacters int64 `theorydb:"attr:inputCharacters" json:"input_characters"`
OutputCharacters int64 `theorydb:"attr:outputCharacters" json:"output_characters"`
TokensPerSecond float64 `theorydb:"attr:tokensPerSecond" json:"tokens_per_second"`
CharactersPerToken float64 `theorydb:"attr:charactersPerToken" json:"characters_per_token"`
// Content complexity analysis
ComplexityScore float64 `theorydb:"attr:complexityScore" json:"complexity_score"` // 0.0-1.0 based on content analysis
ComplexityFactors []string `theorydb:"attr:complexityFactors" json:"complexity_factors"` // factors that contributed to complexity
LanguageDetected string `theorydb:"attr:languageDetected" json:"language_detected"`
ContentLength int64 `theorydb:"attr:contentLength" json:"content_length"`
ContentType string `theorydb:"attr:contentType" json:"content_type"` // text, markdown, json, etc.
SentimentPolarity float64 `theorydb:"attr:sentimentPolarity" json:"sentiment_polarity,omitempty"`
SentimentMagnitude float64 `theorydb:"attr:sentimentMagnitude" json:"sentiment_magnitude,omitempty"`
// Cost breakdown (all in microcents)
InputTokenCost int64 `theorydb:"attr:inputTokenCost" json:"input_token_cost"` // Cost for input tokens
OutputTokenCost int64 `theorydb:"attr:outputTokenCost" json:"output_token_cost"` // Cost for output tokens
ModelInferenceCost int64 `theorydb:"attr:modelInferenceCost" json:"model_inference_cost"` // Base inference cost
ComplexityPenaltyCost int64 `theorydb:"attr:complexityPenaltyCost" json:"complexity_penalty_cost"` // Additional cost for complex operations
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
// Performance metrics
RequestLatencyMs int64 `theorydb:"attr:requestLatencyMs" json:"request_latency_ms"` // Total request latency
ModelLatencyMs int64 `theorydb:"attr:modelLatencyMs" json:"model_latency_ms"` // Model processing time
QueueWaitTimeMs int64 `theorydb:"attr:queueWaitTimeMs" json:"queue_wait_time_ms"` // Time waiting in queue
TokenGenerationMs int64 `theorydb:"attr:tokenGenerationMs" json:"token_generation_ms"` // Token generation time
FirstTokenLatencyMs int64 `theorydb:"attr:firstTokenLatencyMs" json:"first_token_latency_ms"` // Time to first token
StreamingEnabled bool `theorydb:"attr:streamingEnabled" json:"streaming_enabled"`
// Error tracking
Success bool `theorydb:"attr:success" json:"success"`
ErrorCode string `theorydb:"attr:errorCode" json:"error_code,omitempty"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"`
RetryCost int64 `theorydb:"attr:retryCost" json:"retry_cost"` // Additional cost from retries
// Context and configuration
Temperature float64 `theorydb:"attr:temperature" json:"temperature,omitempty"`
MaxTokens int64 `theorydb:"attr:maxTokens" json:"max_tokens,omitempty"`
TopP float64 `theorydb:"attr:topP" json:"top_p,omitempty"`
ModelConfig map[string]interface{} `theorydb:"attr:modelConfig" json:"model_config,omitempty"`
SystemPrompt string `theorydb:"attr:systemPrompt" json:"system_prompt,omitempty"` // Truncated for storage
UserPrompt string `theorydb:"attr:userPrompt" json:"user_prompt,omitempty"` // Truncated for storage
ResponseFormat string `theorydb:"attr:responseFormat" json:"response_format,omitempty"`
// Business context
OperationContext map[string]string `theorydb:"attr:operationContext" json:"operation_context,omitempty"` // Additional context
BillingPeriod string `theorydb:"attr:billingPeriod" json:"billing_period"` // YYYY-MM format
CostTier string `theorydb:"attr:costTier" json:"cost_tier"` // low, medium, high, premium
Priority string `theorydb:"attr:priority" json:"priority"` // low, normal, high, urgent
// Efficiency metrics
CostPerInputToken float64 `theorydb:"attr:costPerInputToken" json:"cost_per_input_token"`
CostPerOutputToken float64 `theorydb:"attr:costPerOutputToken" json:"cost_per_output_token"`
CostPerCharacter float64 `theorydb:"attr:costPerCharacter" json:"cost_per_character"`
EfficiencyScore float64 `theorydb:"attr:efficiencyScore" json:"efficiency_score"` // Quality/cost ratio
QualityScore float64 `theorydb:"attr:qualityScore" json:"quality_score"` // Output quality assessment
RelevanceScore float64 `theorydb:"attr:relevanceScore" json:"relevance_score"` // Output relevance to prompt
ComprehensivenesScore float64 `theorydb:"attr:comprehensivenesScore" json:"comprehensiveness_score"` // How complete the output is
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
ProcessingStart time.Time `theorydb:"attr:processingStart" json:"processing_start"`
ProcessingEnd time.Time `theorydb:"attr:processingEnd" json:"processing_end"`
// TTL for automatic cleanup (90 days for AI cost records)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
AICost represents AI/ML operation costs with detailed Bedrock usage tracking
func (*AICost) AddComplexityFactor ¶
AddComplexityFactor adds a factor that contributed to operation complexity
func (*AICost) BeforeCreate ¶
BeforeCreate is called before creating the record
func (*AICost) BeforeUpdate ¶
BeforeUpdate is called before updating the record
func (*AICost) CalculateTotalCost ¶
func (a *AICost) CalculateTotalCost()
CalculateTotalCost calculates the total cost from all components
func (*AICost) GetOperationSummary ¶
GetOperationSummary returns a summary of the AI operation for logging
func (*AICost) GetPerformanceMetrics ¶
GetPerformanceMetrics returns performance-related metrics
func (*AICost) GetTotalCostDollars ¶
GetTotalCostDollars returns the total cost in dollars
func (*AICost) SetModelPricing ¶
func (a *AICost) SetModelPricing()
SetModelPricing sets the cost based on model-specific pricing
func (*AICost) UpdateKeys ¶
UpdateKeys sets the primary keys for the AICost model
type AIInstanceConfig ¶
type AIInstanceConfig struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#CONFIG
SK string `theorydb:"sk,attr:SK" json:"-"` // AI_CONFIG
Managed *AIInstanceConfigManaged `theorydb:"attr:managed" json:"managed"`
Override *AIInstanceConfigOverride `theorydb:"attr:override,omitempty" json:"override,omitempty"`
// Legacy flat attributes (read-only).
// These are preserved for backwards compatibility when reading older records.
LegacyAIEnabled bool `theorydb:"attr:aiEnabled" json:"-"`
LegacyModerationEnabled bool `theorydb:"attr:moderationEnabled" json:"-"`
LegacyNSFWDetectionEnabled bool `theorydb:"attr:nsfwDetectionEnabled" json:"-"`
LegacySpamDetectionEnabled bool `theorydb:"attr:spamDetectionEnabled" json:"-"`
LegacyPIIDetectionEnabled bool `theorydb:"attr:piiDetectionEnabled" json:"-"`
LegacyAIContentDetection bool `theorydb:"attr:aiContentDetection" json:"-"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
AIInstanceConfig represents AI-specific instance configuration
func NewAIInstanceConfig ¶
func NewAIInstanceConfig() *AIInstanceConfig
NewAIInstanceConfig creates a new AI config with defaults
func (*AIInstanceConfig) GetPK ¶
func (c *AIInstanceConfig) GetPK() string
GetPK returns the partition key
func (*AIInstanceConfig) GetSK ¶
func (c *AIInstanceConfig) GetSK() string
GetSK returns the sort key
func (AIInstanceConfig) TableName ¶
func (AIInstanceConfig) TableName() string
TableName returns the DynamoDB table backing AIInstanceConfig.
func (*AIInstanceConfig) UpdateKeys ¶
func (c *AIInstanceConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys
type AIInstanceConfigManaged ¶ added in v0.1.36
type AIInstanceConfigManaged struct {
AIEnabled bool `theorydb:"attr:aiEnabled" json:"ai_enabled"`
ModerationEnabled bool `theorydb:"attr:moderationEnabled" json:"moderation_enabled"`
NSFWDetectionEnabled bool `theorydb:"attr:nsfwDetectionEnabled" json:"nsfw_detection_enabled"`
SpamDetectionEnabled bool `theorydb:"attr:spamDetectionEnabled" json:"spam_detection_enabled"`
PIIDetectionEnabled bool `theorydb:"attr:piiDetectionEnabled" json:"pii_detection_enabled"`
AIContentDetection bool `theorydb:"attr:aiContentDetection" json:"ai_content_detection_enabled"`
}
AIInstanceConfigManaged stores managed/default AI configuration values for an instance.
type AIInstanceConfigOverride ¶ added in v0.1.36
type AIInstanceConfigOverride struct {
AIEnabled *bool `theorydb:"attr:aiEnabled,omitempty" json:"ai_enabled,omitempty"`
ModerationEnabled *bool `theorydb:"attr:moderationEnabled,omitempty" json:"moderation_enabled,omitempty"`
NSFWDetectionEnabled *bool `theorydb:"attr:nsfwDetectionEnabled,omitempty" json:"nsfw_detection_enabled,omitempty"`
SpamDetectionEnabled *bool `theorydb:"attr:spamDetectionEnabled,omitempty" json:"spam_detection_enabled,omitempty"`
PIIDetectionEnabled *bool `theorydb:"attr:piiDetectionEnabled,omitempty" json:"pii_detection_enabled,omitempty"`
AIContentDetection *bool `theorydb:"attr:aiContentDetection,omitempty" json:"ai_content_detection_enabled,omitempty"`
}
AIInstanceConfigOverride stores operator overrides for AI configuration values. Nil fields mean "no override".
type AIInstanceConfigPatch ¶ added in v0.1.36
type AIInstanceConfigPatch struct {
AIEnabled *bool
ModerationEnabled *bool
NSFWDetectionEnabled *bool
SpamDetectionEnabled *bool
PIIDetectionEnabled *bool
AIContentDetection *bool
}
AIInstanceConfigPatch is a merge-safe patch for the AI configuration layers.
type APIRateLimit ¶
type APIRateLimit struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // RATELIMIT#{userID|domain}#{endpoint}
SK string `theorydb:"sk,attr:SK" json:"sk"` // WINDOW#{window_start}
// Attributes
Type string `theorydb:"attr:type" json:"type"` // "APIRateLimit"
UserID string `theorydb:"attr:userID" json:"user_id"` // User identifier
Domain string `theorydb:"attr:domain" json:"domain,omitempty"` // Domain for federation limits
Endpoint string `theorydb:"attr:endpoint" json:"endpoint"` // API endpoint pattern
Count int `theorydb:"attr:count" json:"count"` // Current request count
Window time.Time `theorydb:"attr:window" json:"window"` // Window start time
Blocked bool `theorydb:"attr:blocked" json:"blocked"` // Whether user is blocked
BlockedUntil time.Time `theorydb:"attr:blockedUntil" json:"blocked_until"` // When block expires
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update time
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Automatic cleanup
// Escalating penalty tracking
ViolationCount int `theorydb:"attr:violationCount" json:"violation_count"` // Number of violations
FirstViolation time.Time `theorydb:"attr:firstViolation" json:"first_violation"` // When first violation occurred
LastViolation time.Time `theorydb:"attr:lastViolation" json:"last_violation"` // Most recent violation
// contains filtered or unexported fields
}
APIRateLimit represents a rate limit counter for API endpoints
func NewAPIRateLimit ¶
func NewAPIRateLimit(userID, endpoint string, windowStart time.Time) *APIRateLimit
NewAPIRateLimit creates a new APIRateLimit record
func NewFederationRateLimit ¶
func NewFederationRateLimit(domain, endpoint string, windowStart time.Time) *APIRateLimit
NewFederationRateLimit creates a new rate limit record for federation domains
func (*APIRateLimit) GetPK ¶
func (arl *APIRateLimit) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*APIRateLimit) GetSK ¶
func (arl *APIRateLimit) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (APIRateLimit) TableName ¶
func (APIRateLimit) TableName() string
TableName returns the DynamoDB table name for API rate limits
func (*APIRateLimit) UpdateKeys ¶
func (arl *APIRateLimit) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the APIRateLimit model
type AccountNote ¶
type AccountNote struct {
// Primary key components
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "ACCOUNT_NOTE#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "NOTE#{target_actor_id}"
// Note data - matches storage.AccountNote fields
Username string `theorydb:"attr:username" json:"username"` // Who wrote the note
TargetActorID string `theorydb:"attr:targetActorID" json:"target_actor_id"` // The actor the note is about
Note string `theorydb:"attr:note" json:"note"` // The note content
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
AccountNote represents a private note on an account in DynamoDB Key pattern: PK=ACCOUNT_NOTE#{username}, SK=NOTE#{target_actor_id}
func (*AccountNote) BeforeCreate ¶
func (n *AccountNote) BeforeCreate() error
BeforeCreate prepares the AccountNote for creation
func (*AccountNote) GetPK ¶
func (n *AccountNote) GetPK() string
GetPK returns the partition key (implements BaseModel interface)
func (*AccountNote) GetSK ¶
func (n *AccountNote) GetSK() string
GetSK returns the sort key (implements BaseModel interface)
func (AccountNote) TableName ¶
func (AccountNote) TableName() string
TableName returns the DynamoDB table name
func (*AccountNote) UpdateKeys ¶
func (n *AccountNote) UpdateKeys() error
UpdateKeys updates the primary key fields based on the current data
type AccountPin ¶
type AccountPin struct {
// Primary key components
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "ACCOUNT_PIN#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PIN#{pinned_actor_id}"
// Pin data - matches storage.AccountPin fields
Username string `theorydb:"attr:username" json:"username"` // Who pinned the account
PinnedActorID string `theorydb:"attr:pinnedActorID" json:"pinned_actor_id"` // The actor ID that was pinned
PinnedUsername string `theorydb:"attr:pinnedUsername" json:"pinned_username"` // The username that was pinned
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
AccountPin represents a pinned/endorsed account in DynamoDB Key pattern: PK=ACCOUNT_PIN#{username}, SK=PIN#{pinned_actor_id}
func (*AccountPin) BeforeCreate ¶
func (p *AccountPin) BeforeCreate() error
BeforeCreate prepares the AccountPin for creation
func (*AccountPin) GetPK ¶
func (p *AccountPin) GetPK() string
GetPK returns the partition key (implements BaseModel interface)
func (*AccountPin) GetSK ¶
func (p *AccountPin) GetSK() string
GetSK returns the sort key (implements BaseModel interface)
func (AccountPin) TableName ¶
func (AccountPin) TableName() string
TableName returns the DynamoDB table name
func (*AccountPin) UpdateKeys ¶
func (p *AccountPin) UpdateKeys() error
UpdateKeys updates the primary key fields based on the current data
type Activity ¶
type Activity struct {
// Primary keys - MUST match legacy patterns exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // Format: "ACTOR#{username}"
SK string `theorydb:"sk,attr:SK" json:"SK"` // Format: "ACTIVITY#{timestamp}#{activity_id}"
// GSI for inbox activities - MUST match legacy patterns exactly
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK,omitempty"` // Format: "INBOX#{username}" (only for inbox activities)
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"` // Format: timestamp (only for inbox activities)
// GSI for direct activity lookup by Activity.ID
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2PK,omitempty"` // Format: "ACTIVITYID#{activity_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2SK,omitempty"` // Format: "ACTIVITY#{timestamp}#{activity_id}"
// Activity data
Activity *activitypub.Activity `theorydb:"attr:activity" json:"Activity"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
// contains filtered or unexported fields
}
Activity represents an ActivityPub activity in DynamoDB This matches the legacy storage.ActivityRecord structure
func (*Activity) UpdateKeys ¶
UpdateKeys updates the PK/SK and GSI keys for activities This method sets up the key structure for ActivityPub activities Key patterns MUST match legacy exactly: - PK: "ACTOR#{username}" - SK: "ACTIVITY#{timestamp}#{activity_id}" - GSI1PK: "INBOX#{username}" (only for inbox activities) - GSI1SK: timestamp (only for inbox activities)
type ActivityActorDay ¶ added in v1.6.24
type ActivityActorDay struct {
PK string `theorydb:"pk,attr:PK"` // ACTIVITY_ACTOR#<actor ID>
SK string `theorydb:"sk,attr:SK"` // DAY#YYYY-MM-DD
ActorID string `theorydb:"attr:actorId" json:"actor_id"`
Day string `theorydb:"attr:day" json:"day"` // YYYY-MM-DD (UTC)
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ActivityActorDay is an idempotency marker that ensures an actor is counted at most once per UTC day in the active-month rollup. The write path creates it conditionally; only a newly-created marker bumps the day counter.
func (*ActivityActorDay) GetPK ¶ added in v1.6.24
func (a *ActivityActorDay) GetPK() string
GetPK returns the partition key.
func (*ActivityActorDay) GetSK ¶ added in v1.6.24
func (a *ActivityActorDay) GetSK() string
GetSK returns the sort key.
func (ActivityActorDay) TableName ¶ added in v1.6.24
func (ActivityActorDay) TableName() string
TableName returns the DynamoDB table backing ActivityActorDay.
func (*ActivityActorDay) UpdateKeys ¶ added in v1.6.24
func (a *ActivityActorDay) UpdateKeys() error
UpdateKeys derives PK/SK and TTL for ActivityActorDay.
type ActivityDayCounter ¶ added in v1.6.24
type ActivityDayCounter struct {
PK string `theorydb:"pk,attr:PK"` // ACTIVITY_DAY#YYYY-MM-DD
SK string `theorydb:"sk,attr:SK"` // COUNTER
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD (UTC)
Value int64 `theorydb:"attr:value" json:"value"` // distinct actors active that day
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ActivityDayCounter is the per-UTC-day distinct-actor counter maintained by the activity write path (repositories.RecordActivityActorDay).
func (*ActivityDayCounter) GetPK ¶ added in v1.6.24
func (a *ActivityDayCounter) GetPK() string
GetPK returns the partition key.
func (*ActivityDayCounter) GetSK ¶ added in v1.6.24
func (a *ActivityDayCounter) GetSK() string
GetSK returns the sort key.
func (ActivityDayCounter) TableName ¶ added in v1.6.24
func (ActivityDayCounter) TableName() string
TableName returns the DynamoDB table backing ActivityDayCounter.
func (*ActivityDayCounter) UpdateKeys ¶ added in v1.6.24
func (a *ActivityDayCounter) UpdateKeys() error
UpdateKeys derives PK/SK and TTL for ActivityDayCounter.
type ActivityMetric ¶
type ActivityMetric struct {
PK string `theorydb:"pk,attr:PK" json:"PK"`
SK string `theorydb:"sk,attr:SK" json:"SK"`
ActivityType string `theorydb:"attr:activityType" json:"ActivityType"`
ActorID string `theorydb:"attr:actorID" json:"ActorID"`
Timestamp string `theorydb:"attr:timestamp" json:"Timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
Type string `theorydb:"attr:type" json:"Type"`
// contains filtered or unexported fields
}
ActivityMetric represents a lightweight activity metric record written to the main table. These records power coarse-grained analytics such as push delivery counts.
func NewActivityMetric ¶
func NewActivityMetric(activityType, actorID string, timestamp time.Time) *ActivityMetric
NewActivityMetric constructs an activity metric record for the provided actor and activity type.
func (ActivityMetric) TableName ¶
func (ActivityMetric) TableName() string
TableName ensures activity metrics live in the shared single table.
type Actor ¶
type Actor struct {
// Primary key - using actor username as the primary identifier
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "ACTOR#{username}" - MUST match legacy exactly
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PROFILE" - MUST match legacy exactly
// GSI1 - Username search with prefix partitioning for efficient queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USERNAME_SEARCH#{first_2_chars}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{lowercase_username}"
// GSI2 - Display name search
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "NAME_SEARCH#{first_2_chars}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "{lowercase_name}#{username}"
// GSI3 - Domain-based queries for federation
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "DOMAIN#{domain}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{username}"
// GSI4 - Popularity ranking by follower count
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk"` // Format: "ACTOR_RANK#{bucket}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk"` // Format: "{padded_count}#{username}"
// GSI5 - Recent activity tracking
GSI5PK string `theorydb:"index:gsi5,pk,attr:gsi5PK,omitempty" json:"gsi5_pk"` // Format: "ACTIVE#{date}"
GSI5SK string `theorydb:"index:gsi5,sk,attr:gsi5SK,omitempty" json:"gsi5_sk"` // Format: "{timestamp}#{username}"
// Core actor data
Actor *activitypub.Actor `theorydb:"json,attr:actor" json:"actor"`
Username string `theorydb:"attr:username" json:"username"`
PrivateKey string `theorydb:"attr:privateKey" json:"private_key,omitempty"` // Encrypted private key
KeyType string `theorydb:"attr:keyType" json:"key_type,omitempty"` // Key type: RSA, ECDSA, Ed25519
NumericID string `theorydb:"attr:numericID" json:"numeric_id"` // Mastodon-compatible numeric ID
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastStatusAt *time.Time `theorydb:"attr:lastStatusAt" json:"last_status_at,omitempty"`
Fields []ActorField `theorydb:"json,attr:fields" json:"fields,omitempty"`
// Counts for efficient access
FollowerCount int `theorydb:"attr:followerCount" json:"follower_count"`
FollowingCount int `theorydb:"attr:followingCount" json:"following_count"`
StatusCount int `theorydb:"attr:statusCount" json:"status_count"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Actor represents an ActivityPub actor stored in DynamoDB using DynamORM
func (*Actor) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Actor) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Actor) UpdateKeys ¶
UpdateKeys updates the GSI keys for this actor (required by DynamORM)
type ActorField ¶
type ActorField struct {
Name string `json:"name"`
Value string `json:"value"`
VerifiedAt *time.Time `json:"verified_at,omitempty"`
}
ActorField represents a profile field (like bio fields in Mastodon)
func (ActorField) TableName ¶
func (ActorField) TableName() string
TableName returns the DynamoDB table backing ActorField.
type ActorMetadata ¶
type ActorMetadata struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastStatusAt *time.Time `json:"last_status_at,omitempty"`
Fields []ActorField `json:"fields,omitempty"`
}
ActorMetadata contains additional metadata about an actor
func (ActorMetadata) TableName ¶
func (ActorMetadata) TableName() string
TableName returns the DynamoDB table backing ActorMetadata.
type AdvancedModerationAction ¶
type AdvancedModerationAction string
AdvancedModerationAction represents advanced moderation action types - different from legacy ModerationAction
const ( // AdvancedModerationActionAllow represents allowing content AdvancedModerationActionAllow AdvancedModerationAction = "allow" // AdvancedModerationActionFlag represents flagging content AdvancedModerationActionFlag AdvancedModerationAction = "flag" // AdvancedModerationActionQuarantine represents quarantining content AdvancedModerationActionQuarantine AdvancedModerationAction = "quarantine" // AdvancedModerationActionRemove represents removing content AdvancedModerationActionRemove AdvancedModerationAction = "remove" // AdvancedModerationActionShadowBan represents shadow banning AdvancedModerationActionShadowBan AdvancedModerationAction = "shadow_ban" // AdvancedModerationActionReportToAuth represents reporting to authorities AdvancedModerationActionReportToAuth AdvancedModerationAction = "report_to_authorities" )
type AdvancedSeverity ¶
type AdvancedSeverity string
AdvancedSeverity represents the severity level of a moderation issue
const ( // AdvancedSeverityLow represents low severity AdvancedSeverityLow AdvancedSeverity = "low" // AdvancedSeverityMedium represents medium severity AdvancedSeverityMedium AdvancedSeverity = "medium" // AdvancedSeverityHigh represents high severity AdvancedSeverityHigh AdvancedSeverity = "high" // AdvancedSeverityCritical represents critical severity AdvancedSeverityCritical AdvancedSeverity = "critical" )
type AffectedRelationship ¶
type AffectedRelationship struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // SEVERED#{severanceID}
SK string `theorydb:"sk,attr:SK" json:"-"` // AFFECTED#{actorID}
// GSI1 for reverse lookup by actor
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // ACTOR#{actorID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // SEVERED#{severanceID}
// Fields
SeveranceID string `theorydb:"attr:severanceID" json:"severance_id"`
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
ActorHandle string `theorydb:"attr:actorHandle" json:"actor_handle"`
ActorDomain string `theorydb:"attr:actorDomain" json:"actor_domain"`
RelationshipType string `theorydb:"attr:relationshipType" json:"relationship_type"` // "follower" or "following"
EstablishedAt time.Time `theorydb:"attr:establishedAt" json:"established_at"`
LastInteraction *time.Time `theorydb:"attr:lastInteraction" json:"last_interaction,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for auto-cleanup (180 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
AffectedRelationship represents a single affected follow/follower relationship
func NewAffectedRelationship ¶
func NewAffectedRelationship(severanceID, actorID, actorHandle, actorDomain, relationshipType string, establishedAt time.Time) *AffectedRelationship
NewAffectedRelationship creates a new affected relationship record
func (*AffectedRelationship) GetPK ¶
func (a *AffectedRelationship) GetPK() string
GetPK returns the partition key
func (*AffectedRelationship) GetSK ¶
func (a *AffectedRelationship) GetSK() string
GetSK returns the sort key
func (AffectedRelationship) TableName ¶
func (AffectedRelationship) TableName() string
TableName returns the DynamoDB table backing AffectedRelationship.
func (*AffectedRelationship) UpdateKeys ¶
func (a *AffectedRelationship) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the affected relationship
type AgentAccessLease ¶ added in v1.1.38
type AgentAccessLease struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
PrincipalUsername string `theorydb:"attr:principalUsername" json:"principal_username"`
PrincipalWallet string `theorydb:"attr:principalWallet" json:"principal_wallet"`
AgentWallet string `theorydb:"attr:agentWallet" json:"agent_wallet"`
Scopes []string `theorydb:"attr:scopes" json:"scopes"`
DeviceLabel string `theorydb:"attr:deviceLabel" json:"device_label"`
Status string `theorydb:"attr:status" json:"status"`
IdleTimeoutHours int `theorydb:"attr:idleTimeoutHours" json:"idle_timeout_hours"`
TokenTTLHours int `theorydb:"attr:tokenTTLHours" json:"token_ttl_hours"`
IdleExpiresAt time.Time `theorydb:"attr:idleExpiresAt" json:"idle_expires_at"`
AbsoluteExpiresAt time.Time `theorydb:"attr:absoluteExpiresAt" json:"absolute_expires_at"`
LastUsedAt time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at"`
LeaseVersion int `theorydb:"attr:leaseVersion" json:"lease_version"`
SessionPublicKey string `theorydb:"attr:sessionPublicKey" json:"session_public_key,omitempty"`
SessionKeyType string `theorydb:"attr:sessionKeyType" json:"session_key_type,omitempty"`
SessionKeyCreatedAt time.Time `theorydb:"attr:sessionKeyCreatedAt" json:"session_key_created_at,omitempty"`
SessionKeyLastUsedAt time.Time `theorydb:"attr:sessionKeyLastUsedAt" json:"session_key_last_used_at,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
RevokedAt time.Time `theorydb:"attr:revokedAt" json:"revoked_at,omitempty"`
RevokedBy string `theorydb:"attr:revokedBy" json:"revoked_by,omitempty"`
RevokedReason string `theorydb:"attr:revokedReason" json:"revoked_reason,omitempty"`
// contains filtered or unexported fields
}
AgentAccessLease represents a durable, wallet-backed local access lease for an agent.
func (*AgentAccessLease) BeforeCreate ¶ added in v1.1.38
func (l *AgentAccessLease) BeforeCreate() error
BeforeCreate derives keys and timestamps before persistence.
func (*AgentAccessLease) BeforeUpdate ¶ added in v1.1.38
func (l *AgentAccessLease) BeforeUpdate() error
BeforeUpdate refreshes timestamps before persistence.
func (*AgentAccessLease) EffectiveTokenTTLHours ¶ added in v1.1.46
func (l *AgentAccessLease) EffectiveTokenTTLHours() int
EffectiveTokenTTLHours returns the lease token TTL policy after applying lease-safe defaults and clamps.
func (*AgentAccessLease) GetPK ¶ added in v1.1.38
func (l *AgentAccessLease) GetPK() string
GetPK returns the partition key.
func (*AgentAccessLease) GetSK ¶ added in v1.1.38
func (l *AgentAccessLease) GetSK() string
GetSK returns the sort key.
func (AgentAccessLease) TableName ¶ added in v1.1.38
func (AgentAccessLease) TableName() string
TableName returns the DynamoDB table backing AgentAccessLease.
func (*AgentAccessLease) UpdateKeys ¶ added in v1.1.38
func (l *AgentAccessLease) UpdateKeys() error
UpdateKeys derives the storage keys and TTL.
type AgentAccessLeaseChallenge ¶ added in v1.1.38
type AgentAccessLeaseChallenge struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
LeaseID string `theorydb:"attr:leaseID" json:"lease_id"`
Username string `theorydb:"attr:username" json:"username"`
Action string `theorydb:"attr:action" json:"action"`
Address string `theorydb:"attr:address" json:"address"`
PrincipalUsername string `theorydb:"attr:principalUsername" json:"principal_username"`
PrincipalWallet string `theorydb:"attr:principalWallet" json:"principal_wallet"`
AgentWallet string `theorydb:"attr:agentWallet" json:"agent_wallet"`
SessionPublicKey string `theorydb:"attr:sessionPublicKey" json:"session_public_key,omitempty"`
SessionKeyType string `theorydb:"attr:sessionKeyType" json:"session_key_type,omitempty"`
Scopes []string `theorydb:"attr:scopes" json:"scopes"`
DeviceLabel string `theorydb:"attr:deviceLabel" json:"device_label"`
IdleTimeoutHours int `theorydb:"attr:idleTimeoutHours" json:"idle_timeout_hours"`
TokenTTLHours int `theorydb:"attr:tokenTTLHours" json:"token_ttl_hours"`
AbsoluteTTLHours int `theorydb:"attr:absoluteTTLHours" json:"absolute_ttl_hours"`
Nonce string `theorydb:"attr:nonce" json:"nonce"`
Message string `theorydb:"attr:message" json:"message"`
IssuedAt time.Time `theorydb:"attr:issuedAt" json:"issued_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Used bool `theorydb:"attr:used" json:"used"`
// contains filtered or unexported fields
}
AgentAccessLeaseChallenge represents a one-time wallet-signing challenge for lease enrollment or renewal.
func (*AgentAccessLeaseChallenge) BeforeCreate ¶ added in v1.1.38
func (c *AgentAccessLeaseChallenge) BeforeCreate() error
BeforeCreate derives keys and timestamps before persistence.
func (*AgentAccessLeaseChallenge) EffectiveTokenTTLHours ¶ added in v1.1.46
func (c *AgentAccessLeaseChallenge) EffectiveTokenTTLHours() int
EffectiveTokenTTLHours returns the challenge token TTL policy after applying lease-safe defaults and clamps.
func (*AgentAccessLeaseChallenge) GetPK ¶ added in v1.1.38
func (c *AgentAccessLeaseChallenge) GetPK() string
GetPK returns the partition key.
func (*AgentAccessLeaseChallenge) GetSK ¶ added in v1.1.38
func (c *AgentAccessLeaseChallenge) GetSK() string
GetSK returns the sort key.
func (AgentAccessLeaseChallenge) TableName ¶ added in v1.1.38
func (AgentAccessLeaseChallenge) TableName() string
TableName returns the DynamoDB table backing AgentAccessLeaseChallenge.
func (*AgentAccessLeaseChallenge) UpdateKeys ¶ added in v1.1.38
func (c *AgentAccessLeaseChallenge) UpdateKeys() error
UpdateKeys derives the storage keys and TTL.
type AgentConcurrencySlot ¶
type AgentConcurrencySlot struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // AGENT_CONCURRENCY#{session_id}
SK string `theorydb:"sk,attr:SK" json:"sk"` // SLOT#{n}
LeaseID string `theorydb:"attr:leaseID" json:"lease_id"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
AgentConcurrencySlot is a DynamoDB-backed semaphore slot for agent tokens.
The semaphore is represented as a fixed set of slots per agent session ID. Each slot is claimed with a short TTL so abandoned leases can be reclaimed safely.
func (*AgentConcurrencySlot) BeforeCreate ¶
func (s *AgentConcurrencySlot) BeforeCreate() error
BeforeCreate prepares the lease for persistence and derives the TTL from ExpiresAt.
func (AgentConcurrencySlot) TableName ¶
func (AgentConcurrencySlot) TableName() string
TableName returns the DynamoDB table backing AgentConcurrencySlot.
type AgentGovernanceState ¶ added in v1.1.75
type AgentGovernanceState struct {
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
Username string `theorydb:"attr:username" json:"username"`
QuarantineStatus string `theorydb:"attr:quarantineStatus,omitempty" json:"quarantine_status,omitempty"`
QuarantineStart *time.Time `theorydb:"attr:quarantineStart" json:"quarantine_start,omitempty"`
QuarantineEnd *time.Time `theorydb:"attr:quarantineEnd" json:"quarantine_end,omitempty"`
QuarantineApprovedBy string `theorydb:"attr:quarantineApprovedBy,omitempty" json:"quarantine_approved_by,omitempty"`
QuarantineApprovedAt *time.Time `theorydb:"attr:quarantineApprovedAt" json:"quarantine_approved_at,omitempty"`
DelegatedScopes []string `theorydb:"attr:delegatedScopes" json:"delegated_scopes,omitempty"`
SelfScopes []string `theorydb:"attr:selfScopes" json:"self_scopes,omitempty"`
SelfSovereign bool `theorydb:"attr:selfSovereign" json:"self_sovereign,omitempty"`
Verified bool `theorydb:"attr:verified" json:"verified"`
VerifiedAt *time.Time `theorydb:"attr:verifiedAt" json:"verified_at,omitempty"`
VerifiedBy string `theorydb:"attr:verifiedBy,omitempty" json:"verified_by,omitempty"`
VerifiedReason string `theorydb:"attr:verifiedReason,omitempty" json:"verified_reason,omitempty"`
UnverifiedAt *time.Time `theorydb:"attr:unverifiedAt" json:"unverified_at,omitempty"`
UnverifiedBy string `theorydb:"attr:unverifiedBy,omitempty" json:"unverified_by,omitempty"`
UnverifiedReason string `theorydb:"attr:unverifiedReason,omitempty" json:"unverified_reason,omitempty"`
KeyRotatedAt *time.Time `theorydb:"attr:keyRotatedAt" json:"key_rotated_at,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
AgentGovernanceState stores typed agent governance state outside the core user row.
func (*AgentGovernanceState) BeforeCreate ¶ added in v1.1.75
func (s *AgentGovernanceState) BeforeCreate() error
BeforeCreate normalizes the model before an insert.
func (*AgentGovernanceState) BeforeUpdate ¶ added in v1.1.75
func (s *AgentGovernanceState) BeforeUpdate() error
BeforeUpdate normalizes the model before an update.
func (*AgentGovernanceState) GetPK ¶ added in v1.1.75
func (s *AgentGovernanceState) GetPK() string
GetPK returns the model partition key.
func (*AgentGovernanceState) GetSK ¶ added in v1.1.75
func (s *AgentGovernanceState) GetSK() string
GetSK returns the model sort key.
func (AgentGovernanceState) TableName ¶ added in v1.1.75
func (AgentGovernanceState) TableName() string
TableName returns the backing DynamoDB table for the model.
func (*AgentGovernanceState) UpdateKeys ¶ added in v1.1.75
func (s *AgentGovernanceState) UpdateKeys() error
UpdateKeys refreshes the primary key fields from the username.
type AgentInstanceConfig ¶
type AgentInstanceConfig struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
AllowAgents bool `theorydb:"attr:allowAgents" json:"allow_agents"`
AllowAgentRegistration bool `theorydb:"attr:allowAgentRegistration" json:"allow_agent_registration"`
DefaultQuarantineDays int `theorydb:"attr:defaultQuarantineDays" json:"default_quarantine_days"`
MaxAgentsPerOwner int `theorydb:"attr:maxAgentsPerOwner" json:"max_agents_per_owner"`
// Remote agent policy (federated bot accounts)
AllowRemoteAgents bool `theorydb:"attr:allowRemoteAgents" json:"allow_remote_agents"`
RemoteQuarantineDays int `theorydb:"attr:remoteQuarantineDays" json:"remote_quarantine_days"`
BlockedAgentDomains []string `theorydb:"attr:blockedAgentDomains" json:"blocked_agent_domains,omitempty"`
TrustedAgentDomains []string `theorydb:"attr:trustedAgentDomains" json:"trusted_agent_domains,omitempty"`
// Verified/trust tier limits
AgentMaxPostsPerHour int `theorydb:"attr:agentMaxPostsPerHour" json:"agent_max_posts_per_hour"`
VerifiedAgentMaxPostsPerHour int `theorydb:"attr:verifiedAgentMaxPostsPerHour" json:"verified_agent_max_posts_per_hour"`
AgentMaxFollowsPerHour int `theorydb:"attr:agentMaxFollowsPerHour" json:"agent_max_follows_per_hour"`
VerifiedAgentMaxFollowsPerHour int `theorydb:"attr:verifiedAgentMaxFollowsPerHour" json:"verified_agent_max_follows_per_hour"`
// Optional hybrid retrieval (timeline + semantic fallback). Disabled by default.
HybridRetrievalEnabled bool `theorydb:"attr:hybridRetrievalEnabled" json:"hybrid_retrieval_enabled"`
HybridRetrievalMaxCandidates int `theorydb:"attr:hybridRetrievalMaxCandidates" json:"hybrid_retrieval_max_candidates"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
AgentInstanceConfig stores instance-level agent policy.
This record lives under PK="INSTANCE#CONFIG" and SK="AGENT_CONFIG".
func NewAgentInstanceConfig ¶
func NewAgentInstanceConfig() *AgentInstanceConfig
NewAgentInstanceConfig returns secure-by-default agent policy. Operators must explicitly enable agents and agent registration via env or admin policy.
func (*AgentInstanceConfig) GetPK ¶
func (c *AgentInstanceConfig) GetPK() string
GetPK returns the partition key.
func (*AgentInstanceConfig) GetSK ¶
func (c *AgentInstanceConfig) GetSK() string
GetSK returns the sort key.
func (AgentInstanceConfig) TableName ¶
func (AgentInstanceConfig) TableName() string
TableName returns the DynamoDB table backing AgentInstanceConfig.
func (*AgentInstanceConfig) UpdateKeys ¶
func (c *AgentInstanceConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type AgentKeyChallenge ¶
type AgentKeyChallenge struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
Action string `theorydb:"attr:action" json:"action"`
Nonce string `theorydb:"attr:nonce" json:"nonce"`
Message string `theorydb:"attr:message" json:"message"`
IssuedAt time.Time `theorydb:"attr:issuedAt" json:"issued_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Used bool `theorydb:"attr:used" json:"used"`
// contains filtered or unexported fields
}
AgentKeyChallenge represents a server-issued challenge for self-sovereign agent authentication.
It is used for registration, token minting, and key rotation flows. Challenges are short-lived and are marked used after successful verification to prevent replay.
func (*AgentKeyChallenge) BeforeCreate ¶
func (c *AgentKeyChallenge) BeforeCreate() error
BeforeCreate derives keys and TTL before persistence.
func (*AgentKeyChallenge) GetPK ¶ added in v1.1.42
func (c *AgentKeyChallenge) GetPK() string
GetPK returns the partition key.
func (*AgentKeyChallenge) GetSK ¶ added in v1.1.42
func (c *AgentKeyChallenge) GetSK() string
GetSK returns the sort key.
func (AgentKeyChallenge) TableName ¶
func (AgentKeyChallenge) TableName() string
TableName returns the DynamoDB table backing AgentKeyChallenge.
func (*AgentKeyChallenge) UpdateKeys ¶ added in v1.1.42
func (c *AgentKeyChallenge) UpdateKeys() error
UpdateKeys derives keys and TTL.
type AgentMemoryEvent ¶
type AgentMemoryEvent struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // MEMORY#{original_status_id}
SK string `theorydb:"sk,attr:SK" json:"sk"` // EVENT#{timestamp}#{event_id}
// GSI1 supports querying events by agent (auditing/debugging) without scanning.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // AGENT#{agent_username}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // EVENT#{timestamp}#{event_id}
EventID string `theorydb:"attr:eventID" json:"event_id"`
EventType string `theorydb:"attr:eventType" json:"event_type"`
StatusID string `theorydb:"attr:statusID" json:"status_id"`
OriginalID string `theorydb:"attr:originalID" json:"original_id"`
AgentUsername string `theorydb:"attr:agentUsername" json:"agent_username"`
Reason string `theorydb:"attr:reason" json:"reason,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
AgentMemoryEvent captures the event-sourced "timeline-as-memory" semantics for agent accounts.
Events are immutable and are keyed by the "original" status ID so retrieval can resolve the latest truth (e.g., corrections/retractions) without requiring silent edits.
func (*AgentMemoryEvent) BeforeCreate ¶
func (e *AgentMemoryEvent) BeforeCreate() error
BeforeCreate prepares the event for persistence and derives all index keys.
func (AgentMemoryEvent) TableName ¶
func (AgentMemoryEvent) TableName() string
TableName returns the DynamoDB table backing AgentMemoryEvent.
type AgentShareGrant ¶ added in v1.6.5
type AgentShareGrant struct {
}
AgentShareGrant authorizes one local Lesser account to access an agent through actor-scoped surfaces that independently enforce this storage contract.
func (AgentShareGrant) TableName ¶ added in v1.6.5
func (AgentShareGrant) TableName() string
TableName returns the single Lesser table backing agent share grants.
func (*AgentShareGrant) UpdateKeys ¶ added in v1.6.5
func (g *AgentShareGrant) UpdateKeys() error
UpdateKeys derives the primary direct-read keys and sparse active-grant index.
type AggregatedMetrics ¶
type AggregatedMetrics struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "metrics_agg#{period}#{type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "window#{windowStart}"
// GSI2 - global queries by period (used for cleanup without table/index scans)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "METRICS_AGG#{period}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "WINDOW#{windowStart}#TYPE#{type}#SERVICE#{service}"
// Aggregation details
Period string `theorydb:"attr:period" json:"period"` // minute, hour, day, week, month
Type string `theorydb:"attr:type" json:"type"` // Same as Metrics.Type
Service string `theorydb:"attr:service" json:"service"` // Service name
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"` // Start of aggregation window
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"` // End of aggregation window
// Aggregated values
TotalCount int64 `theorydb:"attr:totalCount" json:"total_count"`
TotalSum float64 `theorydb:"attr:totalSum" json:"total_sum"`
Average float64 `theorydb:"attr:average" json:"average"`
Min float64 `theorydb:"attr:min" json:"min"`
Max float64 `theorydb:"attr:max" json:"max"`
StdDev float64 `theorydb:"attr:stdDev" json:"std_dev"`
Percentiles map[string]float64 `theorydb:"attr:percentiles" json:"percentiles"`
// Breakdown by dimensions
DimensionBreakdown map[string]DimensionStats `theorydb:"attr:dimensionBreakdown" json:"dimension_breakdown,omitempty"`
// Service-specific metrics
ServiceMetrics map[string]interface{} `theorydb:"attr:serviceMetrics" json:"service_metrics,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL (longer for aggregated data)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"`
// contains filtered or unexported fields
}
AggregatedMetrics represents pre-computed metrics aggregations
func (*AggregatedMetrics) BeforeCreate ¶
func (am *AggregatedMetrics) BeforeCreate() error
BeforeCreate for AggregatedMetrics
func (*AggregatedMetrics) BeforeUpdate ¶
func (am *AggregatedMetrics) BeforeUpdate() error
BeforeUpdate for AggregatedMetrics
func (*AggregatedMetrics) GetPK ¶
func (am *AggregatedMetrics) GetPK() string
GetPK implements BaseModel interface for AggregatedMetrics
func (*AggregatedMetrics) GetSK ¶
func (am *AggregatedMetrics) GetSK() string
GetSK implements BaseModel interface for AggregatedMetrics
func (AggregatedMetrics) TableName ¶
func (AggregatedMetrics) TableName() string
TableName returns the DynamoDB table backing AggregatedMetrics.
func (*AggregatedMetrics) UpdateKeys ¶
func (am *AggregatedMetrics) UpdateKeys() error
UpdateKeys implements BaseModel interface for AggregatedMetrics
func (*AggregatedMetrics) Validate ¶
func (am *AggregatedMetrics) Validate() error
Validate for AggregatedMetrics
type Alert ¶
type Alert struct {
// Primary key: ALERT#{alert_id}
PK string `theorydb:"pk,attr:PK" json:"pk"`
// Sort key: METADATA
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1: Alert type index for querying by alert type
// GSI1PK: ALERT_TYPE#{type}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
// GSI1SK: TIMESTAMP#{timestamp}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2: Service index for querying alerts by service
// GSI2PK: SERVICE#{service}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
// GSI2SK: SEVERITY#{severity}#TIMESTAMP#{timestamp}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// GSI3: Status index for querying alerts by status
// GSI3PK: STATUS#{status}
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"`
// GSI3SK: PRIORITY#{priority}#TIMESTAMP#{timestamp}
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"`
// Alert identification
AlertID string `theorydb:"attr:alertID" json:"alert_id"`
Type string `theorydb:"attr:type" json:"type"` // error_rate, latency, cost, health, security, capacity
Severity string `theorydb:"attr:severity" json:"severity"` // info, warning, error, critical
Priority string `theorydb:"attr:priority" json:"priority"` // P0, P1, P2
Status string `theorydb:"attr:status" json:"status"` // firing, resolved, acknowledged, suppressed
// Alert content
Title string `theorydb:"attr:title" json:"title"`
Description string `theorydb:"attr:description" json:"description"`
Message string `theorydb:"attr:message" json:"message"`
RunbookURL string `theorydb:"attr:runbookURL" json:"runbook_url,omitempty"`
// Context information
Service string `theorydb:"attr:service" json:"service"`
Region string `theorydb:"attr:region" json:"region"`
Source string `theorydb:"attr:source" json:"source"`
Dimensions map[string]string `theorydb:"attr:dimensions" json:"dimensions"`
// Alert data
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata"`
Values map[string]float64 `theorydb:"attr:values" json:"values"`
Thresholds map[string]float64 `theorydb:"attr:thresholds" json:"thresholds"`
// Timing information
FiredAt time.Time `theorydb:"attr:firedAt" json:"fired_at"`
ResolvedAt *time.Time `theorydb:"attr:resolvedAt" json:"resolved_at,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Escalation and delivery
EscalationLevel int `theorydb:"attr:escalationLevel" json:"escalation_level"`
DeliveryChannels []string `theorydb:"attr:deliveryChannels" json:"delivery_channels"` // webhook, sns, email, slack
DeliveryAttempts int `theorydb:"attr:deliveryAttempts" json:"delivery_attempts"`
LastDeliveryAt *time.Time `theorydb:"attr:lastDeliveryAt" json:"last_delivery_at,omitempty"`
NextRetryAt *time.Time `theorydb:"attr:nextRetryAt" json:"next_retry_at,omitempty"`
// Alert grouping and suppression
GroupKey string `theorydb:"attr:groupKey" json:"group_key,omitempty"`
SuppressionUntil *time.Time `theorydb:"attr:suppressionUntil" json:"suppression_until,omitempty"`
// TTL for automatic cleanup (alerts older than 30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Alert represents a system alert that can be triggered for monitoring purposes
func (*Alert) Acknowledge ¶
func (a *Alert) Acknowledge()
Acknowledge marks the alert as acknowledged
func (*Alert) AddDimension ¶
AddDimension adds a dimension to the alert
func (*Alert) AddMetadata ¶
AddMetadata adds metadata to the alert
func (*Alert) AddThreshold ¶
AddThreshold adds a threshold to the alert
func (*Alert) CalculateNextRetry ¶
CalculateNextRetry calculates the next retry time using exponential backoff
func (*Alert) IsCritical ¶
IsCritical returns true if the alert is critical severity
func (*Alert) IsHighPriority ¶
IsHighPriority returns true if the alert is P0 or P1
func (*Alert) IsResolved ¶
IsResolved returns true if the alert has been resolved
func (*Alert) RecordDeliveryAttempt ¶
RecordDeliveryAttempt records a delivery attempt
func (*Alert) ShouldRetry ¶
ShouldRetry returns true if the alert delivery should be retried
func (*Alert) UpdateKeys ¶
UpdateKeys sets the partition and sort keys based on alert data
type Announce ¶
type Announce struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // OBJECT#{object_id}#ANNOUNCES
SK string `theorydb:"sk,attr:SK" json:"SK"` // ACTOR#{actor_id}
// GSI4 for actor lookups
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4PK"` // ACTOR#{actor_id}#ANNOUNCES
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4SK"` // PUBLISHED#{timestamp}#OBJECT#{object_id}
// Core fields from legacy (embedded storage.Announce)
Actor string `theorydb:"attr:actor" json:"actor"` // Who announced
Object string `theorydb:"attr:object" json:"object"` // What was announced
ID string `theorydb:"attr:id" json:"id"` // Announce activity ID
Published time.Time `theorydb:"attr:published" json:"published"` // When it was announced
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When stored in DB
To []string `theorydb:"attr:to" json:"to,omitempty"` // Audience
CC []string `theorydb:"attr:cc" json:"cc,omitempty"` // CC audience
// contains filtered or unexported fields
}
Announce represents a reblog/boost activity
func (*Announce) BeforeCreate ¶
BeforeCreate prepares the Announce for creation
func (*Announce) UpdateKeys ¶
UpdateKeys sets the primary and GSI keys
type Announcement ¶
type Announcement struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI1 - Status-based queries (active/inactive)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "ANNOUNCEMENT#active" or "ANNOUNCEMENT#inactive"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "reverse_timestamp" for chronological order
// GSI2 - Created by queries (admin management)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "ADMIN#{admin_username}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{published_at}#{id}"
// Announcement fields
ID string `theorydb:"attr:id" json:"id"`
Content string `theorydb:"attr:content" json:"content"` // HTML content
Text string `theorydb:"attr:text" json:"text"` // Plain text version
PublishedAt time.Time `theorydb:"attr:publishedAt" json:"published_at"` // When it was published
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // When it was last updated
AllDay bool `theorydb:"attr:allDay" json:"all_day"` // Whether it's an all-day announcement
StartsAt *time.Time `theorydb:"attr:startsAt" json:"starts_at,omitempty"` // When the announcement starts
EndsAt *time.Time `theorydb:"attr:endsAt" json:"ends_at,omitempty"` // When the announcement ends
Reactions []Reaction `theorydb:"attr:reactions" json:"reactions,omitempty"` // Available reactions
Tags []string `theorydb:"attr:tags" json:"tags,omitempty"` // Hashtags
Emojis []CustomEmoji `theorydb:"attr:emojis" json:"emojis,omitempty"` // Custom emojis
Mentions []Mention `theorydb:"attr:mentions" json:"mentions,omitempty"` // Mentions
CreatedBy string `theorydb:"attr:createdBy" json:"created_by"` // Admin who created it
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
Announcement represents an announcement in DynamoDB
func (*Announcement) BeforeCreate ¶
func (a *Announcement) BeforeCreate() error
BeforeCreate prepares the announcement for creation
func (*Announcement) GetPK ¶
func (a *Announcement) GetPK() string
GetPK returns the partition key (required by BaseModel)
func (*Announcement) GetSK ¶
func (a *Announcement) GetSK() string
GetSK returns the sort key (required by BaseModel)
func (*Announcement) IsActive ¶
func (a *Announcement) IsActive() bool
IsActive determines if the announcement is currently active
func (Announcement) TableName ¶
func (Announcement) TableName() string
TableName returns the DynamoDB table backing Announcement.
func (*Announcement) UpdateKeys ¶
func (a *Announcement) UpdateKeys() error
UpdateKeys updates the PK and SK based on the announcement data
type AnnouncementDismissal ¶
type AnnouncementDismissal struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Dismissal fields
Username string `theorydb:"attr:username" json:"username"`
AnnouncementID string `theorydb:"attr:announcementID" json:"announcement_id"`
DismissedAt time.Time `theorydb:"attr:dismissedAt" json:"dismissed_at"`
// contains filtered or unexported fields
}
AnnouncementDismissal represents a user dismissing an announcement
func (*AnnouncementDismissal) BeforeCreate ¶
func (d *AnnouncementDismissal) BeforeCreate() error
BeforeCreate prepares the dismissal for creation
func (*AnnouncementDismissal) GetPK ¶
func (d *AnnouncementDismissal) GetPK() string
GetPK returns the partition key for dismissal
func (*AnnouncementDismissal) GetSK ¶
func (d *AnnouncementDismissal) GetSK() string
GetSK returns the sort key for dismissal
func (AnnouncementDismissal) TableName ¶
func (AnnouncementDismissal) TableName() string
TableName returns the DynamoDB table backing AnnouncementDismissal.
func (*AnnouncementDismissal) UpdateKeys ¶
func (d *AnnouncementDismissal) UpdateKeys() error
UpdateKeys updates the PK and SK based on the dismissal data
type AnnouncementReaction ¶
type AnnouncementReaction struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Reaction fields
Username string `theorydb:"attr:username" json:"username"`
AnnouncementID string `theorydb:"attr:announcementID" json:"announcement_id"`
EmojiName string `theorydb:"attr:emojiName" json:"emoji_name"`
ReactedAt time.Time `theorydb:"attr:reactedAt" json:"reacted_at"`
// contains filtered or unexported fields
}
AnnouncementReaction represents a user's reaction to an announcement
func (*AnnouncementReaction) BeforeCreate ¶
func (r *AnnouncementReaction) BeforeCreate() error
BeforeCreate prepares the reaction for creation
func (*AnnouncementReaction) GetPK ¶
func (r *AnnouncementReaction) GetPK() string
GetPK returns the partition key for reaction
func (*AnnouncementReaction) GetSK ¶
func (r *AnnouncementReaction) GetSK() string
GetSK returns the sort key for reaction
func (AnnouncementReaction) TableName ¶
func (AnnouncementReaction) TableName() string
TableName returns the DynamoDB table backing AnnouncementReaction.
func (*AnnouncementReaction) UpdateKeys ¶
func (r *AnnouncementReaction) UpdateKeys() error
UpdateKeys updates the PK and SK based on the reaction data
type Article ¶
type Article struct {
Object // Embeds standard ActivityPub Object fields
// CMS-specific metadata
Slug string `theorydb:"attr:slug" json:"slug,omitempty"`
Subtitle string `theorydb:"attr:subtitle" json:"subtitle,omitempty"`
Excerpt string `theorydb:"attr:excerpt" json:"excerpt,omitempty"`
FeaturedImage *Media `theorydb:"attr:featuredImage" json:"featured_image,omitempty"`
TableOfContents []TOCEntry `theorydb:"attr:tableOfContents" json:"table_of_contents,omitempty"`
// Publishing metadata
ReadingTimeMinutes int `theorydb:"attr:readingTimeMinutes" json:"reading_time_minutes"`
WordCount int `theorydb:"attr:wordCount" json:"word_count"`
ContentFormat string `theorydb:"attr:contentFormat" json:"content_format"` // html, markdown
// Organization
SeriesID *string `theorydb:"attr:seriesID" json:"series_id,omitempty"`
SeriesOrder *int `theorydb:"attr:seriesOrder" json:"series_order,omitempty"`
CategoryIDs []string `theorydb:"attr:categoryIDs" json:"category_ids,omitempty"`
// SEO
SEOTitle string `theorydb:"attr:seoTitle" json:"seo_title,omitempty"`
SEODescription string `theorydb:"attr:seoDescription" json:"seo_description,omitempty"`
CanonicalURL string `theorydb:"attr:canonicalURL" json:"canonical_url,omitempty"`
OGImage string `theorydb:"attr:ogImage" json:"og_image,omitempty"`
// Editorial
EditorNotes string `theorydb:"attr:editorNotes" json:"editor_notes,omitempty"`
ReviewStatus string `theorydb:"attr:reviewStatus" json:"review_status,omitempty"`
// Authoring attribution
GeneratedBy string `theorydb:"attr:generatedBy,omitempty" json:"generated_by,omitempty"`
ReviewedBy string `theorydb:"attr:reviewedBy,omitempty" json:"reviewed_by,omitempty"`
PublishedBy string `theorydb:"attr:publishedBy,omitempty" json:"published_by,omitempty"`
// ActedBy records the local actor URI of the caller who acted on the
// attributed author's behalf under an active share grant (empty when
// the author acted as themselves).
ActedBy string `theorydb:"attr:actedBy,omitempty" json:"acted_by,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
Article represents a long-form content object It extends the standard Object model with CMS-specific metadata
func (*Article) UpdateKeys ¶
UpdateKeys updates the keys for the Article model This overrides Object.UpdateKeys to ensure correct key generation for Articles
type AuditLog ¶
type AuditLog struct {
// Primary key - audit logs by timestamp
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "AUDIT_LOG"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{RFC3339}#{log_id}"
// GSI1 - Actor queries (find actions by who performed them)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "ADMIN#{admin_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Target queries (find actions on specific targets)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "TARGET#{target_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "ACTION#{action}#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "AUDIT_LOG"
// Audit data
ID string `theorydb:"attr:id" json:"id"`
AdminID string `theorydb:"attr:adminID" json:"admin_id"` // Who performed the action
AdminRole string `theorydb:"attr:adminRole" json:"admin_role"` // admin or moderator
Action string `theorydb:"attr:action" json:"action"` // suspend, silence, resolve_report, etc.
TargetType string `theorydb:"attr:targetType" json:"target_type"` // account, status, report, domain
TargetID string `theorydb:"attr:targetID" json:"target_id"` // ID of the target
Reason string `theorydb:"attr:reason" json:"reason,omitempty"` // Reason for action
Details any `theorydb:"attr:details" json:"details,omitempty"` // Additional details
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
RequestID string `theorydb:"attr:requestID" json:"request_id,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// DynamoDB TTL - audit logs expire after 2 years
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
AuditLog represents an audit trail entry for admin actions
func (*AuditLog) UpdateKeys ¶
func (a *AuditLog) UpdateKeys()
UpdateKeys updates the GSI keys based on current field values
type AuthAuditLog ¶
type AuthAuditLog struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Core fields
ID string `theorydb:"attr:id" json:"id"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
EventType string `theorydb:"attr:eventType" json:"event_type"`
Severity string `theorydb:"attr:severity" json:"severity"`
// User information
Username string `theorydb:"attr:username" json:"username,omitempty"`
UserID string `theorydb:"attr:userID" json:"user_id,omitempty"`
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
DeviceName string `theorydb:"attr:deviceName" json:"device_name,omitempty"`
// Session information
SessionID string `theorydb:"attr:sessionID" json:"session_id,omitempty"`
RequestID string `theorydb:"attr:requestID" json:"request_id,omitempty"`
// Result information
Success bool `theorydb:"attr:success" json:"success"`
FailureReason string `theorydb:"attr:failureReason" json:"failure_reason,omitempty"`
// Geographic information
Country string `theorydb:"attr:country" json:"country,omitempty"`
City string `theorydb:"attr:city" json:"city,omitempty"`
Region string `theorydb:"attr:region" json:"region,omitempty"`
Latitude float64 `theorydb:"attr:latitude" json:"latitude,omitempty"`
Longitude float64 `theorydb:"attr:longitude" json:"longitude,omitempty"`
// Risk assessment
RiskScore float64 `theorydb:"attr:riskScore" json:"risk_score,omitempty"`
RiskFlags []string `theorydb:"attr:riskFlags" json:"risk_flags,omitempty"`
// Additional metadata (stored as JSON string)
Metadata string `theorydb:"attr:metadata" json:"metadata,omitempty"`
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // USER#username
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // AUDIT#timestamp
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // IP#address
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // AUDIT#timestamp
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // SESSION#id
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // AUDIT#timestamp
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"-"` // SEVERITY#level
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"-"` // AUDIT#timestamp
// TTL for automatic deletion
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// Compliance fields
DataRetentionDays int `theorydb:"attr:dataRetentionDays" json:"data_retention_days,omitempty"`
ComplianceFlags []string `theorydb:"attr:complianceFlags" json:"compliance_flags,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
AuthAuditLog represents an authentication audit log entry in DynamoDB
func (*AuthAuditLog) BeforeSave ¶
func (a *AuthAuditLog) BeforeSave() error
BeforeSave is called before saving to DynamoDB
func (AuthAuditLog) TableName ¶
func (AuthAuditLog) TableName() string
TableName returns the DynamoDB table backing AuthAuditLog.
func (*AuthAuditLog) UpdateKeys ¶
func (a *AuthAuditLog) UpdateKeys() error
UpdateKeys updates the DynamoDB keys before saving
type AuthRefreshToken ¶
type AuthRefreshToken struct {
// DynamoDB keys - using token as partition key
PK string `theorydb:"pk,attr:PK" json:"-"` // token (the actual token value)
SK string `theorydb:"sk,attr:SK" json:"-"` // TOKEN (constant sort key)
// GSI keys for querying by user, family, and user-family
UserID string `theorydb:"attr:userID" json:"user_id"`
Family string `theorydb:"attr:family" json:"family"`
UserFamily string `theorydb:"attr:userFamily" json:"user_family"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // USER#{userID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // {createdAt}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // FAMILY#{family}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // {createdAt}
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // USER_FAMILY#{userID}#{family}
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // {createdAt}
// Core token data
Token string `theorydb:"attr:token" json:"token"` // The actual token value
Generation int `theorydb:"attr:generation" json:"generation"` // Rotation generation number
CreatedAt int64 `theorydb:"attr:createdAt" json:"created_at"` // Unix timestamp
ExpiresAt int64 `theorydb:"attr:expiresAt" json:"expires_at"` // Unix timestamp
LastUsedAt int64 `theorydb:"attr:lastUsedAt" json:"last_used_at"` // Unix timestamp for tracking
// Security fields
Revoked bool `theorydb:"attr:revoked" json:"revoked"` // Whether token is revoked
RevokedReason string `theorydb:"attr:revokedReason" json:"revoked_reason"` // Reason for revocation
// Tracking fields
DeviceName string `theorydb:"attr:deviceName" json:"device_name"` // Optional device identifier
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address"` // IP address for security monitoring
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
AuthRefreshToken represents a refresh token with advanced security features This implements the token family pattern with rotation and reuse detection
func (*AuthRefreshToken) BeforeCreate ¶
func (a *AuthRefreshToken) BeforeCreate() error
BeforeCreate sets up keys before creating the record
func (*AuthRefreshToken) BeforeUpdate ¶
func (a *AuthRefreshToken) BeforeUpdate() error
BeforeUpdate sets up keys before updating the record
func (*AuthRefreshToken) GetPK ¶
func (a *AuthRefreshToken) GetPK() string
GetPK returns the partition key for this model
func (*AuthRefreshToken) GetSK ¶
func (a *AuthRefreshToken) GetSK() string
GetSK returns the sort key for this model
func (*AuthRefreshToken) IsActive ¶
func (a *AuthRefreshToken) IsActive() bool
IsActive checks if the token is active (not revoked and not expired)
func (*AuthRefreshToken) IsExpired ¶
func (a *AuthRefreshToken) IsExpired() bool
IsExpired checks if the token has expired
func (AuthRefreshToken) TableName ¶
func (AuthRefreshToken) TableName() string
TableName returns the DynamoDB table name
func (*AuthRefreshToken) UpdateKeys ¶
func (a *AuthRefreshToken) UpdateKeys() error
UpdateKeys ensures all keys are properly set for DynamoDB operations
type AuthorizationCode ¶
type AuthorizationCode struct {
// DynamoDB keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"-"` // AUTHCODE#code
SK string `theorydb:"sk,attr:SK" json:"-"` // CODE
// Core fields from legacy storage.AuthorizationCode
Code string `theorydb:"attr:code" json:"Code"`
ClientID string `theorydb:"attr:clientID" json:"ClientID"`
RedirectURI string `theorydb:"attr:redirectURI" json:"RedirectURI"`
Resource string `theorydb:"attr:resource,omitempty" json:"Resource,omitempty"`
Username string `theorydb:"attr:username" json:"Username"`
PrincipalUsername string `theorydb:"attr:principalUsername,omitempty" json:"PrincipalUsername,omitempty"`
CodeChallenge string `theorydb:"attr:codeChallenge" json:"CodeChallenge"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"ExpiresAt"`
Scopes []string `theorydb:"attr:scopes" json:"Scopes"`
// Tracking fields
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
// TTL field for automatic expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
AuthorizationCode represents an OAuth 2.0 authorization code
func (*AuthorizationCode) BeforeCreate ¶
func (a *AuthorizationCode) BeforeCreate() error
BeforeCreate sets up the keys and TTL before creating
func (*AuthorizationCode) GetPK ¶
func (a *AuthorizationCode) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*AuthorizationCode) GetSK ¶
func (a *AuthorizationCode) GetSK() string
GetSK returns the sort key for BaseModel interface
func (AuthorizationCode) TableName ¶
func (AuthorizationCode) TableName() string
TableName returns the DynamoDB table name
func (*AuthorizationCode) UpdateKeys ¶
func (a *AuthorizationCode) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates DynamoDB keys
type BackgroundFetchJob ¶
type BackgroundFetchJob struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "FETCH_JOB#{job_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "JOB#{timestamp}"
// GSI for querying by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{status_id}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // FETCH#{timestamp}
// Job identification
JobID string `theorydb:"attr:jobID" json:"job_id"` // Unique job identifier
StatusID string `theorydb:"attr:statusID" json:"status_id"` // Status/object to fetch
// Job configuration
FetchType string `theorydb:"attr:fetchType" json:"fetch_type"` // "thread_sync", "object_fetch", "media_fetch"
Priority string `theorydb:"attr:priority" json:"priority"` // "low", "normal", "high", "urgent"
MaxRetries int `theorydb:"attr:maxRetries" json:"max_retries"` // Maximum retry attempts
// Job state
Status string `theorydb:"attr:status" json:"status"` // "pending", "running", "completed", "failed"
Attempts int `theorydb:"attr:attempts" json:"attempts"` // Current attempt count
LastAttempt *time.Time `theorydb:"attr:lastAttempt" json:"last_attempt"` // Last attempt timestamp
NextAttempt *time.Time `theorydb:"attr:nextAttempt" json:"next_attempt"` // Next scheduled attempt
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at"` // Completion timestamp
LastError string `theorydb:"attr:lastError" json:"last_error"` // Last error message
ErrorDetails string `theorydb:"attr:errorDetails" json:"error_details"` // Detailed error information
// Fetch metadata
RemoteURL string `theorydb:"attr:remoteURL" json:"remote_url"` // URL to fetch from
FetchMetadata map[string]string `theorydb:"attr:fetchMetadata" json:"fetch_metadata"` // Additional fetch parameters
UserAgent string `theorydb:"attr:userAgent" json:"user_agent"` // User agent for fetching
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for auto-cleanup (7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
BackgroundFetchJob represents a job for fetching remote content
func NewBackgroundFetchJob ¶
func NewBackgroundFetchJob(statusID, fetchType string) *BackgroundFetchJob
NewBackgroundFetchJob creates a new background fetch job
func (*BackgroundFetchJob) AddMetadata ¶
func (j *BackgroundFetchJob) AddMetadata(key, value string)
AddMetadata adds metadata for the fetch job
func (*BackgroundFetchJob) BeforeCreate ¶
func (j *BackgroundFetchJob) BeforeCreate() error
BeforeCreate is called before creating the record
func (*BackgroundFetchJob) BeforeUpdate ¶
func (j *BackgroundFetchJob) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*BackgroundFetchJob) GetMetadata ¶
func (j *BackgroundFetchJob) GetMetadata(key string) string
GetMetadata gets metadata value by key
func (*BackgroundFetchJob) IsReady ¶
func (j *BackgroundFetchJob) IsReady() bool
IsReady returns whether the job is ready to be processed
func (*BackgroundFetchJob) IsRetryable ¶
func (j *BackgroundFetchJob) IsRetryable() bool
IsRetryable returns whether the job can be retried
func (*BackgroundFetchJob) MarkCompleted ¶
func (j *BackgroundFetchJob) MarkCompleted()
MarkCompleted marks the job as completed
func (*BackgroundFetchJob) MarkFailed ¶
func (j *BackgroundFetchJob) MarkFailed(errorMsg, errorDetails string)
MarkFailed marks the job as failed and schedules retry if applicable
func (*BackgroundFetchJob) MarkRunning ¶
func (j *BackgroundFetchJob) MarkRunning()
MarkRunning marks the job as running
func (*BackgroundFetchJob) SetRemoteURL ¶
func (j *BackgroundFetchJob) SetRemoteURL(url string)
SetRemoteURL sets the remote URL to fetch from
func (BackgroundFetchJob) TableName ¶
func (BackgroundFetchJob) TableName() string
TableName returns the DynamoDB table name
func (*BackgroundFetchJob) UpdateKeys ¶
func (j *BackgroundFetchJob) UpdateKeys()
UpdateKeys updates the DynamoDB keys
type BatchGetKeys ¶
type BatchGetKeys struct {
// Primary keys - using pattern: PK=BATCH#{batchType}, SK=KEY#{key}
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Batch data
BatchType string `theorydb:"attr:batchType" json:"batch_type"` // "instance", "metrics", etc.
Key string `theorydb:"attr:key" json:"key"` // The actual key being batched
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for cleanup (short-lived for batching)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
BatchGetKeys represents batch get keys for instances
func (*BatchGetKeys) GetPK ¶
func (b *BatchGetKeys) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*BatchGetKeys) GetSK ¶
func (b *BatchGetKeys) GetSK() string
GetSK returns the sort key for BaseModel interface
func (BatchGetKeys) TableName ¶
func (BatchGetKeys) TableName() string
TableName returns the DynamoDB table backing BatchGetKeys.
func (*BatchGetKeys) UpdateKeys ¶
func (b *BatchGetKeys) UpdateKeys() error
UpdateKeys ensures keys are properly set for batch keys
type Block ¶
type Block struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // ACTOR#{blocker_username}#BLOCKS
SK string `theorydb:"sk,attr:SK" json:"SK"` // BLOCKED#{blocked_username}
// GSI5 for reverse lookup
GSI5PK string `theorydb:"index:gsi5,pk,attr:gsi5PK,omitempty" json:"gsi5PK"` // BLOCKED#{blocked_username}
GSI5SK string `theorydb:"index:gsi5,sk,attr:gsi5SK,omitempty" json:"gsi5SK"` // BLOCKER#{blocker_username}
// Core fields from legacy
Type string `theorydb:"attr:type" json:"Type"` // Always "Block"
Actor string `theorydb:"attr:actor" json:"Actor"` // Full actor ID who is blocking
Object string `theorydb:"attr:object" json:"Object"` // Full actor ID being blocked
ID string `theorydb:"attr:id" json:"ID"` // Block activity ID
Published time.Time `theorydb:"attr:published" json:"Published"` // When the block was published
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"` // When stored in DB
// contains filtered or unexported fields
}
Block represents a block relationship between actors
func (*Block) BeforeCreate ¶
BeforeCreate prepares the Block for creation
func (*Block) UpdateKeys ¶
UpdateKeys sets the primary and GSI keys based on the actor usernames This implements the BaseModel interface requirement
type Bookmark ¶
type Bookmark struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"-"` // BOOKMARK#username
SK string `theorydb:"sk,attr:SK" json:"-"` // TIME#timestamp#objectID or OBJECT#objectID
// GSI8 (OBJECT records only) – reverse index to delete all bookmarks for an object without scans.
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty" json:"-"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty" json:"-"`
// Core fields
Username string `theorydb:"attr:username" json:"username"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// Record metadata for dual-write coordination
RecordType string `theorydb:"attr:recordType" json:"record_type,omitempty"`
Locked bool `theorydb:"attr:locked" json:"locked,omitempty"`
TimeRecordSK string `theorydb:"attr:timeRecordSK" json:"time_record_sk,omitempty"` // OBJECT records keep a pointer to the TIME SK
// TTL field for automatic cleanup (optional)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Bookmark represents a user's bookmark of a status/object. Phase 1 introduces a dual-write pattern where each logical bookmark is written twice:
- A TIME# record keyed by TIME#{timestamp}#{objectID} for chronological reads
- An OBJECT# record keyed by OBJECT#{objectID} for O(1) batch membership checks
The data payload (Username, ObjectID, CreatedAt, etc.) remains identical across both physical records so that either copy can service downstream reads.
func NewObjectIndexedBookmark ¶
func NewObjectIndexedBookmark(username, objectID string, createdAt time.Time, timeRecordSK string) (*Bookmark, error)
NewObjectIndexedBookmark returns a bookmark configured for batch membership checks.
func NewTimeOrderedBookmark ¶
NewTimeOrderedBookmark returns a bookmark configured for chronological reads.
func (*Bookmark) UpdateKeys ¶
UpdateKeys sets the DynamoDB partition and sort keys for the bookmark. RecordType must be one of the BookmarkRecordType* constants; legacy callers that do not set a value default to the TIME record format for backwards compatibility.
type CMSArticleIndex ¶
type CMSArticleIndex struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
ArticleID string `theorydb:"attr:articleID" json:"article_id"`
PublishedAt time.Time `theorydb:"attr:publishedAt" json:"published_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
}
CMSArticleIndex stores an indexed view of articles grouped by author/series/category. It enables efficient queries without scans (single-table design).
func (*CMSArticleIndex) GetPK ¶
func (i *CMSArticleIndex) GetPK() string
GetPK returns the partition key.
func (*CMSArticleIndex) GetSK ¶
func (i *CMSArticleIndex) GetSK() string
GetSK returns the sort key.
func (CMSArticleIndex) TableName ¶
func (CMSArticleIndex) TableName() string
TableName returns the DynamoDB table backing CMSArticleIndex.
func (*CMSArticleIndex) UpdateKeys ¶
func (i *CMSArticleIndex) UpdateKeys() error
UpdateKeys validates required keys and sets timestamps.
type CMSSeriesSlugIndex ¶
type CMSSeriesSlugIndex struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Slug string `theorydb:"attr:slug" json:"slug"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
SeriesID string `theorydb:"attr:seriesID" json:"series_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
CMSSeriesSlugIndex maps a series slug to its owning author + series ID for efficient lookup.
func (*CMSSeriesSlugIndex) GetPK ¶
func (i *CMSSeriesSlugIndex) GetPK() string
GetPK returns the partition key.
func (*CMSSeriesSlugIndex) GetSK ¶
func (i *CMSSeriesSlugIndex) GetSK() string
GetSK returns the sort key.
func (CMSSeriesSlugIndex) TableName ¶
func (CMSSeriesSlugIndex) TableName() string
TableName returns the DynamoDB table backing CMSSeriesSlugIndex.
func (*CMSSeriesSlugIndex) UpdateKeys ¶
func (i *CMSSeriesSlugIndex) UpdateKeys() error
UpdateKeys sets PK/SK based on the slug and stamps timestamps.
type CMSSlugIndex ¶
type CMSSlugIndex struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Slug string `theorydb:"attr:slug" json:"slug"`
TargetID string `theorydb:"attr:targetID" json:"target_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
CMSSlugIndex maps a slug to a canonical object ID.
PK determines the index namespace (article/category/publication) and includes the slug.
func (CMSSlugIndex) TableName ¶
func (CMSSlugIndex) TableName() string
TableName returns the DynamoDB table backing CMSSlugIndex.
func (*CMSSlugIndex) UpdateKeys ¶
func (i *CMSSlugIndex) UpdateKeys() error
UpdateKeys stamps timestamps and validates required fields. Callers must set PK before persisting the record.
type CSRFToken ¶
type CSRFToken struct {
// Primary key - using token as partition key for fast lookups
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "CSRF#{token}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TOKEN"
// GSI1 - User CSRF tokens lookup for rate limiting
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USER_CSRF#{userID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{created_at}#{token}"
// Core CSRF token data
Token string `theorydb:"attr:token" json:"token"`
UserID string `theorydb:"attr:userID" json:"user_id"`
CreatedAt int64 `theorydb:"attr:createdAt" json:"created_at"` // Unix timestamp
ExpiresAt int64 `theorydb:"attr:expiresAt" json:"expires_at"` // Unix timestamp
Used bool `theorydb:"attr:used" json:"used"`
// TTL for automatic cleanup - DynamoDB will automatically delete expired tokens
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Same as ExpiresAt for automatic cleanup
// contains filtered or unexported fields
}
CSRFToken represents a CSRF token stored in DynamoDB
func (*CSRFToken) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*CSRFToken) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*CSRFToken) MarkAsUsed ¶
func (c *CSRFToken) MarkAsUsed()
MarkAsUsed marks the token as used (single-use tokens)
func (*CSRFToken) RemainingTime ¶
RemainingTime returns the time until the token expires
func (*CSRFToken) UpdateKeys ¶
UpdateKeys configures all GSI partition and sort keys
type Category ¶
type Category struct {
PK string `theorydb:"pk,attr:PK"` // INSTANCE#CATEGORY
SK string `theorydb:"sk,attr:SK"` // ID#{category_id}
// GSI: Parent lookup - CATEGORY#{parent_id} / ID#{category_id}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ID string `theorydb:"attr:id" json:"id"`
Name string `theorydb:"attr:name" json:"name"`
Slug string `theorydb:"attr:slug" json:"slug"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
ParentID *string `theorydb:"attr:parentID" json:"parent_id,omitempty"`
// Counts
ArticleCount int `theorydb:"attr:articleCount" json:"article_count"`
// Display
Order int `theorydb:"attr:order" json:"order"`
Color string `theorydb:"attr:color" json:"color,omitempty"` // Hex color for UI
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
Category represents a content category (hierarchical)
func (*Category) UpdateKeys ¶
UpdateKeys updates the keys for the Category model
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// Failure thresholds
FailureThreshold int // Failures to open circuit
SuccessThreshold int // Successes to close circuit
// Timeouts
OpenTimeout time.Duration // How long to stay open
HalfOpenTimeout time.Duration // How long to test in half-open
// Sampling
SampleWindow time.Duration // Window for counting failures
MinimumRequests int // Min requests before evaluating
// Recovery
BackoffMultiplier float64 // Exponential backoff multiplier
MaxBackoff time.Duration // Maximum backoff duration
}
CircuitBreakerConfig represents the configuration for circuit breaker behavior
func DefaultCircuitBreakerConfig ¶
func DefaultCircuitBreakerConfig() *CircuitBreakerConfig
DefaultCircuitBreakerConfig returns sensible defaults
func (CircuitBreakerConfig) TableName ¶
func (CircuitBreakerConfig) TableName() string
TableName returns the DynamoDB table backing CircuitBreakerConfig.
type CircuitBreakerEvent ¶
type CircuitBreakerEvent struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // CIRCUIT#<instance_id>
SK string `theorydb:"sk,attr:SK" json:"sk"` // EVENT#<timestamp_nanos>
// Event details
InstanceID string `theorydb:"attr:instanceID" json:"instance_id"`
EventType string `theorydb:"attr:eventType" json:"event_type"` // state_change, metric
NewStatus string `theorydb:"attr:newStatus" json:"new_status,omitempty"`
OldStatus string `theorydb:"attr:oldStatus" json:"old_status,omitempty"`
Reason string `theorydb:"attr:reason" json:"reason"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// For metric events
Success *bool `theorydb:"attr:success" json:"success,omitempty"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
ErrorType string `theorydb:"attr:errorType" json:"error_type,omitempty"`
// TTL for cleanup (7 days for events)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
CircuitBreakerEvent represents a state change event for debugging and monitoring
func (*CircuitBreakerEvent) GetPK ¶
func (e *CircuitBreakerEvent) GetPK() string
GetPK returns the partition key
func (*CircuitBreakerEvent) GetSK ¶
func (e *CircuitBreakerEvent) GetSK() string
GetSK returns the sort key
func (CircuitBreakerEvent) TableName ¶
func (CircuitBreakerEvent) TableName() string
TableName returns the DynamoDB table backing CircuitBreakerEvent.
func (*CircuitBreakerEvent) UpdateKeys ¶
func (e *CircuitBreakerEvent) UpdateKeys() error
UpdateKeys sets the DynamoDB keys for events
type CircuitBreakerState ¶
type CircuitBreakerState struct {
// DynamoDB keys - use exact patterns from legacy
PK string `theorydb:"pk,attr:PK" json:"pk"` // CIRCUIT#<instance_id>
SK string `theorydb:"sk,attr:SK" json:"sk"` // STATE
// GSI8 - Global state listing (monitoring/debug)
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty" json:"gsi8pk,omitempty"` // CIRCUIT_STATES
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty" json:"gsi8sk,omitempty"` // INSTANCE#<instance_id>
// Core circuit breaker state
InstanceID string `theorydb:"attr:instanceID" json:"instance_id"`
Status string `theorydb:"attr:status" json:"status"` // closed, open, half_open
FailureCount int `theorydb:"attr:failureCount" json:"failure_count"`
SuccessCount int `theorydb:"attr:successCount" json:"success_count"`
ConsecutiveFails int `theorydb:"attr:consecutiveFails" json:"consecutive_fails"`
LastFailure time.Time `theorydb:"attr:lastFailure" json:"last_failure"`
LastSuccess time.Time `theorydb:"attr:lastSuccess" json:"last_success"`
LastStateChange time.Time `theorydb:"attr:lastStateChange" json:"last_state_change"`
NextRetry time.Time `theorydb:"attr:nextRetry" json:"next_retry"`
BackoffDuration int64 `theorydb:"attr:backoffDurationNanos" json:"backoff_duration_nanos"` // Store as nanoseconds for precision
// Metrics
TotalRequests int64 `theorydb:"attr:totalRequests" json:"total_requests"`
TotalFailures int64 `theorydb:"attr:totalFailures" json:"total_failures"`
TotalSuccesses int64 `theorydb:"attr:totalSuccesses" json:"total_successes"`
// Metadata
Reason string `theorydb:"attr:reason" json:"reason"` // Reason for last state change
// TTL for automatic cleanup (30 days after last change)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
CircuitBreakerState represents the state of a circuit breaker for a specific instance
func (*CircuitBreakerState) GetBackoffDuration ¶
func (c *CircuitBreakerState) GetBackoffDuration() time.Duration
GetBackoffDuration returns the backoff duration as time.Duration
func (*CircuitBreakerState) GetPK ¶
func (c *CircuitBreakerState) GetPK() string
GetPK returns the partition key
func (*CircuitBreakerState) GetSK ¶
func (c *CircuitBreakerState) GetSK() string
GetSK returns the sort key
func (*CircuitBreakerState) SetBackoffDuration ¶
func (c *CircuitBreakerState) SetBackoffDuration(d time.Duration)
SetBackoffDuration sets the backoff duration from time.Duration
func (CircuitBreakerState) TableName ¶
func (CircuitBreakerState) TableName() string
TableName returns the DynamoDB table backing CircuitBreakerState.
func (*CircuitBreakerState) UpdateKeys ¶
func (c *CircuitBreakerState) UpdateKeys() error
UpdateKeys sets the DynamoDB keys
type CloudWatchMetrics ¶
type CloudWatchMetrics struct {
// DynamoDB Keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // SERVICE#{serviceName} or INSTANCE#lesser
SK string `theorydb:"sk,attr:SK" json:"sk"` // METRICS#{timestamp}
// GSI keys for time-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // METRIC_DATE#{date}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {serviceName}#{timestamp}
// Business fields
ServiceName string `theorydb:"attr:serviceName" json:"service_name"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD for daily queries
// Metrics data
RequestCount int64 `theorydb:"attr:requestCount" json:"request_count"`
ErrorCount int64 `theorydb:"attr:errorCount" json:"error_count"`
LatencyP50Ms float64 `theorydb:"attr:latencyP50Ms" json:"latency_p50_ms"`
LatencyP90Ms float64 `theorydb:"attr:latencyP90Ms" json:"latency_p90_ms"`
LatencyP99Ms float64 `theorydb:"attr:latencyP99Ms" json:"latency_p99_ms"`
DynamoDBReads int64 `theorydb:"attr:dynamoDBReads" json:"dynamodb_reads"`
DynamoDBWrites int64 `theorydb:"attr:dynamoDBWrites" json:"dynamodb_writes"`
LambdaInvocations int64 `theorydb:"attr:lambdaInvocations" json:"lambda_invocations"`
S3Requests int64 `theorydb:"attr:s3Requests" json:"s3_requests"`
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"`
EstimatedCostUSD float64 `theorydb:"attr:estimatedCostUSD" json:"estimated_cost_usd"`
// Caching metadata
CloudWatchQueryTime time.Time `theorydb:"attr:cloudWatchQueryTime" json:"cloudwatch_query_time"`
CacheExpiry time.Time `theorydb:"attr:cacheExpiry" json:"cache_expiry"`
// TTL for automatic cleanup (24 hours)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
CloudWatchMetrics represents CloudWatch metrics data cached in DynamoDB
func (*CloudWatchMetrics) GetPK ¶
func (c *CloudWatchMetrics) GetPK() string
GetPK returns the partition key
func (*CloudWatchMetrics) GetSK ¶
func (c *CloudWatchMetrics) GetSK() string
GetSK returns the sort key
func (*CloudWatchMetrics) IsExpired ¶
func (c *CloudWatchMetrics) IsExpired() bool
IsExpired checks if the cached metrics have expired (5 minutes cache)
func (*CloudWatchMetrics) SetCacheExpiry ¶
func (c *CloudWatchMetrics) SetCacheExpiry()
SetCacheExpiry sets cache expiry time (default 5 minutes for metrics)
func (CloudWatchMetrics) TableName ¶
func (CloudWatchMetrics) TableName() string
TableName returns the DynamoDB table backing CloudWatchMetrics.
func (*CloudWatchMetrics) UpdateKeys ¶
func (c *CloudWatchMetrics) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type CollectionItem ¶
type CollectionItem struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // COLLECTION#{collection}
SK string `theorydb:"sk,attr:SK" json:"SK"` // ITEM#{itemID}
// GSI1 for reverse lookups (what collections is an item in)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // ITEM#{itemID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // COLLECTION#{collection}
// Collection item data
Collection string `theorydb:"attr:collection" json:"Collection"` // The collection ID (e.g., featured, likes, etc.)
ItemID string `theorydb:"attr:itemID" json:"ItemID"` // The item being added/removed
ItemType string `theorydb:"attr:itemType" json:"ItemType"` // Type of the item (Note, Article, etc.)
AddedBy string `theorydb:"attr:addedBy" json:"AddedBy"` // Who added the item
AddedAt time.Time `theorydb:"attr:addedAt" json:"AddedAt"` // When it was added
Position int `theorydb:"attr:position" json:"Position"` // Optional position in ordered collections
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"` // Database timestamp
// Optional TTL for cleanup
TTL *int64 `theorydb:"ttl,attr:ttl" json:"TTL,omitempty"`
// contains filtered or unexported fields
}
CollectionItem represents an item in an ActivityPub collection
func NewCollectionItem ¶
func NewCollectionItem(collection, itemID, itemType, addedBy string) *CollectionItem
NewCollectionItem creates a new collection item
func (*CollectionItem) BeforeCreate ¶
func (c *CollectionItem) BeforeCreate() error
BeforeCreate sets up the record before creation
func (*CollectionItem) ExtractCollection ¶
func (c *CollectionItem) ExtractCollection() string
ExtractCollection extracts the collection name from PK
func (*CollectionItem) ExtractItemID ¶
func (c *CollectionItem) ExtractItemID() string
ExtractItemID extracts the item ID from SK
func (*CollectionItem) SetPosition ¶
func (c *CollectionItem) SetPosition(position int)
SetPosition sets the position for ordered collections
func (*CollectionItem) SetTTL ¶
func (c *CollectionItem) SetTTL(ttl time.Time)
SetTTL sets the TTL for the collection item (in Unix epoch seconds)
func (CollectionItem) TableName ¶
func (CollectionItem) TableName() string
TableName returns the DynamoDB table name
func (*CollectionItem) UpdateKeys ¶
func (c *CollectionItem) UpdateKeys()
UpdateKeys updates GSI keys based on collection and item
type CommunityNote ¶
type CommunityNote struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // NOTE#<id>
SK string `theorydb:"sk,attr:SK"` // METADATA
// GSI fields for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // OBJECT#<object_id>#NOTES
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // SCORE#<score>#<id>
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"` // NOTES#<visibility_status>
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"` // <created_at>#<id>
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty"` // AUTHOR#<author_id>#NOTES
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty"` // <created_at>#<id>
// Core fields matching storage.CommunityNote
ID string `theorydb:"attr:id" json:"id"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
ObjectType string `theorydb:"attr:objectType" json:"object_type"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Content string `theorydb:"attr:content" json:"content"`
Language string `theorydb:"attr:language" json:"language"`
Sources []string `theorydb:"attr:sources" json:"sources"`
HelpfulVotes int `theorydb:"attr:helpfulVotes" json:"helpful_votes"`
NotHelpfulVotes int `theorydb:"attr:notHelpfulVotes" json:"not_helpful_votes"`
Score float64 `theorydb:"attr:score" json:"score"`
VisibilityStatus string `theorydb:"attr:visibilityStatus" json:"visibility_status"`
// AI Analysis fields
Sentiment float64 `theorydb:"attr:sentiment" json:"sentiment"`
Objectivity float64 `theorydb:"attr:objectivity" json:"objectivity"`
SourceQuality float64 `theorydb:"attr:sourceQuality" json:"source_quality"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL field
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
CommunityNote represents a fact-checking note on an ActivityPub object
func (*CommunityNote) GetPK ¶
func (n *CommunityNote) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*CommunityNote) GetSK ¶
func (n *CommunityNote) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (CommunityNote) TableName ¶
func (CommunityNote) TableName() string
TableName returns the DynamoDB table backing CommunityNote.
func (*CommunityNote) UpdateKeys ¶
func (n *CommunityNote) UpdateKeys() error
UpdateKeys updates the GSI keys based on the current field values
type CommunityNoteVote ¶
type CommunityNoteVote struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // NOTE#<note_id>
SK string `theorydb:"sk,attr:SK"` // VOTE#<voter_id>
// Core fields matching storage.CommunityNoteVote
NoteID string `theorydb:"attr:noteID" json:"note_id"`
VoterID string `theorydb:"attr:voterID" json:"voter_id"`
VoteType string `theorydb:"attr:voteType" json:"vote_type"` // helpful, not_helpful, neutral
Helpful bool `theorydb:"attr:helpful" json:"helpful"` // For simplified access
Weight float64 `theorydb:"attr:weight" json:"weight"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL field
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
CommunityNoteVote represents a vote on a community note
func (*CommunityNoteVote) GetPK ¶
func (v *CommunityNoteVote) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*CommunityNoteVote) GetSK ¶
func (v *CommunityNoteVote) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (CommunityNoteVote) TableName ¶
func (CommunityNoteVote) TableName() string
TableName returns the DynamoDB table backing CommunityNoteVote.
func (*CommunityNoteVote) UpdateKeys ¶
func (v *CommunityNoteVote) UpdateKeys() error
UpdateKeys updates the keys based on the current field values
type ComponentHealthHistory ¶
type ComponentHealthHistory struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // COMPONENT_HISTORY#{component_type}#{component}
SK string `theorydb:"sk,attr:SK" json:"sk"` // HISTORY#{timestamp}
Component string `theorydb:"attr:component" json:"component"`
ComponentType string `theorydb:"attr:componentType" json:"component_type"`
Status string `theorydb:"attr:status" json:"status"`
CheckTime time.Time `theorydb:"attr:checkTime" json:"check_time"`
LatencyMs int64 `theorydb:"attr:latencyMs" json:"latency_ms"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Auto-expire after 7 days
// contains filtered or unexported fields
}
ComponentHealthHistory represents historical health data for a specific component
func NewComponentHealthHistory ¶
func NewComponentHealthHistory(componentType, component, status string, checkTime time.Time, latencyMs int64, err string) *ComponentHealthHistory
NewComponentHealthHistory creates a new component health history entry
func (ComponentHealthHistory) TableName ¶
func (ComponentHealthHistory) TableName() string
TableName returns the DynamoDB table backing ComponentHealthHistory.
func (*ComponentHealthHistory) UpdateKeys ¶
func (c *ComponentHealthHistory) UpdateKeys()
UpdateKeys updates the partition and sort keys for component health history
type ConcurrentViewerMetrics ¶
type ConcurrentViewerMetrics struct {
CurrentViewers int64 `json:"current_viewers"` // Real-time viewer count
PeakViewers int64 `json:"peak_viewers"` // Peak viewers in last 24h
PeakViewerTime time.Time `json:"peak_viewer_time"` // When peak occurred
AverageViewers int64 `json:"average_viewers"` // Average over measurement period
ViewerGrowthRate float64 `json:"viewer_growth_rate"` // Percentage change in viewers
SessionDuration float64 `json:"session_duration"` // Average session length in minutes
NewViewers int64 `json:"new_viewers"` // New viewers in last hour
ReturningViewers int64 `json:"returning_viewers"` // Returning viewers in last hour
}
ConcurrentViewerMetrics represents concurrent viewing statistics
func (ConcurrentViewerMetrics) TableName ¶
func (ConcurrentViewerMetrics) TableName() string
TableName returns the DynamoDB table backing ConcurrentViewerMetrics.
type ConnectionInfo ¶
type ConnectionInfo struct {
ClientIP string `json:"client_ip"`
UserAgent string `json:"user_agent"`
Origin string `json:"origin"`
Protocol string `json:"protocol"`
AuthMethod string `json:"auth_method"`
APIVersion string `json:"api_version"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
}
ConnectionInfo holds metadata about the connection
func (ConnectionInfo) TableName ¶
func (ConnectionInfo) TableName() string
TableName returns the DynamoDB table backing ConnectionInfo.
type ConnectionMetrics ¶
type ConnectionMetrics struct {
MessagesReceived int64 `json:"messages_received"`
MessagesSent int64 `json:"messages_sent"`
BytesReceived int64 `json:"bytes_received"`
BytesSent int64 `json:"bytes_sent"`
LastPingTime time.Time `json:"last_ping_time"`
LastPongTime time.Time `json:"last_pong_time"`
PingLatencyMs int64 `json:"ping_latency_ms"`
ErrorCount int32 `json:"error_count"`
LastError string `json:"last_error,omitempty"`
ConnectionQuality float64 `json:"connection_quality"` // 0.0-1.0
}
ConnectionMetrics tracks connection performance metrics
func (ConnectionMetrics) TableName ¶
func (ConnectionMetrics) TableName() string
TableName returns the DynamoDB table backing ConnectionMetrics.
type ConnectionState ¶
type ConnectionState string
ConnectionState represents the current state of a WebSocket connection
const ( ConnectionStateConnecting ConnectionState = "connecting" ConnectionStateConnected ConnectionState = "connected" ConnectionStateIdle ConnectionState = "idle" ConnectionStateClosing ConnectionState = "closing" ConnectionStateClosed ConnectionState = "closed" ConnectionStateError ConnectionState = "error" )
Connection state constants
type Conversation ¶
type Conversation struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // CONVERSATION#conversationID
SK string `theorydb:"sk,attr:SK" json:"SK"` // METADATA
// GSI1 is used for participant records (additional records per participant)
// Note: The main conversation record doesn't use GSI1, only participant records do
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"`
// Core fields from legacy
ID string `theorydb:"attr:id" json:"id"`
Participants []string `theorydb:"attr:participants" json:"participants"` // Compatibility IDs: local usernames or remote actor URIs.
ParticipantRefs []ConversationParticipantRef `theorydb:"attr:participantRefs,omitempty" json:"participant_refs,omitempty"`
LastStatusID string `theorydb:"attr:lastStatusID" json:"last_status_id,omitempty"`
Unread bool `theorydb:"-" json:"unread"` // Per-viewer projection only; not stored on the shared row
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Message counting fields
TotalMessageCount int64 `theorydb:"attr:totalMessageCount" json:"total_message_count"` // Total messages in conversation
LastMessageTime time.Time `theorydb:"attr:lastMessageTime" json:"last_message_time,omitempty"` // Time of last message
// ViewerState is a runtime-only projection of the canonical per-user DM row that
// powered a list read. It lets callers build list responses from canonical state
// without reloading compatibility participant snapshots.
ViewerState *UserConversationState `theorydb:"-" json:"-"`
// contains filtered or unexported fields
}
Conversation represents a direct message conversation between users
func (*Conversation) BeforeCreate ¶
func (c *Conversation) BeforeCreate() error
BeforeCreate sets up the keys before creating a conversation
func (Conversation) TableName ¶
func (Conversation) TableName() string
TableName returns the DynamoDB table name
func (*Conversation) UpdateKeys ¶
func (c *Conversation) UpdateKeys() error
UpdateKeys updates GSI keys - for conversation, this is mainly used for participant records
type ConversationMessage ¶
type ConversationMessage struct {
// Primary keys as specified in instructions
PK string `theorydb:"pk,attr:PK" json:"PK"` // CONVERSATION#conversationID
SK string `theorydb:"sk,attr:SK" json:"SK"` // STATUS#timestamp#statusID
// Fields from instructions
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id"`
StatusID string `theorydb:"attr:statusID" json:"status_id"`
SenderUsername string `theorydb:"attr:senderUsername" json:"sender_username"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ReadBy map[string]time.Time `theorydb:"attr:readBy" json:"read_by,omitempty"` // username -> read timestamp
// TTL for message retention (optional)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ConversationMessage represents a message/status within a conversation. Note: Based on the legacy code and instructions, this appears to be handled differently - messages are stored as regular Status objects with conversation context The instructions mention PK=CONVERSATION#id, SK=STATUS#timestamp#statusID but the legacy code doesn't show this pattern being used. This model is included for completeness based on the instructions.
Legacy note: DM rewrite M3/M8 removes ConversationMessage from live DM write logic.
func (*ConversationMessage) BeforeCreate ¶
func (m *ConversationMessage) BeforeCreate() error
BeforeCreate sets up the keys before creating a message record
func (*ConversationMessage) GetPK ¶
func (m *ConversationMessage) GetPK() string
GetPK returns the partition key
func (*ConversationMessage) GetSK ¶
func (m *ConversationMessage) GetSK() string
GetSK returns the sort key
func (ConversationMessage) TableName ¶
func (ConversationMessage) TableName() string
TableName returns the DynamoDB table name
func (*ConversationMessage) UpdateKeys ¶
func (m *ConversationMessage) UpdateKeys() error
UpdateKeys updates the composite keys based on conversation ID and status ID
type ConversationMute ¶
type ConversationMute struct {
// Composite keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// TTL for auto-expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// Business fields
Username string `theorydb:"attr:username" json:"username"`
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at,omitempty"`
// contains filtered or unexported fields
}
ConversationMute represents a muted conversation thread in DynamoDB
func (*ConversationMute) BeforeCreate ¶
func (c *ConversationMute) BeforeCreate() error
BeforeCreate sets up the keys before creating a mute
func (*ConversationMute) GetPK ¶
func (c *ConversationMute) GetPK() string
GetPK returns the partition key
func (*ConversationMute) GetSK ¶
func (c *ConversationMute) GetSK() string
GetSK returns the sort key
func (ConversationMute) TableName ¶
func (ConversationMute) TableName() string
TableName returns the DynamoDB table name
func (*ConversationMute) UpdateKeys ¶
func (c *ConversationMute) UpdateKeys() error
UpdateKeys updates the composite keys based on the username and conversation ID
type ConversationParticipantKey ¶
type ConversationParticipantKey struct {
PK string `theorydb:"pk,attr:PK" json:"PK"`
SK string `theorydb:"sk,attr:SK" json:"SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"`
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id"`
// contains filtered or unexported fields
}
ConversationParticipantKey is used for looking up conversations by exact participants Legacy uses GSI1PK = CONVERSATION_PARTICIPANTS#sorted_participants_list
func (*ConversationParticipantKey) GetPK ¶
func (k *ConversationParticipantKey) GetPK() string
GetPK returns the partition key
func (*ConversationParticipantKey) GetSK ¶
func (k *ConversationParticipantKey) GetSK() string
GetSK returns the sort key
func (ConversationParticipantKey) TableName ¶
func (ConversationParticipantKey) TableName() string
TableName returns the DynamoDB table name
func (*ConversationParticipantKey) UpdateKeys ¶
func (k *ConversationParticipantKey) UpdateKeys() error
UpdateKeys updates the composite keys based on conversation ID
type ConversationParticipantRecord ¶
type ConversationParticipantRecord struct {
// Legacy key material preserved for compatibility with older tests and cursors.
PK string `theorydb:"pk,attr:PK" json:"PK"` // USER_CONVERSATIONS#username
SK string `theorydb:"sk,attr:SK" json:"SK"` // timestamp#conversationID (for sorting by recent)
// GSI1 for reverse lookup (find participants by conversation)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // CONVERSATION#conversationID
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // PARTICIPANT#username
ViewerID string `theorydb:"-" json:"viewer_id,omitempty"`
ConversationID string `theorydb:"-" json:"conversation_id,omitempty"`
CounterpartID string `theorydb:"-" json:"counterpart_id,omitempty"`
Folder UserConversationFolder `theorydb:"-" json:"folder,omitempty"`
// Per-participant DM metadata (folder/request lifecycle, deletion, unread).
RequestState DmRequestState `theorydb:"attr:requestState" json:"request_state,omitempty"`
RequestedAt *time.Time `theorydb:"attr:requestedAt" json:"requested_at,omitempty"`
AcceptedAt *time.Time `theorydb:"attr:acceptedAt" json:"accepted_at,omitempty"`
DeclinedAt *time.Time `theorydb:"attr:declinedAt" json:"declined_at,omitempty"`
DeletedAt *time.Time `theorydb:"attr:deletedAt" json:"deleted_at,omitempty"`
Unread bool `theorydb:"attr:unread" json:"unread"`
LastReadAt *time.Time `theorydb:"attr:lastReadAt" json:"last_read_at,omitempty"`
PreviewStatusID string `theorydb:"-" json:"preview_status_id,omitempty"`
PreviewStatusPublishedAt time.Time `theorydb:"-" json:"preview_status_published_at,omitempty"`
SortAt time.Time `theorydb:"-" json:"sort_at,omitempty"`
UpdatedAt time.Time `theorydb:"-" json:"updated_at,omitempty"`
// Conversation is the hydrated runtime view used by repository callers.
Conversation *Conversation `theorydb:"-" json:"-"`
// contains filtered or unexported fields
}
ConversationParticipantRecord is a compatibility projection used by older DM call sites. The canonical stored row is UserConversationState; this type intentionally does not own any nested conversation snapshot.
func (*ConversationParticipantRecord) BeforeCreate ¶
func (p *ConversationParticipantRecord) BeforeCreate(participantID string) error
BeforeCreate sets up the keys for a participant record
func (*ConversationParticipantRecord) GetPK ¶
func (p *ConversationParticipantRecord) GetPK() string
GetPK returns the partition key
func (*ConversationParticipantRecord) GetSK ¶
func (p *ConversationParticipantRecord) GetSK() string
GetSK returns the sort key
func (ConversationParticipantRecord) TableName ¶
func (ConversationParticipantRecord) TableName() string
TableName returns the DynamoDB table name
func (*ConversationParticipantRecord) UpdateKeys ¶
func (p *ConversationParticipantRecord) UpdateKeys() error
UpdateKeys updates the GSI keys for the participant record
type ConversationParticipantRef ¶ added in v1.2.51
type ConversationParticipantRef struct {
ParticipantType ConversationParticipantType `theorydb:"attr:participantType" json:"participant_type"`
ParticipantID string `theorydb:"attr:participantID" json:"participant_id"`
Acct string `theorydb:"attr:acct,omitempty" json:"acct,omitempty"`
Domain string `theorydb:"attr:domain,omitempty" json:"domain,omitempty"`
ResolvedAt *time.Time `theorydb:"attr:resolvedAt,omitempty" json:"resolved_at,omitempty"`
}
ConversationParticipantRef is the typed participant identity stored alongside the legacy participant ID list. Participants remains the compatibility field; ParticipantRefs is the durable source of truth for federated conversations.
func NormalizeConversationParticipantRef ¶ added in v1.2.51
func NormalizeConversationParticipantRef(ref ConversationParticipantRef) ConversationParticipantRef
NormalizeConversationParticipantRef canonicalizes a typed participant ref for durable storage.
func NormalizeConversationParticipantRefs ¶ added in v1.2.51
func NormalizeConversationParticipantRefs(refs []ConversationParticipantRef) []ConversationParticipantRef
NormalizeConversationParticipantRefs canonicalizes, de-duplicates, and sorts typed participants.
type ConversationParticipantType ¶ added in v1.2.51
type ConversationParticipantType string
ConversationParticipantType identifies the durable identity class for a conversation participant. It is intentionally explicit so remote actor URLs, local usernames, and future agent identities do not depend on ID-shape inference as the source of truth.
const ( // ConversationParticipantTypeLocalUser represents a local lesser account. ConversationParticipantTypeLocalUser ConversationParticipantType = "local_user" // ConversationParticipantTypeRemoteActor represents a federated ActivityPub actor. ConversationParticipantTypeRemoteActor ConversationParticipantType = "remote_actor" )
type ConversationStatus ¶
type ConversationStatus struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // CONVERSATION_STATUS#conversationID
SK string `theorydb:"sk,attr:SK" json:"SK"` // USER#username
// Core fields from storage.ConversationStatus
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id"`
UserID string `theorydb:"attr:userID" json:"user_id"` // username
Unread bool `theorydb:"attr:unread" json:"unread"`
LastReadAt time.Time `theorydb:"attr:lastReadAt" json:"last_read_at"`
// contains filtered or unexported fields
}
ConversationStatus represents a user's read status for a conversation. This tracks whether a user has unread messages in a conversation.
Legacy note: DM rewrite M4 removes ConversationStatus as the canonical owner of DM unread state.
func (*ConversationStatus) BeforeCreate ¶
func (s *ConversationStatus) BeforeCreate() error
BeforeCreate sets up the keys before creating a status record
func (*ConversationStatus) GetPK ¶
func (s *ConversationStatus) GetPK() string
GetPK returns the partition key
func (*ConversationStatus) GetSK ¶
func (s *ConversationStatus) GetSK() string
GetSK returns the sort key
func (ConversationStatus) TableName ¶
func (ConversationStatus) TableName() string
TableName returns the DynamoDB table name
func (*ConversationStatus) UpdateKeys ¶
func (s *ConversationStatus) UpdateKeys() error
UpdateKeys updates the composite keys based on conversation ID and user ID
type CostProjection ¶
type CostProjection struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // COST#PROJECTION
SK string `theorydb:"sk,attr:SK" json:"-"` // {period}#{timestamp}
// Attributes from interface
Period string `theorydb:"attr:period" json:"period"`
CurrentCost float64 `theorydb:"attr:currentCost" json:"current_cost"`
ProjectedCost float64 `theorydb:"attr:projectedCost" json:"projected_cost"`
Variance float64 `theorydb:"attr:variance" json:"variance"`
TopDrivers []Driver `theorydb:"attr:topDrivers" json:"top_drivers"`
Recommendations []string `theorydb:"attr:recommendations" json:"recommendations"`
// Additional metadata
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CalculatedAt time.Time `theorydb:"attr:calculatedAt" json:"calculated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 90 days retention
// contains filtered or unexported fields
}
CostProjection represents projected costs for federation
func NewCostProjection ¶
func NewCostProjection(period string) *CostProjection
NewCostProjection creates a new cost projection
func (*CostProjection) AddDriver ¶
func (c *CostProjection) AddDriver(driver Driver)
AddDriver adds a cost driver and sorts by cost
func (*CostProjection) CalculateVariance ¶
func (c *CostProjection) CalculateVariance()
CalculateVariance calculates the variance between current and projected costs
func (*CostProjection) GenerateRecommendations ¶
func (c *CostProjection) GenerateRecommendations()
GenerateRecommendations creates recommendations based on the projection
func (*CostProjection) IsOverBudget ¶
func (c *CostProjection) IsOverBudget(budgetLimit float64) bool
IsOverBudget checks if projected cost exceeds a threshold
func (CostProjection) TableName ¶
func (CostProjection) TableName() string
TableName returns the DynamoDB table backing CostProjection.
func (*CostProjection) UpdateKeys ¶
func (c *CostProjection) UpdateKeys()
UpdateKeys updates the partition and sort keys
type CustomEmoji ¶
type CustomEmoji struct {
Shortcode string `json:"shortcode"`
URL string `json:"url"`
StaticURL string `json:"static_url"`
VisibleInPicker bool `json:"visible_in_picker"`
Category string `json:"category,omitempty"`
}
CustomEmoji represents a custom emoji used in announcements
func (CustomEmoji) TableName ¶
func (CustomEmoji) TableName() string
TableName returns the DynamoDB table backing CustomEmoji.
type DLQMessage ¶
type DLQMessage struct {
// Primary key - service and date for partitioning
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "DLQ#service#date"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "MSG#timestamp#messageId"
// GSI1 - Error type analysis
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "DLQ_ERROR#errorType"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{service}#{messageId}"
// GSI2 - Retry analysis and reprocessing
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "DLQ_RETRY#{service}#{status}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{messageId}"
// GSI3 - Service-wide analysis
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "DLQ_SERVICE#{service}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{timestamp}#{errorType}#{messageId}"
// Core message data
ID string `theorydb:"attr:id" json:"id"` // Unique DLQ message ID
OriginalMessageID string `theorydb:"attr:originalMessageID" json:"original_message_id"` // Original SQS message ID
Service string `theorydb:"attr:service" json:"service"` // Service that failed (e.g., "notification-processor")
QueueName string `theorydb:"attr:queueName" json:"queue_name"` // Name of the source DLQ
SourceQueue string `theorydb:"attr:sourceQueue" json:"source_queue"` // Original queue name
// Message content
MessageBody string `theorydb:"attr:messageBody" json:"message_body"` // Original message body
MessageAttributes map[string]string `theorydb:"attr:messageAttributes" json:"message_attributes,omitempty"` // SQS message attributes
MessageMetadata map[string]interface{} `theorydb:"attr:messageMetadata" json:"message_metadata,omitempty"` // Additional metadata
// Error information
ErrorType string `theorydb:"attr:errorType" json:"error_type"` // Categorized error type
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message"` // Full error message
ErrorStack string `theorydb:"attr:errorStack" json:"error_stack,omitempty"` // Stack trace if available
FailureReason string `theorydb:"attr:failureReason" json:"failure_reason"` // Human-readable failure reason
IsPermanent bool `theorydb:"attr:isPermanent" json:"is_permanent"` // Whether this is a permanent failure
// Processing context
FunctionName string `theorydb:"attr:functionName" json:"function_name"` // Lambda function that failed
FunctionVersion string `theorydb:"attr:functionVersion" json:"function_version,omitempty"` // Lambda function version
LogGroup string `theorydb:"attr:logGroup" json:"log_group,omitempty"` // CloudWatch log group
LogStream string `theorydb:"attr:logStream" json:"log_stream,omitempty"` // CloudWatch log stream
RequestID string `theorydb:"attr:requestID" json:"request_id,omitempty"` // AWS request ID
// Retry information
OriginalRetryCount int `theorydb:"attr:originalRetryCount" json:"original_retry_count"` // How many times original message was retried
ReprocessingCount int `theorydb:"attr:reprocessingCount" json:"reprocessing_count"` // How many times we've tried to reprocess
MaxReprocessAttempts int `theorydb:"attr:maxReprocessAttempts" json:"max_reprocess_attempts"` // Maximum reprocessing attempts
NextRetryAt *time.Time `theorydb:"attr:nextRetryAt" json:"next_retry_at,omitempty"` // When to retry next
Status string `theorydb:"attr:status" json:"status"` // "new", "reprocessing", "failed", "resolved", "abandoned"
// Analysis metadata
SimilarityHash string `theorydb:"attr:similarityHash" json:"similarity_hash"` // Hash for grouping similar errors
Tags []string `theorydb:"attr:tags" json:"tags,omitempty"` // Tags for categorization
Priority string `theorydb:"attr:priority" json:"priority"` // "low", "medium", "high", "critical"
BusinessImpact string `theorydb:"attr:businessImpact" json:"business_impact,omitempty"` // Impact assessment
// Cost tracking
ProcessingCostMicroCents int64 `theorydb:"attr:processingCostMicroCents" json:"processing_cost_micro_cents"` // Cost of processing attempts
ReprocessingCostMicroCents int64 `theorydb:"attr:reprocessingCostMicroCents" json:"reprocessing_cost_micro_cents"` // Cost of reprocessing
// Timestamps
FirstSeenAt time.Time `theorydb:"attr:firstSeenAt" json:"first_seen_at"` // When first captured in DLQ
LastProcessedAt *time.Time `theorydb:"attr:lastProcessedAt" json:"last_processed_at,omitempty"` // Last processing attempt
ResolvedAt *time.Time `theorydb:"attr:resolvedAt" json:"resolved_at,omitempty"` // When successfully reprocessed
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (90 days for DLQ messages)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
DLQMessage represents a failed message captured from a dead letter queue
func NewDependencyErrorDLQ ¶
func NewDependencyErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
NewDependencyErrorDLQ creates a DLQ message for dependency errors
func NewProcessingErrorDLQ ¶
func NewProcessingErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
NewProcessingErrorDLQ creates a DLQ message for processing errors
func NewTransientErrorDLQ ¶
func NewTransientErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
NewTransientErrorDLQ creates a DLQ message for transient errors
func NewValidationErrorDLQ ¶
func NewValidationErrorDLQ(service, messageID, body, errorMsg string) *DLQMessage
NewValidationErrorDLQ creates a DLQ message for validation errors
func (*DLQMessage) AddTag ¶
func (d *DLQMessage) AddTag(tag string)
AddTag adds a tag to the message
func (*DLQMessage) BeforeCreate ¶
func (d *DLQMessage) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*DLQMessage) BeforeUpdate ¶
func (d *DLQMessage) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*DLQMessage) CanReprocess ¶
func (d *DLQMessage) CanReprocess() bool
CanReprocess determines if the message can be reprocessed
func (*DLQMessage) GetMetadata ¶
func (d *DLQMessage) GetMetadata(key string) (interface{}, bool)
GetMetadata gets a metadata field
func (*DLQMessage) GetPK ¶
func (d *DLQMessage) GetPK() string
GetPK returns the partition key (required by BaseModel interface)
func (*DLQMessage) GetSK ¶
func (d *DLQMessage) GetSK() string
GetSK returns the sort key (required by BaseModel interface)
func (*DLQMessage) GetTotalCost ¶
func (d *DLQMessage) GetTotalCost() int64
GetTotalCost returns the total cost for this message
func (*DLQMessage) MarkAbandoned ¶
func (d *DLQMessage) MarkAbandoned()
MarkAbandoned marks the message as abandoned (too many failures)
func (*DLQMessage) MarkFailed ¶
func (d *DLQMessage) MarkFailed(errorMsg string)
MarkFailed marks the message as failed during reprocessing
func (*DLQMessage) MarkForReprocessing ¶
func (d *DLQMessage) MarkForReprocessing()
MarkForReprocessing marks the message for reprocessing
func (*DLQMessage) MarkResolved ¶
func (d *DLQMessage) MarkResolved()
MarkResolved marks the message as successfully reprocessed
func (*DLQMessage) SetMetadata ¶
func (d *DLQMessage) SetMetadata(key string, value interface{})
SetMetadata sets a metadata field
func (*DLQMessage) ShouldAbandon ¶
func (d *DLQMessage) ShouldAbandon() bool
ShouldAbandon determines if the message should be abandoned
func (DLQMessage) TableName ¶
func (DLQMessage) TableName() string
TableName returns the DynamoDB table name for the DLQMessage model
func (*DLQMessage) UpdateCosts ¶
func (d *DLQMessage) UpdateCosts(processingCost, reprocessingCost int64)
UpdateCosts updates the processing costs
func (*DLQMessage) UpdateKeys ¶
func (d *DLQMessage) UpdateKeys() error
UpdateKeys updates the GSI keys for this DLQ message (required by DynamORM)
func (*DLQMessage) Validate ¶
func (d *DLQMessage) Validate() error
Validate performs validation on the DLQMessage using centralized validation
type DLQMessageBuilder ¶
type DLQMessageBuilder struct {
// contains filtered or unexported fields
}
DLQMessageBuilder helps create DLQ messages with proper defaults
func NewDLQMessageBuilder ¶
func NewDLQMessageBuilder() *DLQMessageBuilder
NewDLQMessageBuilder creates a new DLQ message builder
func (*DLQMessageBuilder) Build ¶
func (b *DLQMessageBuilder) Build() *DLQMessage
Build creates the DLQ message
func (*DLQMessageBuilder) ForService ¶
func (b *DLQMessageBuilder) ForService(service string) *DLQMessageBuilder
ForService sets the service name
func (*DLQMessageBuilder) MarkAsPermanent ¶
func (b *DLQMessageBuilder) MarkAsPermanent() *DLQMessageBuilder
MarkAsPermanent marks the failure as permanent
func (DLQMessageBuilder) TableName ¶
func (DLQMessageBuilder) TableName() string
TableName returns the DynamoDB table backing DLQMessageBuilder.
func (*DLQMessageBuilder) WithAttributes ¶
func (b *DLQMessageBuilder) WithAttributes(attributes map[string]string) *DLQMessageBuilder
WithAttributes sets message attributes
func (*DLQMessageBuilder) WithBusinessImpact ¶
func (b *DLQMessageBuilder) WithBusinessImpact(impact string) *DLQMessageBuilder
WithBusinessImpact sets the business impact assessment
func (*DLQMessageBuilder) WithContext ¶
func (b *DLQMessageBuilder) WithContext(functionName, logGroup, logStream, requestID string) *DLQMessageBuilder
WithContext sets the processing context
func (*DLQMessageBuilder) WithError ¶
func (b *DLQMessageBuilder) WithError(errorType, errorMessage, errorStack string) *DLQMessageBuilder
WithError sets the error information
func (*DLQMessageBuilder) WithFailureReason ¶
func (b *DLQMessageBuilder) WithFailureReason(reason string) *DLQMessageBuilder
WithFailureReason sets a human-readable failure reason
func (*DLQMessageBuilder) WithMetadata ¶
func (b *DLQMessageBuilder) WithMetadata(metadata map[string]interface{}) *DLQMessageBuilder
WithMetadata adds metadata
func (*DLQMessageBuilder) WithOriginalMessage ¶
func (b *DLQMessageBuilder) WithOriginalMessage(messageID, body string) *DLQMessageBuilder
WithOriginalMessage sets the original message details
func (*DLQMessageBuilder) WithPriority ¶
func (b *DLQMessageBuilder) WithPriority(priority string) *DLQMessageBuilder
WithPriority sets the priority level
func (*DLQMessageBuilder) WithQueue ¶
func (b *DLQMessageBuilder) WithQueue(queueName, sourceQueue string) *DLQMessageBuilder
WithQueue sets the queue information
func (*DLQMessageBuilder) WithRetryInfo ¶
func (b *DLQMessageBuilder) WithRetryInfo(originalRetryCount, maxReprocessAttempts int) *DLQMessageBuilder
WithRetryInfo sets retry information
func (*DLQMessageBuilder) WithTags ¶
func (b *DLQMessageBuilder) WithTags(tags ...string) *DLQMessageBuilder
WithTags adds tags to the message
type DNSCache ¶
type DNSCache struct {
// Keys - EXACT pattern from legacy: PK=DNSCACHE#hostname, SK=ENTRY
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Business fields matching legacy implementation
Hostname string `theorydb:"attr:hostname" json:"hostname"`
IPs []string `theorydb:"attr:ips" json:"ips"`
ResolvedAt time.Time `theorydb:"attr:resolvedAt" json:"resolved_at"`
TTL int `theorydb:"-" json:"ttl"` // seconds; request metadata, not persisted in v2
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp for DynamoDB TTL
// contains filtered or unexported fields
}
DNSCache represents a cached DNS lookup result in DynamoDB
func (*DNSCache) UpdateKeys ¶
UpdateKeys sets the composite key values for DynamoDB
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) TableName ¶
func (DeadLetterMessage) TableName() string
TableName returns the DynamoDB table backing DeadLetterMessage.
func (*DeadLetterMessage) UpdateKeys ¶
func (d *DeadLetterMessage) UpdateKeys() error
UpdateKeys sets the partition and sort keys
type DeliveryStatus ¶
type DeliveryStatus struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI fields for failed delivery queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// Business fields
ActivityID string `theorydb:"attr:activityID" json:"activity_id"`
TargetDomain string `theorydb:"attr:targetDomain" json:"target_domain"`
Status string `theorydb:"attr:status" json:"status"` // pending/delivered/failed
Attempts int `theorydb:"attr:attempts" json:"attempts"` // Number of delivery attempts
LastAttempt time.Time `theorydb:"attr:lastAttempt" json:"last_attempt"` // Time of last delivery attempt
Error string `theorydb:"attr:error" json:"error,omitempty"` // Error message if failed
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
DeliveredAt time.Time `theorydb:"attr:deliveredAt" json:"delivered_at,omitempty"`
NextRetry time.Time `theorydb:"attr:nextRetry" json:"next_retry,omitempty"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // For automatic cleanup
// contains filtered or unexported fields
}
DeliveryStatus tracks the delivery status of activities to remote instances
func (DeliveryStatus) TableName ¶
func (DeliveryStatus) TableName() string
TableName returns the DynamoDB table backing DeliveryStatus.
func (*DeliveryStatus) UpdateKeys ¶
func (d *DeliveryStatus) UpdateKeys()
UpdateKeys updates the composite keys based on the delivery status data
type Device ¶
type Device struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // USER#username
SK string `theorydb:"sk,attr:SK" json:"-"` // DEVICE#deviceID
// GSI for querying devices by last seen
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // USER#username#DEVICES
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // {lastSeenAt}#{deviceID}
// GSI for trust level monitoring
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // TRUST_LEVEL#{trustLevel}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // {lastSeenAt}#{deviceID}
// GSI for direct deviceID lookup (login/session flows)
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // DEVICEID#{deviceID}
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // USER#{username}
// Device data
DeviceID string `theorydb:"attr:deviceID" json:"device_id"`
Username string `theorydb:"attr:username" json:"username"`
DeviceName string `theorydb:"attr:deviceName" json:"device_name"`
DeviceType string `theorydb:"attr:deviceType" json:"device_type"` // web, mobile, desktop
LastIPAddress string `theorydb:"attr:lastIPAddress" json:"last_ip_address"`
LastUserAgent string `theorydb:"attr:lastUserAgent" json:"last_user_agent"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
LastSeenAt time.Time `theorydb:"attr:lastSeenAt" json:"last_seen_at"`
TrustLevel string `theorydb:"attr:trustLevel" json:"trust_level"` // trusted, untrusted, suspicious
Platform string `theorydb:"attr:platform" json:"platform,omitempty"` // iOS, Android, Windows, etc.
AppVersion string `theorydb:"attr:appVersion" json:"app_version,omitempty"`
Location string `theorydb:"attr:location" json:"location,omitempty"` // Approximate location
Active bool `theorydb:"attr:active" json:"active"`
// TTL for auto-cleanup of inactive devices (90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Device represents a user's device/session stored in DynamoDB
func (*Device) SetTrustLevel ¶
SetTrustLevel updates the device trust level
func (*Device) UpdateKeys ¶
func (d *Device) UpdateKeys()
UpdateKeys updates the GSI keys based on the device data
func (*Device) UpdateLastSeen ¶
UpdateLastSeen updates the last seen timestamp and related fields
type DimensionStats ¶
type DimensionStats struct {
Value string `json:"value"`
Count int64 `json:"count"`
Sum float64 `json:"sum"`
Average float64 `json:"average"`
Min float64 `json:"min"`
Max float64 `json:"max"`
}
DimensionStats represents statistics for a specific dimension value
func (DimensionStats) TableName ¶
func (DimensionStats) TableName() string
TableName returns the DynamoDB table backing DimensionStats.
type DirectMessageMigrationState ¶ added in v1.1.73
type DirectMessageMigrationState struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
WritesFrozen bool `theorydb:"attr:writesFrozen" json:"writes_frozen"`
Phase string `theorydb:"attr:phase,omitempty" json:"phase,omitempty"`
Reason string `theorydb:"attr:reason,omitempty" json:"reason,omitempty"`
Owner string `theorydb:"attr:owner,omitempty" json:"owner,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
DirectMessageMigrationState stores the live DM migration lock used to freeze DM writes while canonical state backfills and legacy-row cleanup are running.
func (*DirectMessageMigrationState) BeforeCreate ¶ added in v1.1.73
func (s *DirectMessageMigrationState) BeforeCreate() error
BeforeCreate initializes keys and timestamps before create.
func (*DirectMessageMigrationState) BeforeUpdate ¶ added in v1.1.73
func (s *DirectMessageMigrationState) BeforeUpdate() error
BeforeUpdate refreshes keys and updatedAt before update.
func (*DirectMessageMigrationState) GetPK ¶ added in v1.1.73
func (s *DirectMessageMigrationState) GetPK() string
GetPK returns the partition key.
func (*DirectMessageMigrationState) GetSK ¶ added in v1.1.73
func (s *DirectMessageMigrationState) GetSK() string
GetSK returns the sort key.
func (DirectMessageMigrationState) TableName ¶ added in v1.1.73
func (DirectMessageMigrationState) TableName() string
TableName returns the DynamoDB table name.
func (*DirectMessageMigrationState) UpdateKeys ¶ added in v1.1.73
func (s *DirectMessageMigrationState) UpdateKeys() error
UpdateKeys sets the singleton key material.
type DirectMessageSendTransition ¶ added in v1.1.73
type DirectMessageSendTransition struct {
Conversation *Conversation
Status *Status
ParticipantStates []*UserConversationState
ExpectedParticipantStates []*UserConversationState
CreateConversation bool
}
DirectMessageSendTransition is the repository-owned DM send write set. It captures the status row, shared conversation metadata, and the per-local-user canonical state owner rows that must move together for one send.
type DirectMessageTombstone ¶ added in v0.1.36
type DirectMessageTombstone struct {
PK string `theorydb:"pk,attr:PK" json:"PK"` // DM_MESSAGE_TOMBSTONE#viewerUsername
SK string `theorydb:"sk,attr:SK" json:"SK"` // STATUS#statusID
ViewerUsername string `theorydb:"attr:viewerUsername" json:"viewer_username"`
StatusID string `theorydb:"attr:statusID" json:"status_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
DirectMessageTombstone represents a per-viewer deletion marker for a direct message (Status). It enables "delete for me" semantics without deleting the underlying status globally.
Primary keying is (viewerUsername, statusID).
func (*DirectMessageTombstone) GetPK ¶ added in v0.1.36
func (t *DirectMessageTombstone) GetPK() string
GetPK returns the record's partition key.
func (*DirectMessageTombstone) GetSK ¶ added in v0.1.36
func (t *DirectMessageTombstone) GetSK() string
GetSK returns the record's sort key.
func (DirectMessageTombstone) TableName ¶ added in v0.1.36
func (DirectMessageTombstone) TableName() string
TableName returns the DynamoDB table name.
func (*DirectMessageTombstone) UpdateKeys ¶ added in v0.1.36
func (t *DirectMessageTombstone) UpdateKeys() error
UpdateKeys populates keys and timestamps before persistence.
type DmRequestState ¶ added in v0.1.36
type DmRequestState string
DmRequestState represents the per-user request lifecycle state for a DM thread. It is stored on ConversationParticipantRecord (not on the shared Conversation).
const ( // DmRequestStatePending indicates the participant has not yet accepted or declined the request. DmRequestStatePending DmRequestState = "PENDING" // DmRequestStateAccepted indicates the participant has accepted the request. DmRequestStateAccepted DmRequestState = "ACCEPTED" // DmRequestStateDeclined indicates the participant has declined the request. DmRequestStateDeclined DmRequestState = "DECLINED" )
type DomainAllow ¶
type DomainAllow struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ID string `theorydb:"attr:id" json:"ID"`
Domain string `theorydb:"attr:domain" json:"Domain"`
CreatedBy string `theorydb:"attr:createdBy" json:"CreatedBy"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
// contains filtered or unexported fields
}
DomainAllow represents a domain in the allowlist
func (*DomainAllow) GetDomain ¶
func (d *DomainAllow) GetDomain() string
GetDomain returns the domain of the domain allow
func (*DomainAllow) GetID ¶
func (d *DomainAllow) GetID() string
GetID returns the ID of the domain allow
func (*DomainAllow) GetPK ¶
func (d *DomainAllow) GetPK() string
GetPK returns the primary key of the domain allow
func (*DomainAllow) GetSK ¶
func (d *DomainAllow) GetSK() string
GetSK returns the sort key of the domain allow
func (DomainAllow) TableName ¶
func (DomainAllow) TableName() string
TableName returns the DynamoDB table backing DomainAllow.
func (*DomainAllow) UpdateKeys ¶
func (d *DomainAllow) UpdateKeys() error
UpdateKeys updates the keys for the domain allow
type DomainCounter ¶ added in v1.6.24
type DomainCounter struct {
PK string `theorydb:"pk,attr:PK"` // DOMAIN#<host>
SK string `theorydb:"sk,attr:SK"` // COUNTER
Domain string `theorydb:"attr:domain" json:"domain"`
Value int64 `theorydb:"attr:value" json:"value"` // actor count for the domain
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
DomainCounter tracks how many actor records exist per domain (host of the actor ID) and doubles as the dedupe marker for the TOTAL_DOMAINS instance counter: the item is created on the first actor of a domain and removed when the last actor of that domain is deleted.
func (*DomainCounter) GetPK ¶ added in v1.6.24
func (d *DomainCounter) GetPK() string
GetPK returns the partition key.
func (*DomainCounter) GetSK ¶ added in v1.6.24
func (d *DomainCounter) GetSK() string
GetSK returns the sort key.
func (DomainCounter) TableName ¶ added in v1.6.24
func (DomainCounter) TableName() string
TableName returns the DynamoDB table backing DomainCounter.
func (*DomainCounter) UpdateKeys ¶ added in v1.6.24
func (d *DomainCounter) UpdateKeys() error
UpdateKeys derives PK/SK for DomainCounter.
type Draft ¶
type Draft struct {
// Primary keys: USER#{author_id}#DRAFT / ID#{draft_id}
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI1: Object drafts - OBJECT#{object_id}#DRAFT / TIME#{updated_at}
// Allows finding all drafts for a specific published object
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// GSI4: Scheduled publishing + status index - DRAFT#STATUS#{status} / TIME#{timestamp}#AUTHOR#{author_id}#ID#{draft_id}
// Allows finding drafts by status, and enables scheduled publishing workers to query due drafts efficiently.
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty"`
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty"`
// Core fields
ID string `theorydb:"attr:id" json:"id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
ObjectID *string `theorydb:"attr:objectID" json:"object_id,omitempty"` // nil = new, set = editing existing
// Content
ContentType string `theorydb:"attr:contentType" json:"content_type"` // Note, Article
Title string `theorydb:"attr:title" json:"title,omitempty"` // For Article
Slug string `theorydb:"attr:slug" json:"slug,omitempty"`
Content string `theorydb:"attr:content" json:"content"`
ContentFormat string `theorydb:"attr:contentFormat" json:"content_format"` // html, markdown
// Draft state
Status string `theorydb:"attr:status" json:"status"` // draft, scheduled, publishing, failed
ScheduledAt *time.Time `theorydb:"attr:scheduledAt" json:"scheduled_at,omitempty"`
PublishFailureReason string `theorydb:"attr:publishFailureReason" json:"publish_failure_reason,omitempty"`
// PublishAttemptedAt records the moment the draft transitioned into the
// publishing status. It is written ONLY by the publish transition's
// field-scoped repository lane (TransitionDraftToPublishing); content
// writers never select the attribute, so an author editing a crash-stuck
// publishing draft cannot re-arm the orphan-reconciliation stale-publishing
// horizon by advancing UpdatedAt. Absent on rows that never entered
// publishing and on legacy publishing rows that predate the attribute;
// those fall back to UpdatedAt for the sweep horizon.
PublishAttemptedAt *time.Time `theorydb:"attr:publishAttemptedAt,omitempty" json:"publish_attempted_at,omitempty"`
// Metadata snapshot (full object metadata for preview)
MetadataJSON string `theorydb:"attr:metadataJSON" json:"metadata_json,omitempty"`
// EditorialMedia is an ordered, modeled association with internal media.
// M2 will bind these usages into revision integrity and publication state.
EditorialMedia []DraftMediaUsage `theorydb:"attr:editorialMedia,omitempty" json:"editorial_media,omitempty"`
// Authoring attribution
GeneratedBy string `theorydb:"attr:generatedBy,omitempty" json:"generated_by,omitempty"`
ReviewedBy string `theorydb:"attr:reviewedBy,omitempty" json:"reviewed_by,omitempty"`
ReviewStatus string `theorydb:"attr:reviewStatus,omitempty" json:"review_status,omitempty"`
EditorNotes string `theorydb:"attr:editorNotes,omitempty" json:"editor_notes,omitempty"`
// ActedBy records the local actor URI of the caller who acted on the
// author's behalf under an active share grant (empty when the author
// acted as themselves).
ActedBy string `theorydb:"attr:actedBy,omitempty" json:"acted_by,omitempty"`
// Autosave tracking
AutosaveVersion int `theorydb:"attr:autosaveVersion" json:"autosave_version"`
LastSavedAt time.Time `theorydb:"attr:lastSavedAt" json:"last_saved_at"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// ModelVersion provides optimistic concurrency for the field-scoped
// editorial-media writer (UpdateDraftEditorialMedia), closing the
// setDraftEditorialMedia lost-update seam with a version-conditioned CAS.
// It is deliberately NOT tagged theorydb:"version": that tag would arm
// TableTheory's automatic optimistic lock on every full-model content write
// (UpdateDraft/autosave), whose condition (`version = <read>`) fails in real
// DynamoDB for pre-M4 rows that never carried the attribute — every existing
// draft would break on its next content save. The media lane instead
// conditions explicitly (attribute_exists AND (attribute_not_exists OR
// version = read)), migrating pre-version rows on their first media write.
// The omitempty modifier keeps content writers from selecting a zero-valued
// version and resetting a versioned row; a fetched non-zero version
// round-trips unchanged because the field is not auto-incremented.
ModelVersion int `theorydb:"attr:modelVersion,omitempty" json:"-"`
}
Draft represents an unpublished content draft
func (*Draft) UpdateKeys ¶
UpdateKeys updates the keys for the Draft model
type DraftMediaUsage ¶ added in v1.6.23
type DraftMediaUsage struct {
MediaID string `json:"media_id"`
Role EditorialMediaRole `json:"role"`
InlinePosition *int `json:"inline_position,omitempty"`
Caption string `json:"caption,omitempty"`
CreditLine string `json:"credit_line,omitempty"`
AltText string `json:"alt_text,omitempty"`
Focus string `json:"focus,omitempty"`
}
DraftMediaUsage is per-draft editorial presentation metadata for an asset. InlinePosition is zero-based and required only for inline assets.
func NormalizeDraftMediaUsages ¶ added in v1.6.23
func NormalizeDraftMediaUsages(usages []DraftMediaUsage) ([]DraftMediaUsage, error)
NormalizeDraftMediaUsages validates draft associations and returns a stable copy. A draft can have at most one hero and one social card; media IDs cannot be reused in multiple roles because an exact binding must be unambiguous.
type DraftReviewGrant ¶ added in v1.5.32
type DraftReviewGrant struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
OwnerID string `theorydb:"attr:ownerID"`
DraftID string `theorydb:"attr:draftID"`
Reviewer string `theorydb:"attr:reviewer"`
GrantedAt time.Time `theorydb:"attr:grantedAt"`
// ExpiresAt bounds the grant. Grants are cheap and explicitly re-shared, so
// an unbounded grant would let a stale reviewer assignment authorize reads,
// URL minting, and approval forever. Expired grants fail closed everywhere.
ExpiresAt *time.Time `theorydb:"attr:expiresAt,omitempty"`
RevokedAt *time.Time `theorydb:"attr:revokedAt,omitempty"`
Version int `theorydb:"version,attr:version"`
}
DraftReviewGrant authorizes one local account to review an owner's draft.
func (*DraftReviewGrant) Expired ¶ added in v1.6.23
func (g *DraftReviewGrant) Expired(now time.Time) bool
Expired reports whether a bounded grant has passed its expiry. Revocation is reported separately by the active checks; this predicate only classifies un-revoked grants that can no longer authorize anything.
func (*DraftReviewGrant) IsActive ¶ added in v1.6.23
func (g *DraftReviewGrant) IsActive(now time.Time) bool
IsActive reports whether the grant is currently usable: not revoked and not past its bounded expiry. A grant without an expiry is deliberately treated as expired (fail-closed) so rows created before the M2 expiry surface cannot authorize reads or approval indefinitely; re-sharing refreshes the grant.
func (DraftReviewGrant) TableName ¶ added in v1.5.32
func (DraftReviewGrant) TableName() string
TableName returns the table for a review grant.
func (*DraftReviewGrant) UpdateKeys ¶ added in v1.5.32
func (g *DraftReviewGrant) UpdateKeys() error
UpdateKeys derives grant primary and sparse reviewer-queue keys.
type DraftReviewVerdict ¶ added in v1.5.32
type DraftReviewVerdict struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
OwnerID string `theorydb:"attr:ownerID"`
DraftID string `theorydb:"attr:draftID"`
Reviewer string `theorydb:"attr:reviewer"`
Verdict string `theorydb:"attr:verdict"`
Notes string `theorydb:"attr:notes,omitempty"`
ContentHash string `theorydb:"attr:contentHash,omitempty" json:"content_hash,omitempty"`
RecordedAt time.Time `theorydb:"attr:recordedAt"`
Version int `theorydb:"version,attr:version"`
}
DraftReviewVerdict is an immutable review decision audit record.
func (DraftReviewVerdict) TableName ¶ added in v1.5.32
func (DraftReviewVerdict) TableName() string
TableName returns the table for a review verdict.
func (*DraftReviewVerdict) UpdateKeys ¶ added in v1.5.32
func (v *DraftReviewVerdict) UpdateKeys() error
UpdateKeys derives verdict primary keys.
type Driver ¶
type Driver struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // COST#DRIVER
SK string `theorydb:"sk,attr:SK" json:"-"` // {category}#{resource}
// Attributes from interface
Type string `theorydb:"attr:type" json:"type"`
Domain string `theorydb:"attr:domain" json:"domain,omitempty"`
Cost float64 `theorydb:"attr:cost" json:"cost"`
PercentOfTotal float64 `theorydb:"attr:percentOfTotal" json:"percent_of_total"`
Trend string `theorydb:"attr:trend" json:"trend"` // increasing/stable/decreasing
// Additional attributes
Category string `theorydb:"attr:category" json:"category"` // storage/compute/network/api
Resource string `theorydb:"attr:resource" json:"resource"` // specific resource identifier
Period string `theorydb:"attr:period" json:"period"` // daily/weekly/monthly
MeasuredAt time.Time `theorydb:"attr:measuredAt" json:"measured_at"`
PreviousCost float64 `theorydb:"attr:previousCost" json:"previous_cost"` // For trend calculation
VolumeMetrics map[string]int64 `theorydb:"attr:volumeMetrics" json:"volume_metrics,omitempty"` // requests, bytes, etc
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 90 days retention
// contains filtered or unexported fields
}
Driver represents a major cost contributor
func (*Driver) CalculateTrend ¶
func (c *Driver) CalculateTrend()
CalculateTrend determines the trend based on previous cost
func (*Driver) DetermineCostType ¶
func (c *Driver) DetermineCostType()
DetermineCostType sets the Type field based on category and resource
func (*Driver) FormatCostSummary ¶
FormatCostSummary returns a human-readable cost summary
func (*Driver) GetCostPerUnit ¶
GetCostPerUnit calculates cost per unit for a given metric
func (*Driver) IsSignificant ¶
IsSignificant checks if this driver is a significant cost contributor
func (*Driver) SetVolumeMetric ¶
SetVolumeMetric sets a volume metric value
func (*Driver) UpdateKeys ¶
func (c *Driver) UpdateKeys()
UpdateKeys updates the partition and sort keys
type DynamoDBCostAggregation ¶
type DynamoDBCostAggregation struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "cost_agg#{period}#{operation_type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "window#{windowStart}"
// Aggregation details
Period string `theorydb:"attr:period" json:"period"` // minute, hour, day, week, month
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // Same as CostTracking.OperationType
Table string `theorydb:"attr:tableName" json:"table_name"` // Specific table or "all" for all tables
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"` // Start of aggregation window
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"` // End of aggregation window
// Aggregated capacity units
TotalReadCapacityUnits float64 `theorydb:"attr:totalReadCapacityUnits" json:"total_read_capacity_units"`
TotalWriteCapacityUnits float64 `theorydb:"attr:totalWriteCapacityUnits" json:"total_write_capacity_units"`
// Aggregated costs
TotalReadCostMicroCents int64 `theorydb:"attr:totalReadCostMicroCents" json:"total_read_cost_micro_cents"`
TotalWriteCostMicroCents int64 `theorydb:"attr:totalWriteCostMicroCents" json:"total_write_cost_micro_cents"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
// Operation statistics
TotalOperations int64 `theorydb:"attr:totalOperations" json:"total_operations"`
TotalItemCount int64 `theorydb:"attr:totalItemCount" json:"total_item_count"`
AverageCostPerOperation float64 `theorydb:"attr:averageCostPerOperation" json:"average_cost_per_operation"`
AverageDuration float64 `theorydb:"attr:averageDuration" json:"average_duration"` // milliseconds
// Cost breakdown by table
TableBreakdown map[string]*DynamoDBTableCostStats `theorydb:"attr:tableBreakdown" json:"table_breakdown,omitempty"`
// Cost breakdown by service
ServiceBreakdown map[string]*DynamoDBServiceCostStats `theorydb:"attr:serviceBreakdown" json:"service_breakdown,omitempty"`
// Percentiles for cost distribution
CostPercentiles map[string]float64 `theorydb:"attr:costPercentiles" json:"cost_percentiles,omitempty"` // p50, p90, p95, p99
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL (longer for aggregated data)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"`
// contains filtered or unexported fields
}
DynamoDBCostAggregation represents pre-computed cost aggregations
func (*DynamoDBCostAggregation) BeforeCreate ¶
func (act *DynamoDBCostAggregation) BeforeCreate() error
BeforeCreate for DynamoDBCostAggregation
func (*DynamoDBCostAggregation) BeforeUpdate ¶
func (act *DynamoDBCostAggregation) BeforeUpdate() error
BeforeUpdate for DynamoDBCostAggregation
func (*DynamoDBCostAggregation) GetPK ¶
func (act *DynamoDBCostAggregation) GetPK() string
GetPK returns the partition key
func (*DynamoDBCostAggregation) GetSK ¶
func (act *DynamoDBCostAggregation) GetSK() string
GetSK returns the sort key
func (DynamoDBCostAggregation) TableName ¶
func (DynamoDBCostAggregation) TableName() string
TableName returns the DynamoDB table backing DynamoDBCostAggregation.
func (*DynamoDBCostAggregation) UpdateKeys ¶
func (act *DynamoDBCostAggregation) UpdateKeys() error
UpdateKeys sets up all the keys for the aggregation record
func (*DynamoDBCostAggregation) Validate ¶
func (act *DynamoDBCostAggregation) Validate() error
Validate for DynamoDBCostAggregation
type DynamoDBCostRecord ¶
type DynamoDBCostRecord struct {
// Primary key - using operation type as partition key with timestamp sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "cost#{operation_type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "ts#{timestamp}#{id}"
// GSI1 - Table queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "COST_TABLE#{table_name}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{operation_type}#{id}"
// GSI2 - Aggregation queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "COST_AGG#{period}#{operation_type}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{id}"
// Core cost tracking data
ID string `theorydb:"attr:id" json:"id"`
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // GetItem, PutItem, Query, Scan, BatchWrite, etc.
Table string `theorydb:"attr:tableName" json:"table_name"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Period string `theorydb:"attr:period" json:"period"` // minute, hour, day
// Capacity units consumed
ReadCapacityUnits float64 `theorydb:"attr:readCapacityUnits" json:"read_capacity_units"`
WriteCapacityUnits float64 `theorydb:"attr:writeCapacityUnits" json:"write_capacity_units"`
// Cost calculations (in microcents for precision)
ReadCostMicroCents int64 `theorydb:"attr:readCostMicroCents" json:"read_cost_micro_cents"`
WriteCostMicroCents int64 `theorydb:"attr:writeCostMicroCents" json:"write_cost_micro_cents"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
// Estimated cost in dollars for easy display
EstimatedCostDollars float64 `theorydb:"attr:estimatedCostDollars" json:"estimated_cost_dollars"`
// Operation details
ItemCount int `theorydb:"attr:itemCount" json:"item_count"` // Number of items in operation
RequestDuration int64 `theorydb:"attr:requestDuration" json:"request_duration"` // Duration in milliseconds
IndexName string `theorydb:"attr:indexName" json:"index_name,omitempty"` // GSI name if used
ConsistentRead bool `theorydb:"attr:consistentRead" json:"consistent_read"`
// Service and function information
ServiceName string `theorydb:"attr:serviceName" json:"service_name"` // Lambda function or service
RequestID string `theorydb:"attr:requestID" json:"request_id"` // AWS Request ID
FunctionName string `theorydb:"attr:functionName" json:"function_name"` // Lambda function name
FunctionVersion string `theorydb:"attr:functionVersion" json:"function_version"` // Lambda function version
// Additional metadata
Tags map[string]string `theorydb:"attr:tags" json:"tags,omitempty"`
Properties map[string]interface{} `theorydb:"attr:properties" json:"properties,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (30 days for raw, 90 days for aggregated)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
DynamoDBCostRecord represents detailed cost tracking data from DynamoDB operations
func (*DynamoDBCostRecord) AddTag ¶
func (ct *DynamoDBCostRecord) AddTag(key, value string)
AddTag adds a tag to the cost tracking
func (*DynamoDBCostRecord) BeforeCreate ¶
func (ct *DynamoDBCostRecord) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*DynamoDBCostRecord) BeforeUpdate ¶
func (ct *DynamoDBCostRecord) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*DynamoDBCostRecord) GetPK ¶
func (ct *DynamoDBCostRecord) GetPK() string
GetPK returns the partition key
func (*DynamoDBCostRecord) GetProperty ¶
func (ct *DynamoDBCostRecord) GetProperty(key string) (interface{}, bool)
GetProperty gets a custom property
func (*DynamoDBCostRecord) GetSK ¶
func (ct *DynamoDBCostRecord) GetSK() string
GetSK returns the sort key
func (*DynamoDBCostRecord) SetProperty ¶
func (ct *DynamoDBCostRecord) SetProperty(key string, value interface{})
SetProperty sets a custom property
func (DynamoDBCostRecord) TableName ¶
func (DynamoDBCostRecord) TableName() string
TableName returns the DynamoDB table backing DynamoDBCostRecord.
func (*DynamoDBCostRecord) UpdateKeys ¶
func (ct *DynamoDBCostRecord) UpdateKeys() error
UpdateKeys sets up all the keys for the record
func (*DynamoDBCostRecord) Validate ¶
func (ct *DynamoDBCostRecord) Validate() error
Validate performs validation on the DynamoDBCostRecord
type DynamoDBCostRecordBuilder ¶
type DynamoDBCostRecordBuilder struct {
// contains filtered or unexported fields
}
DynamoDBCostRecordBuilder helps create cost tracking records
func NewDynamoDBCostRecordBuilder ¶
func NewDynamoDBCostRecordBuilder() *DynamoDBCostRecordBuilder
NewDynamoDBCostRecordBuilder creates a new cost tracking builder
func (*DynamoDBCostRecordBuilder) Build ¶
func (ctb *DynamoDBCostRecordBuilder) Build() *DynamoDBCostRecord
Build creates the cost tracking record
func (*DynamoDBCostRecordBuilder) ForOperation ¶
func (ctb *DynamoDBCostRecordBuilder) ForOperation(operationType string) *DynamoDBCostRecordBuilder
ForOperation sets the operation type
func (*DynamoDBCostRecordBuilder) OnTable ¶
func (ctb *DynamoDBCostRecordBuilder) OnTable(tableName string) *DynamoDBCostRecordBuilder
OnTable sets the table name
func (DynamoDBCostRecordBuilder) TableName ¶
func (DynamoDBCostRecordBuilder) TableName() string
TableName returns the DynamoDB table backing DynamoDBCostRecordBuilder.
func (*DynamoDBCostRecordBuilder) WithCapacityUnits ¶
func (ctb *DynamoDBCostRecordBuilder) WithCapacityUnits(readUnits, writeUnits float64) *DynamoDBCostRecordBuilder
WithCapacityUnits sets the consumed capacity units
func (*DynamoDBCostRecordBuilder) WithConsistentRead ¶
func (ctb *DynamoDBCostRecordBuilder) WithConsistentRead(consistent bool) *DynamoDBCostRecordBuilder
WithConsistentRead sets whether consistent read was used
func (*DynamoDBCostRecordBuilder) WithCostMicroCents ¶
func (ctb *DynamoDBCostRecordBuilder) WithCostMicroCents(readCost, writeCost int64) *DynamoDBCostRecordBuilder
WithCostMicroCents sets the cost in microcents
func (*DynamoDBCostRecordBuilder) WithDuration ¶
func (ctb *DynamoDBCostRecordBuilder) WithDuration(durationMs int64) *DynamoDBCostRecordBuilder
WithDuration sets the request duration in milliseconds
func (*DynamoDBCostRecordBuilder) WithIndex ¶
func (ctb *DynamoDBCostRecordBuilder) WithIndex(indexName string) *DynamoDBCostRecordBuilder
WithIndex sets the index name if a GSI was used
func (*DynamoDBCostRecordBuilder) WithItemCount ¶
func (ctb *DynamoDBCostRecordBuilder) WithItemCount(count int) *DynamoDBCostRecordBuilder
WithItemCount sets the item count
func (*DynamoDBCostRecordBuilder) WithPeriod ¶
func (ctb *DynamoDBCostRecordBuilder) WithPeriod(period string) *DynamoDBCostRecordBuilder
WithPeriod sets the period
func (*DynamoDBCostRecordBuilder) WithRequestID ¶
func (ctb *DynamoDBCostRecordBuilder) WithRequestID(requestID string) *DynamoDBCostRecordBuilder
WithRequestID sets the request ID
func (*DynamoDBCostRecordBuilder) WithService ¶
func (ctb *DynamoDBCostRecordBuilder) WithService(serviceName, functionName string) *DynamoDBCostRecordBuilder
WithService sets the service information
func (*DynamoDBCostRecordBuilder) WithTag ¶
func (ctb *DynamoDBCostRecordBuilder) WithTag(key, value string) *DynamoDBCostRecordBuilder
WithTag adds a tag
type DynamoDBServiceCostStats ¶
type DynamoDBServiceCostStats struct {
ServiceName string `theorydb:"attr:serviceName" json:"service_name"`
OperationCount int64 `theorydb:"attr:operationCount" json:"operation_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerOp float64 `theorydb:"attr:averageCostPerOp" json:"average_cost_per_op"`
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Data transfer for this service
}
DynamoDBServiceCostStats represents cost statistics for a specific service
func (DynamoDBServiceCostStats) TableName ¶
func (DynamoDBServiceCostStats) TableName() string
TableName returns the DynamoDB table backing DynamoDBServiceCostStats.
type DynamoDBTableCostStats ¶
type DynamoDBTableCostStats struct {
Table string `theorydb:"attr:tableName" json:"table_name"`
OperationCount int64 `theorydb:"attr:operationCount" json:"operation_count"`
ReadCapacityUnits float64 `theorydb:"attr:readCapacityUnits" json:"read_capacity_units"`
WriteCapacityUnits float64 `theorydb:"attr:writeCapacityUnits" json:"write_capacity_units"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users"` // Number of unique users for this table
}
DynamoDBTableCostStats represents cost statistics for a specific table
func (DynamoDBTableCostStats) TableName ¶
func (DynamoDBTableCostStats) TableName() string
TableName returns the DynamoDB table backing DynamoDBTableCostStats.
type EditorialLifecycle ¶ added in v1.6.23
type EditorialLifecycle string
EditorialLifecycle is the editorial lifecycle of an internal asset, distinct from the processing-pipeline Status enum ("pending/processing/ready/failed"). The lifecycle is an inspectable editorial decision surface: withdrawal, supersession, and service unavailability are explicit states that block publication until the draft is re-reviewed against the surviving asset.
const ( // EditorialLifecycleAvailable is the default servable editorial state. EditorialLifecycleAvailable EditorialLifecycle = "available" // EditorialLifecycleWithdrawn removes an asset from editorial circulation. EditorialLifecycleWithdrawn EditorialLifecycle = "withdrawn" // EditorialLifecycleSuperseded marks an asset replaced by a named successor. EditorialLifecycleSuperseded EditorialLifecycle = "superseded" EditorialLifecycleUnavailable EditorialLifecycle = "unavailable" )
type EditorialMediaOrigin ¶ added in v1.6.23
type EditorialMediaOrigin string
EditorialMediaOrigin records the editorial origin of an asset.
const ( // EditorialMediaOriginAIGenerated identifies wholly generated media. EditorialMediaOriginAIGenerated EditorialMediaOrigin = "ai_generated" // EditorialMediaOriginAIEdited identifies AI-modified source media. EditorialMediaOriginAIEdited EditorialMediaOrigin = "ai_edited" // EditorialMediaOriginPhotographed identifies photographic media. EditorialMediaOriginPhotographed EditorialMediaOrigin = "photographed" // EditorialMediaOriginIllustrated identifies illustrated media. EditorialMediaOriginIllustrated EditorialMediaOrigin = "illustrated" // EditorialMediaOriginSupplied identifies externally supplied media. EditorialMediaOriginSupplied EditorialMediaOrigin = "supplied" )
type EditorialMediaRole ¶ added in v1.6.23
type EditorialMediaRole string
EditorialMediaRole describes how one media asset is used by an article draft.
const ( // EditorialMediaRoleHero is the draft-side source for Article.featuredImage. EditorialMediaRoleHero EditorialMediaRole = "hero" // EditorialMediaRoleInline places an asset at a modeled position in article content. EditorialMediaRoleInline EditorialMediaRole = "inline" // EditorialMediaRoleSocialCard is the promotional/social-card presentation. EditorialMediaRoleSocialCard EditorialMediaRole = "social_card" )
type EffectiveAIInstanceConfig ¶ added in v0.1.36
type EffectiveAIInstanceConfig struct {
AIEnabled bool
ModerationEnabled bool
NSFWDetectionEnabled bool
SpamDetectionEnabled bool
PIIDetectionEnabled bool
AIContentDetection bool
}
EffectiveAIInstanceConfig contains resolved AI configuration values after applying managed defaults and overrides.
type EffectiveTipsConfig ¶ added in v0.1.36
EffectiveTipsConfig contains resolved tips configuration values after applying managed defaults and overrides.
type EffectiveTrustConfig ¶ added in v0.1.36
type EffectiveTrustConfig struct {
TrustBaseURL string
AttestationsBaseURL string
InstanceKeySecretARN string
// TrustProxyEnabled indicates whether instance-authenticated trust proxy calls should work.
TrustProxyEnabled bool
// PublicAttestationsEnabled indicates whether public JWKS/attestation proxy calls should work.
PublicAttestationsEnabled bool
}
EffectiveTrustConfig contains resolved trust configuration values after applying managed defaults and overrides.
type EmailDomainBlock ¶
type EmailDomainBlock struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ID string `theorydb:"attr:id" json:"ID"`
Domain string `theorydb:"attr:domain" json:"Domain"`
CreatedBy string `theorydb:"attr:createdBy" json:"CreatedBy"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
// contains filtered or unexported fields
}
EmailDomainBlock represents an email domain block
func (*EmailDomainBlock) GetDomain ¶
func (d *EmailDomainBlock) GetDomain() string
GetDomain returns the domain of the email domain block
func (*EmailDomainBlock) GetID ¶
func (d *EmailDomainBlock) GetID() string
GetID returns the ID of the email domain block
func (*EmailDomainBlock) GetPK ¶
func (d *EmailDomainBlock) GetPK() string
GetPK returns the primary key of the email domain block
func (*EmailDomainBlock) GetSK ¶
func (d *EmailDomainBlock) GetSK() string
GetSK returns the sort key of the email domain block
func (EmailDomainBlock) TableName ¶
func (EmailDomainBlock) TableName() string
TableName returns the DynamoDB table backing EmailDomainBlock.
func (*EmailDomainBlock) UpdateKeys ¶
func (d *EmailDomainBlock) UpdateKeys() error
UpdateKeys updates the keys for the email domain block
type EmojiModel ¶
type EmojiModel struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // EMOJI#shortcode
SK string `theorydb:"sk,attr:SK" json:"-"` // EMOJI
// GSI keys - for querying all emojis
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // ALL_EMOJIS
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // EMOJI#shortcode
// GSI keys - for querying by category
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // CATEGORY#category
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // EMOJI#shortcode
// GSI keys - for search and domain queries
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // SEARCH#prefix or DOMAIN#domain
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // EMOJI#shortcode
// GSI keys - for usage statistics and popularity
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"-"` // USAGE#domain
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"-"` // SCORE#usage_count#shortcode
// Business fields
Shortcode string `theorydb:"attr:shortcode" json:"shortcode"`
URL string `theorydb:"attr:url" json:"url"`
StaticURL string `theorydb:"attr:staticURL" json:"static_url"`
VisibleInPicker bool `theorydb:"attr:visibleInPicker" json:"visible_in_picker"`
Category string `theorydb:"attr:category" json:"category,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Disabled bool `theorydb:"attr:disabled" json:"disabled"`
Domain string `theorydb:"attr:domain" json:"domain,omitempty"` // Empty for local emojis
ImageRemoteURL string `theorydb:"attr:imageRemoteURL" json:"image_remote_url,omitempty"`
ImageStorageVersion int `theorydb:"attr:imageStorageVersion" json:"image_storage_version"`
ImageFileSize int64 `theorydb:"attr:imageFileSize" json:"image_file_size"`
ImageContentType string `theorydb:"attr:imageContentType" json:"image_content_type"`
ImageWidth int `theorydb:"attr:imageWidth" json:"image_width"`
ImageHeight int `theorydb:"attr:imageHeight" json:"image_height"`
ImageUpdatedAt time.Time `theorydb:"attr:imageUpdatedAt" json:"image_updated_at"`
// Enhanced fields for sophisticated queries
UsageCount int64 `theorydb:"attr:usageCount" json:"usage_count"` // How many times this emoji has been used
LastUsedAt time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at"` // When this emoji was last used
PopularityScore float64 `theorydb:"attr:popularityScore" json:"popularity_score"` // Calculated popularity score
SearchKeywords []string `theorydb:"attr:searchKeywords" json:"search_keywords"` // Additional search terms
AltText string `theorydb:"attr:altText" json:"alt_text,omitempty"` // Alternative text for accessibility
// contains filtered or unexported fields
}
EmojiModel represents a custom emoji with DynamORM tags
func (*EmojiModel) IncrementUsage ¶
func (e *EmojiModel) IncrementUsage()
IncrementUsage increments the usage count and updates last used time
func (EmojiModel) TableName ¶
func (EmojiModel) TableName() string
TableName returns the DynamoDB table backing EmojiModel.
func (*EmojiModel) UpdateKeys ¶
func (e *EmojiModel) UpdateKeys() error
UpdateKeys updates the composite keys based on the business fields
type EngagementMetrics ¶
type EngagementMetrics struct {
// Key fields - EXACT pattern from legacy: PK=`METRICS#type#date`, SK=`target#targetID`
PK string `theorydb:"pk,attr:PK"` // METRICS#type#date or STATUS#statusID or ENGAGEMENT#bucket
SK string `theorydb:"sk,attr:SK"` // target#targetID or ENGAGEMENT#METRICS or STATUS#timestamp#statusID
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"` // For date range queries
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"` // For date range queries
// Business fields from legacy
MetricType string `theorydb:"attr:metricType" json:"metric_type,omitempty"`
TargetID string `theorydb:"attr:targetID" json:"target_id,omitempty"` // user/post/hashtag ID
Date string `theorydb:"attr:date" json:"date,omitempty"` // YYYY-MM-DD format
Views int64 `theorydb:"attr:views" json:"views,omitempty"`
Likes int64 `theorydb:"attr:likes" json:"likes,omitempty"`
Replies int64 `theorydb:"attr:replies" json:"replies,omitempty"`
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at,omitempty"`
// Additional fields for status metrics
StatusID string `theorydb:"attr:statusID" json:"status_id,omitempty"`
LikeCount int64 `theorydb:"attr:likeCount" json:"like_count,omitempty"`
BoostCount int64 `theorydb:"attr:boostCount" json:"boost_count,omitempty"`
ReplyCount int64 `theorydb:"attr:replyCount" json:"reply_count,omitempty"`
Score float64 `theorydb:"attr:score" json:"score,omitempty"`
EngagementBucket string `theorydb:"attr:engagementBucket" json:"engagement_bucket,omitempty"`
// TTL field
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
EngagementMetrics tracks engagement metrics for platform usage analysis
func (*EngagementMetrics) GetPK ¶
func (e *EngagementMetrics) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*EngagementMetrics) GetSK ¶
func (e *EngagementMetrics) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*EngagementMetrics) TableName ¶
func (e *EngagementMetrics) TableName() string
TableName returns the DynamoDB table backing EngagementMetrics.
func (*EngagementMetrics) UpdateKeys ¶
func (e *EngagementMetrics) UpdateKeys() error
UpdateKeys updates GSI keys for EngagementMetrics
type EnhancedModerationPattern ¶
type EnhancedModerationPattern struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "ENHANCED_PATTERN#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // "METADATA"
// GSI1 - Active pattern queries with priority
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "ENHANCED_PATTERNS#ACTIVE" (when active)
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // "{priority}#{type}#{severity}#{pattern_id}"
// GSI2 - Type-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // "ENHANCED_PATTERNS#{type}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // "{effectiveness}#{updated_at}#{pattern_id}"
// GSI3 - Performance metric queries
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk,omitempty"` // "PATTERN_METRICS#{category}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk,omitempty"` // "{effectiveness}#{match_count}#{pattern_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ENHANCED_PATTERN"
// Pattern identification
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
Name string `theorydb:"attr:name" json:"name"`
Description string `theorydb:"attr:description" json:"description"`
Version int `theorydb:"attr:version" json:"version"`
// Pattern configuration
PatternType string `theorydb:"attr:patternType" json:"pattern_type"` // "url_exact", ...
PatternContent string `theorydb:"attr:patternContent" json:"pattern_content"` // The actual pattern string
Category string `theorydb:"attr:category" json:"category"` // "spam", ...
Severity string `theorydb:"attr:severity" json:"severity"` // "low", "medium", etc.
Priority int `theorydb:"attr:priority" json:"priority"` // 1-10, higher is more important
Active bool `theorydb:"attr:active" json:"active"`
Compiled bool `theorydb:"attr:compiled" json:"compiled"` // Whether pattern has been compiled successfully
CompilationHash string `theorydb:"attr:compilationHash" json:"compilation_hash"` // Hash of compiled pattern for cache invalidation
// Pattern behavior
Action string `theorydb:"attr:action" json:"action"` // "flag", etc.
BlockDuration int64 `theorydb:"attr:blockDuration" json:"block_duration"` // Duration in seconds, 0 for permanent
EscalationThreshold int `theorydb:"attr:escalationThreshold" json:"escalation_threshold"` // Number of matches before escalation
WhitelistOverride bool `theorydb:"attr:whitelistOverride" json:"whitelist_override"` // Whether this pattern can be overridden by whitelist
Tags []string `theorydb:"attr:tags" json:"tags,omitempty"` // Additional categorization tags
// Performance metrics
MatchCount int64 `theorydb:"attr:matchCount" json:"match_count"`
FalsePositiveCount int64 `theorydb:"attr:falsePositiveCount" json:"false_positive_count"`
TruePositiveCount int64 `theorydb:"attr:truePositiveCount" json:"true_positive_count"`
Effectiveness float64 `theorydb:"attr:effectiveness" json:"effectiveness"` // Calculated effectiveness score 0.0-1.0
ConfidenceScore float64 `theorydb:"attr:confidenceScore" json:"confidence_score"`
LastMatch time.Time `theorydb:"attr:lastMatch" json:"last_match,omitempty"`
AverageMatchTime float64 `theorydb:"attr:averageMatchTime" json:"average_match_time"` // Average time to match in milliseconds
// Pattern validation metrics
TestResults map[string]interface{} `theorydb:"attr:testResults" json:"test_results,omitempty"` // Results from pattern testing
ValidationScore float64 `theorydb:"attr:validationScore" json:"validation_score"` // 0.0-1.0 based on test results
LastValidated time.Time `theorydb:"attr:lastValidated" json:"last_validated,omitempty"`
// Metadata
CreatedBy string `theorydb:"attr:createdBy" json:"created_by"`
UpdatedBy string `theorydb:"attr:updatedBy" json:"updated_by,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used,omitempty"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at,omitempty"`
// DynamoDB TTL (90 days default)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
EnhancedModerationPattern represents an enhanced moderation pattern with advanced matching capabilities
func (*EnhancedModerationPattern) CalculateEffectiveness ¶
func (p *EnhancedModerationPattern) CalculateEffectiveness()
CalculateEffectiveness calculates the pattern effectiveness score
func (*EnhancedModerationPattern) GetPK ¶
func (p *EnhancedModerationPattern) GetPK() string
GetPK returns the partition key
func (*EnhancedModerationPattern) GetSK ¶
func (p *EnhancedModerationPattern) GetSK() string
GetSK returns the sort key
func (*EnhancedModerationPattern) IsExpired ¶
func (p *EnhancedModerationPattern) IsExpired() bool
IsExpired checks if the pattern has expired
func (*EnhancedModerationPattern) ShouldEscalate ¶
func (p *EnhancedModerationPattern) ShouldEscalate() bool
ShouldEscalate checks if pattern matches have reached escalation threshold
func (EnhancedModerationPattern) TableName ¶
func (EnhancedModerationPattern) TableName() string
TableName returns the DynamoDB table name
func (*EnhancedModerationPattern) UpdateKeys ¶
func (p *EnhancedModerationPattern) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ErrorFrequency ¶
type ErrorFrequency struct {
ErrorCode string `json:"error_code"`
Count int64 `json:"count"`
Percentage float64 `json:"percentage"`
}
ErrorFrequency represents error frequency data
func (ErrorFrequency) TableName ¶
func (ErrorFrequency) TableName() string
TableName returns the DynamoDB table backing ErrorFrequency.
type Export ¶
type Export struct {
// Primary keys - export records use EXPORT#{export_id} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for user queries - USER#{username}, CREATED#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// Export metadata
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
Type string `theorydb:"attr:type" json:"type"` // archive, followers, following, etc.
Format string `theorydb:"attr:format" json:"format"` // activitypub, mastodon, csv
Status string `theorydb:"attr:status" json:"status"` // pending, processing, completed, failed
Options map[string]any `theorydb:"attr:options" json:"options"`
IncludeMedia bool `theorydb:"attr:includeMedia" json:"include_media"`
DateRange *ExportDateRange `theorydb:"attr:dateRange" json:"date_range"`
// Status tracking
DownloadURL string `theorydb:"attr:downloadURL" json:"download_url,omitempty"`
ExpiresAt *time.Time `theorydb:"attr:expiresAt" json:"expires_at,omitempty"`
FileSize int64 `theorydb:"attr:fileSize" json:"file_size,omitempty"`
RecordCount int64 `theorydb:"attr:recordCount" json:"record_count,omitempty"`
S3Key string `theorydb:"attr:s3Key" json:"s3_key,omitempty"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
// contains filtered or unexported fields
}
Export represents a data export request
func (*Export) GetCreatedAt ¶
GetCreatedAt returns the creation timestamp of the export
func (*Export) UpdateKeys ¶
func (e *Export) UpdateKeys()
UpdateKeys sets the primary keys for the Export model
type ExportCostSummary ¶
type ExportCostSummary struct {
Username string `theorydb:"attr:username" json:"username"`
Period string `theorydb:"attr:period" json:"period"` // daily, weekly, monthly
StartDate time.Time `theorydb:"attr:startDate" json:"start_date"`
EndDate time.Time `theorydb:"attr:endDate" json:"end_date"`
TotalExports int64 `theorydb:"attr:totalExports" json:"total_exports"`
CompletedExports int64 `theorydb:"attr:completedExports" json:"completed_exports"`
FailedExports int64 `theorydb:"attr:failedExports" json:"failed_exports"`
TotalLambdaCost int64 `theorydb:"attr:totalLambdaCost" json:"total_lambda_cost"`
TotalS3Cost int64 `theorydb:"attr:totalS3Cost" json:"total_s3_cost"`
TotalDynamoDBCost int64 `theorydb:"attr:totalDynamoDBCost" json:"total_dynamodb_cost"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalFileSize int64 `theorydb:"attr:totalFileSize" json:"total_file_size"`
TotalRecordCount int64 `theorydb:"attr:totalRecordCount" json:"total_record_count"`
TotalMediaFiles int64 `theorydb:"attr:totalMediaFiles" json:"total_media_files"`
AverageCostPerExport float64 `theorydb:"attr:averageCostPerExport" json:"average_cost_per_export"`
AverageExportSize int64 `theorydb:"attr:averageExportSize" json:"average_export_size"`
TypeBreakdown map[string]*ExportTypeCostStats `theorydb:"attr:typeBreakdown" json:"type_breakdown"`
}
ExportCostSummary represents aggregated export costs
func (ExportCostSummary) TableName ¶
func (ExportCostSummary) TableName() string
TableName returns the DynamoDB table backing ExportCostSummary.
type ExportCostTracking ¶
type ExportCostTracking struct {
// Primary keys - export cost tracking uses EXPORT_COST#{export_id}#{timestamp} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for user queries - USER#{username}, COST#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for date range queries - EXPORT_COSTS#{date}, TS#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Export metadata
ExportID string `theorydb:"attr:exportID" json:"export_id"`
Username string `theorydb:"attr:username" json:"username"`
Type string `theorydb:"attr:type" json:"type"` // archive, followers, following, etc.
Format string `theorydb:"attr:format" json:"format"` // activitypub, mastodon, csv
IncludeMedia bool `theorydb:"attr:includeMedia" json:"include_media"`
// Cost breakdown (all in microcents)
LambdaExecutionCost int64 `theorydb:"attr:lambdaExecutionCost" json:"lambda_execution_cost"` // Lambda compute cost
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Lambda execution time
S3StorageCost int64 `theorydb:"attr:s3StorageCost" json:"s3_storage_cost"` // S3 storage for export file
S3PutRequestCost int64 `theorydb:"attr:s3PutRequestCost" json:"s3_put_request_cost"` // S3 PUT operations
S3GetRequestCost int64 `theorydb:"attr:s3GetRequestCost" json:"s3_get_request_cost"` // S3 GET operations for media
S3DataTransferCost int64 `theorydb:"attr:s3DataTransferCost" json:"s3_data_transfer_cost"` // Data transfer costs
DynamoDBReadCost int64 `theorydb:"attr:dynamoDBReadCost" json:"dynamodb_read_cost"` // DynamoDB read operations
DynamoDBReadUnits float64 `theorydb:"attr:dynamoDBReadUnits" json:"dynamodb_read_units"` // Read capacity consumed
DynamoDBOperations int64 `theorydb:"attr:dynamoDBOperations" json:"dynamodb_operations"` // Number of DB operations
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost in microcents
// Operation metrics
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // Size of exported file in bytes
RecordCount int64 `theorydb:"attr:recordCount" json:"record_count"` // Number of records exported
MediaFilesIncluded int64 `theorydb:"attr:mediaFilesIncluded" json:"media_files_included"` // Number of media files included
MediaSizeBytes int64 `theorydb:"attr:mediaSizeBytes" json:"media_size_bytes"` // Total size of media files
S3PutRequests int64 `theorydb:"attr:s3PutRequests" json:"s3_put_requests"` // Number of S3 PUT requests
S3GetRequests int64 `theorydb:"attr:s3GetRequests" json:"s3_get_requests"` // Number of S3 GET requests
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Bytes transferred
// Status tracking
Status string `theorydb:"attr:status" json:"status"` // pending, processing, completed, failed
StartedAt time.Time `theorydb:"attr:startedAt" json:"started_at"` // When export processing started
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"` // When export completed
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ExportCostTracking represents cost tracking for export operations
func (*ExportCostTracking) BeforeCreate ¶
func (e *ExportCostTracking) BeforeCreate() error
BeforeCreate is called before creating the record
func (*ExportCostTracking) BeforeUpdate ¶
func (e *ExportCostTracking) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*ExportCostTracking) CalculateTotalCost ¶
func (e *ExportCostTracking) CalculateTotalCost()
CalculateTotalCost calculates the total cost from all components
func (*ExportCostTracking) GetTimestamp ¶
func (e *ExportCostTracking) GetTimestamp() time.Time
GetTimestamp returns the timestamp for cost tracking
func (*ExportCostTracking) GetTotalCostDollars ¶
func (e *ExportCostTracking) GetTotalCostDollars() float64
GetTotalCostDollars returns the total cost in dollars
func (*ExportCostTracking) GetTotalCostMicroCents ¶
func (e *ExportCostTracking) GetTotalCostMicroCents() int64
GetTotalCostMicroCents returns the total cost in microcents
func (*ExportCostTracking) TableName ¶
func (e *ExportCostTracking) TableName() string
TableName returns the DynamoDB table backing ExportCostTracking.
func (*ExportCostTracking) UpdateKeys ¶
func (e *ExportCostTracking) UpdateKeys()
UpdateKeys sets the primary keys for the ExportCostTracking model
type ExportDateRange ¶
ExportDateRange for filtering exports
func NewExportDateRangeFromStrings ¶
func NewExportDateRangeFromStrings(start, end string) (*ExportDateRange, error)
NewExportDateRangeFromStrings creates a date range from ISO date strings
func (ExportDateRange) TableName ¶
func (ExportDateRange) TableName() string
TableName returns the DynamoDB table backing ExportDateRange.
type ExportTypeCostStats ¶
type ExportTypeCostStats struct {
Type string `theorydb:"attr:type" json:"type"`
Count int64 `theorydb:"attr:count" json:"count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostMicroCents int64 `theorydb:"attr:averageCostMicroCents" json:"average_cost_micro_cents"`
AverageFileSize int64 `theorydb:"attr:averageFileSize" json:"average_file_size"`
AverageRecordCount int64 `theorydb:"attr:averageRecordCount" json:"average_record_count"`
}
ExportTypeCostStats represents cost statistics for a specific export type
func (ExportTypeCostStats) TableName ¶
func (ExportTypeCostStats) TableName() string
TableName returns the DynamoDB table backing ExportTypeCostStats.
type FeaturedTag ¶
type FeaturedTag struct {
// Primary key: USER#username
PK string `theorydb:"pk,attr:PK"`
// Sort key: FEATURED_TAG#id
SK string `theorydb:"sk,attr:SK"`
// Core fields (must match legacy exactly)
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"` // Who featured the tag
Name string `theorydb:"attr:name" json:"name"` // The tag name (without #)
URL string `theorydb:"attr:url" json:"url"` // URL to the tag
StatusesCount int `theorydb:"attr:statusesCount" json:"statuses_count"` // Number of statuses with this tag
LastStatusAt string `theorydb:"attr:lastStatusAt" json:"last_status_at"` // Last time the user posted with this tag
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
FeaturedTag represents a featured hashtag for a user
func (*FeaturedTag) GetPK ¶
func (f *FeaturedTag) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*FeaturedTag) GetSK ¶
func (f *FeaturedTag) GetSK() string
GetSK returns the sort key for BaseModel interface
func (FeaturedTag) TableName ¶
func (FeaturedTag) TableName() string
TableName returns the DynamoDB table backing FeaturedTag.
func (*FeaturedTag) UpdateKeys ¶
func (f *FeaturedTag) UpdateKeys() error
UpdateKeys sets the PK and SK based on the username and ID
type FederationActivity ¶
type FederationActivity struct {
// Primary key - using domain as partition key with timestamp sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "fed_activity#{domain}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "activity#{timestamp}#{id}"
// GSI1 - Activity type queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "FED_TYPE#{type}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{domain}#{id}"
// GSI2 - Actor queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "FED_ACTOR#{actorID}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{id}"
// Core activity data
ID string `theorydb:"attr:id" json:"id"`
Domain string `theorydb:"attr:domain" json:"domain"` // Remote instance domain
ActivityType string `theorydb:"attr:activityType" json:"activity_type"` // Create, Update, Delete, Follow, etc.
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // Remote actor ID (full URL)
ObjectID string `theorydb:"attr:objectID" json:"object_id"` // Object being acted upon
ObjectType string `theorydb:"attr:objectType" json:"object_type"` // Note, Actor, etc.
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// Instance information
InstanceInfo *InstanceInfo `theorydb:"attr:instanceInfo" json:"instance_info,omitempty"`
// Activity details
Success bool `theorydb:"attr:success" json:"success"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
ResponseTime float64 `theorydb:"attr:responseTime" json:"response_time_ms"` // Response time in milliseconds
// Volume tracking
InboundSize int64 `theorydb:"attr:inboundSize" json:"inbound_size"` // Size of inbound data in bytes
OutboundSize int64 `theorydb:"attr:outboundSize" json:"outbound_size"` // Size of outbound data in bytes
// Additional metadata
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
RemoteIP string `theorydb:"attr:remoteIP" json:"remote_ip,omitempty"`
Headers map[string]string `theorydb:"attr:headers" json:"headers,omitempty"`
Properties map[string]interface{} `theorydb:"attr:properties" json:"properties,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (90 days)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
FederationActivity represents activity from federated instances
func (*FederationActivity) BeforeCreate ¶
func (fa *FederationActivity) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*FederationActivity) BeforeUpdate ¶
func (fa *FederationActivity) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*FederationActivity) GetHeader ¶
func (fa *FederationActivity) GetHeader(key string) (string, bool)
GetHeader gets a header value
func (*FederationActivity) GetPK ¶
func (fa *FederationActivity) GetPK() string
GetPK returns the partition key for BaseRepository compatibility
func (*FederationActivity) GetProperty ¶
func (fa *FederationActivity) GetProperty(key string) (interface{}, bool)
GetProperty gets a custom property
func (*FederationActivity) GetSK ¶
func (fa *FederationActivity) GetSK() string
GetSK returns the sort key for BaseRepository compatibility
func (*FederationActivity) IsRemote ¶
func (fa *FederationActivity) IsRemote(localDomain string) bool
IsRemote checks if the activity is from a remote instance
func (*FederationActivity) MarkFailed ¶
func (fa *FederationActivity) MarkFailed(errorMsg string)
MarkFailed marks the activity as failed
func (*FederationActivity) MarkSuccess ¶
func (fa *FederationActivity) MarkSuccess()
MarkSuccess marks the activity as successful
func (*FederationActivity) SetHeader ¶
func (fa *FederationActivity) SetHeader(key, value string)
SetHeader sets a header value
func (*FederationActivity) SetProperty ¶
func (fa *FederationActivity) SetProperty(key string, value interface{})
SetProperty sets a custom property
func (FederationActivity) TableName ¶
func (FederationActivity) TableName() string
TableName returns the DynamoDB table backing FederationActivity.
func (*FederationActivity) UpdateKeys ¶
func (fa *FederationActivity) UpdateKeys() error
UpdateKeys updates all keys (primary and GSI) for the federation activity
func (*FederationActivity) Validate ¶
func (fa *FederationActivity) Validate() error
Validate performs validation on the FederationActivity
type FederationActivityBuilder ¶
type FederationActivityBuilder struct {
// contains filtered or unexported fields
}
FederationActivityBuilder helps create federation activities
func NewFederationActivityBuilder ¶
func NewFederationActivityBuilder() *FederationActivityBuilder
NewFederationActivityBuilder creates a new builder
func (*FederationActivityBuilder) Build ¶
func (fab *FederationActivityBuilder) Build() *FederationActivity
Build creates the federation activity
func (*FederationActivityBuilder) FromDomain ¶
func (fab *FederationActivityBuilder) FromDomain(domain string) *FederationActivityBuilder
FromDomain sets the source domain
func (FederationActivityBuilder) TableName ¶
func (FederationActivityBuilder) TableName() string
TableName returns the DynamoDB table backing FederationActivityBuilder.
func (*FederationActivityBuilder) WithActor ¶
func (fab *FederationActivityBuilder) WithActor(actorID string) *FederationActivityBuilder
WithActor sets the actor ID
func (*FederationActivityBuilder) WithError ¶
func (fab *FederationActivityBuilder) WithError(err error) *FederationActivityBuilder
WithError marks the activity as failed with an error
func (*FederationActivityBuilder) WithInstanceInfo ¶
func (fab *FederationActivityBuilder) WithInstanceInfo(info *InstanceInfo) *FederationActivityBuilder
WithInstanceInfo sets the instance information
func (*FederationActivityBuilder) WithObject ¶
func (fab *FederationActivityBuilder) WithObject(objectID, objectType string) *FederationActivityBuilder
WithObject sets the object information
func (*FederationActivityBuilder) WithResponseTime ¶
func (fab *FederationActivityBuilder) WithResponseTime(ms float64) *FederationActivityBuilder
WithResponseTime sets the response time
func (*FederationActivityBuilder) WithType ¶
func (fab *FederationActivityBuilder) WithType(activityType string) *FederationActivityBuilder
WithType sets the activity type
func (*FederationActivityBuilder) WithVolume ¶
func (fab *FederationActivityBuilder) WithVolume(inbound, outbound int64) *FederationActivityBuilder
WithVolume sets the data volume
type FederationAlert ¶
type FederationAlert struct {
Domain string `json:"domain"`
Level string `json:"level"` // CRITICAL, WARNING, INFO
Message string `json:"message"`
HealthScore float64 `json:"health_score"`
Timestamp time.Time `json:"timestamp"`
}
FederationAlert represents an alert condition for federation monitoring
func (FederationAlert) TableName ¶
func (FederationAlert) TableName() string
TableName returns the DynamoDB table backing FederationAlert.
type FederationAnalyticsTimeSeries ¶
type FederationAnalyticsTimeSeries struct {
// Primary keys - PK: FEDERATION_TIMESERIES#domain#period, SK: timestamp
PK string `theorydb:"pk,attr:PK" json:"-"` // FEDERATION_TIMESERIES#{domain}#{period}
SK string `theorydb:"sk,attr:SK" json:"-"` // {timestamp}
// GSI1 - Domain-based queries: GSI1PK: DOMAIN#{domain}, GSI1SK: {period}#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 - Period-based queries: GSI2PK: PERIOD#{period}, GSI2SK: {timestamp}#{domain}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Core time series data
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // 5min, hourly, daily, monthly
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // Start time of the time window
// 1. Availability Metrics (40% weight in health scoring)
InstanceReachability float64 `theorydb:"attr:instanceReachability" json:"instance_reachability"` // % instances responding (0-1)
EndpointAvailability float64 `theorydb:"attr:endpointAvailability" json:"endpoint_availability"` // % endpoints up (0-1)
LastSuccessfulContact *time.Time `theorydb:"attr:lastSuccessfulContact" json:"last_successful_contact,omitempty"`
ConsecutiveFailures int64 `theorydb:"attr:consecutiveFailures" json:"consecutive_failures"`
CircuitBreakerActive bool `theorydb:"attr:circuitBreakerActive" json:"circuit_breaker_active"`
// 2. Performance Metrics (30% weight)
InboxDeliveryP50 int64 `theorydb:"attr:inboxDeliveryP50" json:"inbox_delivery_p50_ms"` // ms
InboxDeliveryP95 int64 `theorydb:"attr:inboxDeliveryP95" json:"inbox_delivery_p95_ms"` // ms
InboxDeliveryP99 int64 `theorydb:"attr:inboxDeliveryP99" json:"inbox_delivery_p99_ms"` // ms
OutboxProcessingTime int64 `theorydb:"attr:outboxProcessingTime" json:"outbox_processing_time_ms"` // ms
SignatureVerificationTime int64 `theorydb:"attr:signatureVerificationTime" json:"signature_verification_ms"` // ms
MediaDeliveryTime int64 `theorydb:"attr:mediaDeliveryTime" json:"media_delivery_time_ms"` // ms
// 3. Throughput Metrics (20% weight)
IncomingActivitiesPerSec float64 `theorydb:"attr:incomingActivitiesPerSec" json:"incoming_activities_per_sec"`
OutgoingActivitiesPerSec float64 `theorydb:"attr:outgoingActivitiesPerSec" json:"outgoing_activities_per_sec"`
QueueDepth int64 `theorydb:"attr:queueDepth" json:"queue_depth"`
ProcessingBacklog int64 `theorydb:"attr:processingBacklog" json:"processing_backlog_ms"`
BurstCapacity float64 `theorydb:"attr:burstCapacity" json:"burst_capacity"`
// 4. Error Metrics (10% weight)
SignatureFailures int64 `theorydb:"attr:signatureFailures" json:"signature_failures"`
TimeoutRate float64 `theorydb:"attr:timeoutRate" json:"timeout_rate"` // 0-1
RateLimitHits int64 `theorydb:"attr:rateLimitHits" json:"rate_limit_hits"`
MalformedActivities int64 `theorydb:"attr:malformedActivities" json:"malformed_activities"`
ValidationFailures int64 `theorydb:"attr:validationFailures" json:"validation_failures"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"` // Total error rate (0-1)
// 5. Cost Efficiency Metrics
PerActivityCost float64 `theorydb:"attr:perActivityCost" json:"per_activity_cost_usd"`
BandwidthCost float64 `theorydb:"attr:bandwidthCost" json:"bandwidth_cost_usd"`
ComputeCost float64 `theorydb:"attr:computeCost" json:"compute_cost_usd"`
StorageCost float64 `theorydb:"attr:storageCost" json:"storage_cost_usd"`
EgressCost float64 `theorydb:"attr:egressCost" json:"egress_cost_usd"`
// Volume metrics for aggregation
TotalInboundVolume int64 `theorydb:"attr:totalInboundVolume" json:"total_inbound_volume"` // bytes
TotalOutboundVolume int64 `theorydb:"attr:totalOutboundVolume" json:"total_outbound_volume"` // bytes
ActivityCount int64 `theorydb:"attr:activityCount" json:"activity_count"`
SuccessfulActivities int64 `theorydb:"attr:successfulActivities" json:"successful_activities"`
FailedActivities int64 `theorydb:"attr:failedActivities" json:"failed_activities"`
// Health Score (calculated field)
HealthScore float64 `theorydb:"attr:healthScore" json:"health_score"` // 0-100
// Aggregation metadata
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"`
SampleCount int64 `theorydb:"attr:sampleCount" json:"sample_count"` // Number of raw samples aggregated
AggregationLevel string `theorydb:"attr:aggregationLevel" json:"aggregation_level"` // raw, 5min, hourly, daily, monthly
CompressedData []byte `theorydb:"attr:compressedData" json:"compressed_data,omitempty"` // Compressed historical data
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup based on aggregation level
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // Unix timestamp
// contains filtered or unexported fields
}
FederationAnalyticsTimeSeries represents time series federation metrics with 5-minute primary aggregation
func NewFederationAnalyticsTimeSeries ¶
func NewFederationAnalyticsTimeSeries(domain, period string, timestamp time.Time) *FederationAnalyticsTimeSeries
NewFederationAnalyticsTimeSeries creates a new time series record with proper defaults
func (*FederationAnalyticsTimeSeries) Aggregate ¶
func (f *FederationAnalyticsTimeSeries) Aggregate(rawMetrics []*FederationAnalyticsTimeSeries)
Aggregate aggregates raw metrics into this time series record
func (*FederationAnalyticsTimeSeries) CalculateHealthScore ¶
func (f *FederationAnalyticsTimeSeries) CalculateHealthScore()
CalculateHealthScore calculates instance health score based on weighted metrics Following guidance: 40% availability, 30% performance, 20% reliability, 10% activity
func (*FederationAnalyticsTimeSeries) IsCritical ¶
func (f *FederationAnalyticsTimeSeries) IsCritical() bool
IsCritical returns true if the instance is in critical state
func (*FederationAnalyticsTimeSeries) IsDegraded ¶
func (f *FederationAnalyticsTimeSeries) IsDegraded() bool
IsDegraded returns true if the instance is in a degraded state
func (*FederationAnalyticsTimeSeries) IsHealthy ¶
func (f *FederationAnalyticsTimeSeries) IsHealthy() bool
IsHealthy returns true if the instance is considered healthy based on thresholds
func (*FederationAnalyticsTimeSeries) IsUnhealthy ¶
func (f *FederationAnalyticsTimeSeries) IsUnhealthy() bool
IsUnhealthy returns true if the instance is unhealthy
func (*FederationAnalyticsTimeSeries) ShouldTriggerAlert ¶
func (f *FederationAnalyticsTimeSeries) ShouldTriggerAlert() (bool, string)
ShouldTriggerAlert checks if this metric should trigger an alert
func (FederationAnalyticsTimeSeries) TableName ¶
func (FederationAnalyticsTimeSeries) TableName() string
TableName returns the DynamoDB table backing FederationAnalyticsTimeSeries.
func (*FederationAnalyticsTimeSeries) UpdateKeys ¶
func (f *FederationAnalyticsTimeSeries) UpdateKeys()
UpdateKeys sets all primary and GSI keys for the time series record
type FederationBudget ¶
type FederationBudget struct {
// Primary keys - federation budgets use FED_BUDGET#{domain}#{period} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for active budget queries - ACTIVE_BUDGETS, DOMAIN#{domain}#{period}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// Budget configuration
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // daily, weekly, monthly
// Budget limits (in microcents)
InboundLimitMicroCents int64 `theorydb:"attr:inboundLimitMicroCents" json:"inbound_limit_micro_cents"`
OutboundLimitMicroCents int64 `theorydb:"attr:outboundLimitMicroCents" json:"outbound_limit_micro_cents"`
CombinedLimitMicroCents int64 `theorydb:"attr:combinedLimitMicroCents" json:"combined_limit_micro_cents"`
// Per-activity type limits
ActivityTypeLimits map[string]int64 `theorydb:"attr:activityTypeLimits" json:"activity_type_limits,omitempty"`
// Current usage (reset per period)
CurrentInboundCost int64 `theorydb:"attr:currentInboundCost" json:"current_inbound_cost"`
CurrentOutboundCost int64 `theorydb:"attr:currentOutboundCost" json:"current_outbound_cost"`
CurrentCombinedCost int64 `theorydb:"attr:currentCombinedCost" json:"current_combined_cost"`
// Activity type usage
ActivityTypeUsage map[string]int64 `theorydb:"attr:activityTypeUsage" json:"activity_type_usage,omitempty"`
// Usage tracking
InboundActivityCount int64 `theorydb:"attr:inboundActivityCount" json:"inbound_activity_count"`
OutboundActivityCount int64 `theorydb:"attr:outboundActivityCount" json:"outbound_activity_count"`
LastInboundAt *time.Time `theorydb:"attr:lastInboundAt" json:"last_inbound_at,omitempty"`
LastOutboundAt *time.Time `theorydb:"attr:lastOutboundAt" json:"last_outbound_at,omitempty"`
// Period tracking
PeriodStart time.Time `theorydb:"attr:periodStart" json:"period_start"`
PeriodEnd time.Time `theorydb:"attr:periodEnd" json:"period_end"`
// Alert settings
AlertThresholdPercent float64 `theorydb:"attr:alertThresholdPercent" json:"alert_threshold_percent"` // Send alert at this % of limit
AlertSendingEnabled bool `theorydb:"attr:alertSendingEnabled" json:"alert_sending_enabled"`
LastAlertSentAt *time.Time `theorydb:"attr:lastAlertSentAt" json:"last_alert_sent_at,omitempty"`
// Enforcement settings
BlockOnLimitExceeded bool `theorydb:"attr:blockOnLimitExceeded" json:"block_on_limit_exceeded"`
RateLimitOnThreshold bool `theorydb:"attr:rateLimitOnThreshold" json:"rate_limit_on_threshold"`
// Status
IsActive bool `theorydb:"attr:isActive" json:"is_active"`
Status string `theorydb:"attr:status" json:"status"` // active, suspended, over_limit
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
FederationBudget represents budget limits for federation operations per instance
func (*FederationBudget) AddUsage ¶
func (f *FederationBudget) AddUsage(activityType, direction string, cost int64)
AddUsage adds usage for a specific activity type and direction
func (*FederationBudget) BeforeCreate ¶
func (f *FederationBudget) BeforeCreate() error
BeforeCreate is called before creating the record
func (*FederationBudget) BeforeUpdate ¶
func (f *FederationBudget) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*FederationBudget) GetActivityTypeUsagePercent ¶
func (f *FederationBudget) GetActivityTypeUsagePercent(activityType string) float64
GetActivityTypeUsagePercent returns activity type usage as a percentage of limit
func (*FederationBudget) GetCombinedUsagePercent ¶
func (f *FederationBudget) GetCombinedUsagePercent() float64
GetCombinedUsagePercent returns combined usage as a percentage of limit
func (*FederationBudget) GetInboundUsagePercent ¶
func (f *FederationBudget) GetInboundUsagePercent() float64
GetInboundUsagePercent returns inbound usage as a percentage of limit
func (*FederationBudget) GetOutboundUsagePercent ¶
func (f *FederationBudget) GetOutboundUsagePercent() float64
GetOutboundUsagePercent returns outbound usage as a percentage of limit
func (*FederationBudget) GetPK ¶
func (f *FederationBudget) GetPK() string
GetPK returns the partition key (required for BaseModel interface)
func (*FederationBudget) GetSK ¶
func (f *FederationBudget) GetSK() string
GetSK returns the sort key (required for BaseModel interface)
func (*FederationBudget) IsOverActivityTypeLimit ¶
func (f *FederationBudget) IsOverActivityTypeLimit(activityType string) bool
IsOverActivityTypeLimit checks if the domain is over a specific activity type limit
func (*FederationBudget) IsOverCombinedLimit ¶
func (f *FederationBudget) IsOverCombinedLimit() bool
IsOverCombinedLimit checks if the domain is over their combined limit
func (*FederationBudget) IsOverInboundLimit ¶
func (f *FederationBudget) IsOverInboundLimit() bool
IsOverInboundLimit checks if the domain is over their inbound limit
func (*FederationBudget) IsOverOutboundLimit ¶
func (f *FederationBudget) IsOverOutboundLimit() bool
IsOverOutboundLimit checks if the domain is over their outbound limit
func (*FederationBudget) ResetPeriod ¶
func (f *FederationBudget) ResetPeriod(newPeriodStart, newPeriodEnd time.Time)
ResetPeriod resets usage counters for a new period
func (*FederationBudget) ShouldBlock ¶
func (f *FederationBudget) ShouldBlock() bool
ShouldBlock checks if federation should be blocked for this domain
func (*FederationBudget) ShouldRateLimit ¶
func (f *FederationBudget) ShouldRateLimit() bool
ShouldRateLimit checks if federation should be rate limited for this domain
func (*FederationBudget) ShouldSendAlert ¶
func (f *FederationBudget) ShouldSendAlert() bool
ShouldSendAlert checks if an alert should be sent
func (FederationBudget) TableName ¶
func (FederationBudget) TableName() string
TableName returns the DynamoDB table backing FederationBudget.
func (*FederationBudget) UpdateKeys ¶
func (f *FederationBudget) UpdateKeys() error
UpdateKeys sets the primary keys for the FederationBudget model
type FederationCost ¶
type FederationCost struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // daily/monthly
IngressBytes int64 `theorydb:"attr:ingressBytes" json:"ingress_bytes"`
EgressBytes int64 `theorydb:"attr:egressBytes" json:"egress_bytes"`
RequestCount int64 `theorydb:"attr:requestCount" json:"request_count"`
ErrorCount int64 `theorydb:"attr:errorCount" json:"error_count"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
AvgResponseTime float64 `theorydb:"attr:avgResponseTime" json:"avg_response_time"`
EstimatedCostUSD float64 `theorydb:"attr:estimatedCostUSD" json:"estimated_cost_usd"`
LastUpdated time.Time `theorydb:"attr:lastUpdated" json:"last_updated"`
// contains filtered or unexported fields
}
FederationCost represents aggregated federation cost data
func (FederationCost) TableName ¶
func (FederationCost) TableName() string
TableName returns the DynamoDB table backing FederationCost.
func (*FederationCost) UpdateKeys ¶
func (f *FederationCost) UpdateKeys()
UpdateKeys updates the GSI keys for federation cost
type FederationCostActivity ¶
type FederationCostActivity struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ID string `theorydb:"attr:id" json:"id"`
Domain string `theorydb:"attr:domain" json:"domain"`
Type string `theorydb:"attr:type" json:"type"` // ingress/egress
ActivityType string `theorydb:"attr:activityType" json:"activity_type"` // Create/Update/Delete/Follow/etc
ByteSize int64 `theorydb:"attr:byteSize" json:"byte_size"`
Success bool `theorydb:"attr:success" json:"success"`
ResponseTime int64 `theorydb:"attr:responseTime" json:"response_time"` // milliseconds
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationCostActivity represents a federation activity for cost tracking
func (*FederationCostActivity) GetPK ¶
func (f *FederationCostActivity) GetPK() string
GetPK returns the partition key for BaseRepository compatibility
func (*FederationCostActivity) GetSK ¶
func (f *FederationCostActivity) GetSK() string
GetSK returns the sort key for BaseRepository compatibility
func (FederationCostActivity) TableName ¶
func (FederationCostActivity) TableName() string
TableName returns the DynamoDB table backing FederationCostActivity.
func (*FederationCostActivity) UpdateKeys ¶
func (f *FederationCostActivity) UpdateKeys() error
UpdateKeys updates the GSI keys for federation cost activity
type FederationCostTracking ¶
type FederationCostTracking struct {
// Primary keys - federation cost tracking uses FED_COST#{domain}#{timestamp} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for time-based domain queries - FED_COSTS#DOMAIN#{domain}#{YYYY-MM}, TS#{unix_millis}#{activity_type}#{activity_id}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for activity type queries - FED_TYPE#{activity_type}, DOMAIN#{domain}#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Federation activity metadata
ActivityID string `theorydb:"attr:activityID" json:"activity_id"`
Domain string `theorydb:"attr:domain" json:"domain"` // Remote instance domain
InstanceDomain string `theorydb:"attr:instanceDomain" json:"instance_domain"` // Alias for Domain for compatibility
ActivityType string `theorydb:"attr:activityType" json:"activity_type"` // Create, Follow, Like, etc.
Direction string `theorydb:"attr:direction" json:"direction"` // inbound, outbound
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // inbox_processing, outbox_delivery, signature_verification
// Billing period tracking
BillingPeriod string `theorydb:"attr:billingPeriod" json:"billing_period"` // YYYY-MM format
LastUpdated time.Time `theorydb:"attr:lastUpdated" json:"last_updated"` // Last update timestamp
// Legacy compatibility fields for aggregated metrics
IngressBytes int64 `theorydb:"attr:ingressBytes" json:"ingress_bytes"` // Inbound data bytes
EgressBytes int64 `theorydb:"attr:egressBytes" json:"egress_bytes"` // Outbound data bytes
RequestCount int `theorydb:"attr:requestCount" json:"request_count"` // Number of requests
ErrorCount int `theorydb:"attr:errorCount" json:"error_count"` // Number of errors
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"` // Error rate percentage
AverageCostUSD float64 `theorydb:"attr:averageCostUSD" json:"average_cost_usd"` // Average cost in USD
// Success/failure tracking
Success bool `theorydb:"attr:success" json:"success"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
// Lambda execution costs (all in microdollars)
LambdaExecutionCost int64 `theorydb:"attr:lambdaExecutionCost" json:"lambda_execution_cost"` // Lambda compute cost
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Lambda execution time
LambdaMemoryMB int64 `theorydb:"attr:lambdaMemoryMB" json:"lambda_memory_mb"` // Lambda memory allocation
// HTTP signature verification costs (CPU intensive)
SignatureVerificationMs int64 `theorydb:"attr:signatureVerificationMs" json:"signature_verification_ms"` // Time spent verifying signatures
SignatureVerificationCost int64 `theorydb:"attr:signatureVerificationCost" json:"signature_verification_cost"` // CPU cost for signature verification
// Network costs
HTTPRequestCount int64 `theorydb:"attr:httpRequestCount" json:"http_request_count"` // Number of HTTP requests made
HTTPRequestCost int64 `theorydb:"attr:httpRequestCost" json:"http_request_cost"` // Cost of HTTP requests ($0.0001 per request)
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Bytes transferred (inbound/outbound)
DataTransferCost int64 `theorydb:"attr:dataTransferCost" json:"data_transfer_cost"` // Data transfer costs ($0.09 per GB outbound)
// DynamoDB costs
DynamoDBWriteCount int64 `theorydb:"attr:dynamodbWriteCount" json:"dynamodb_write_count"` // Number of write operations
DynamoDBReadCount int64 `theorydb:"attr:dynamodbReadCount" json:"dynamodb_read_count"` // Number of read operations
DynamoDBWriteUnits float64 `theorydb:"attr:dynamodbWriteUnits" json:"dynamodb_write_units"` // Write capacity consumed
DynamoDBReadUnits float64 `theorydb:"attr:dynamodbReadUnits" json:"dynamodb_read_units"` // Read capacity consumed
DynamoDBWriteCost int64 `theorydb:"attr:dynamodbWriteCost" json:"dynamodb_write_cost"` // Write operation costs
DynamoDBReadCost int64 `theorydb:"attr:dynamodbReadCost" json:"dynamodb_read_cost"` // Read operation costs
// DNS/WebFinger costs
DNSLookupCount int64 `theorydb:"attr:dnsLookupCount" json:"dns_lookup_count"` // Number of DNS lookups
DNSLookupCost int64 `theorydb:"attr:dnsLookupCost" json:"dns_lookup_cost"` // DNS lookup costs ($0.0004 per query)
WebFingerCount int64 `theorydb:"attr:webFingerCount" json:"webfinger_count"` // WebFinger lookups
WebFingerCost int64 `theorydb:"attr:webFingerCost" json:"webfinger_cost"` // WebFinger lookup costs
// SQS costs (for outbound delivery queue)
SQSMessageCount int64 `theorydb:"attr:sqsMessageCount" json:"sqs_message_count"` // SQS messages sent
SQSMessageCost int64 `theorydb:"attr:sqsMessageCost" json:"sqs_message_cost"` // SQS message costs ($0.0000004 per message)
// Retry penalty costs
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"` // Number of retries performed
RetryCost int64 `theorydb:"attr:retryCost" json:"retry_cost"` // Additional cost penalties for retries
// Detailed per-delivery attribution
BytesSent int64 `theorydb:"attr:bytesSent" json:"bytes_sent"` // Actual bytes sent per delivery attempt
RetryAttempts int `theorydb:"attr:retryAttempts" json:"retry_attempts"` // Number of retry attempts for this specific delivery
DeliveryAttempts int `theorydb:"attr:deliveryAttempts" json:"delivery_attempts"` // Total delivery attempts (including first)
RouteID string `theorydb:"attr:routeID" json:"route_id,omitempty"` // Route used for delivery
DestinationServer string `theorydb:"attr:destinationServer" json:"destination_server"` // Destination server domain
RouteBreakdown map[string]int64 `theorydb:"attr:routeBreakdown" json:"route_breakdown"` // Per-route cost breakdown in microcents
// Per-route delivery metrics
RouteLatency map[string]int64 `theorydb:"attr:routeLatency" json:"route_latency"` // Per-route response times in ms
RouteErrors map[string]int `theorydb:"attr:routeErrors" json:"route_errors"` // Per-route error counts
RouteAttempts map[string]int `theorydb:"attr:routeAttempts" json:"route_attempts"` // Per-route total attempts
RouteSuccessRates map[string]float64 `theorydb:"attr:routeSuccessRates" json:"route_success_rates"` // Per-route success rates
// Enhanced retry tracking
RetryDelaySeconds []int64 `theorydb:"attr:retryDelaySeconds" json:"retry_delay_seconds"` // Delay between retry attempts
RetryErrorMessages []string `theorydb:"attr:retryErrorMessages" json:"retry_error_messages"` // Error messages for each retry
FinalRetrySuccess bool `theorydb:"attr:finalRetrySuccess" json:"final_retry_success"` // Whether final retry succeeded
// Performance metrics
ResponseTimeMs int64 `theorydb:"attr:responseTimeMs" json:"response_time_ms"` // Total response time
ProcessingTimeMs int64 `theorydb:"attr:processingTimeMs" json:"processing_time_ms"` // Time spent processing
QueueWaitTimeMs int64 `theorydb:"attr:queueWaitTimeMs" json:"queue_wait_time_ms"` // Time spent waiting in queue
// Data volume metrics
PayloadSize int64 `theorydb:"attr:payloadSize" json:"payload_size"` // Size of activity payload
CompressedSize int64 `theorydb:"attr:compressedSize" json:"compressed_size"` // Size after compression
CompressionRatio float64 `theorydb:"attr:compressionRatio" json:"compression_ratio"` // Compression efficiency
// Total cost breakdown
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost in microcents
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (30 days for detailed cost records)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationCostTracking represents comprehensive cost tracking for federation activities
func (*FederationCostTracking) AddRetryDelay ¶
func (f *FederationCostTracking) AddRetryDelay(delaySeconds int64)
AddRetryDelay tracks the delay before a retry attempt
func (*FederationCostTracking) AddRouteDeliveryAttempt ¶
func (f *FederationCostTracking) AddRouteDeliveryAttempt(routeID string, bytes int64, latencyMs int64, success bool, errorMsg string)
AddRouteDeliveryAttempt tracks a delivery attempt for a specific route
func (*FederationCostTracking) BeforeCreate ¶
func (f *FederationCostTracking) BeforeCreate() error
BeforeCreate is called before creating the record
func (*FederationCostTracking) BeforeUpdate ¶
func (f *FederationCostTracking) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*FederationCostTracking) CalculateTotalCost ¶
func (f *FederationCostTracking) CalculateTotalCost()
CalculateTotalCost calculates the total cost from all components
func (*FederationCostTracking) GetAverageRouteLatency ¶
func (f *FederationCostTracking) GetAverageRouteLatency() int64
GetAverageRouteLatency returns the average latency across all routes
func (*FederationCostTracking) GetMostExpensiveRoute ¶
func (f *FederationCostTracking) GetMostExpensiveRoute() (string, int64)
GetMostExpensiveRoute returns the route ID with the highest cost
func (*FederationCostTracking) GetPK ¶
func (f *FederationCostTracking) GetPK() string
GetPK returns the partition key (required for BaseModel interface)
func (*FederationCostTracking) GetRetryEfficiency ¶
func (f *FederationCostTracking) GetRetryEfficiency() map[string]interface{}
GetRetryEfficiency returns metrics about retry effectiveness
func (*FederationCostTracking) GetSK ¶
func (f *FederationCostTracking) GetSK() string
GetSK returns the sort key (required for BaseModel interface)
func (*FederationCostTracking) GetTotalCostDollars ¶
func (f *FederationCostTracking) GetTotalCostDollars() float64
GetTotalCostDollars returns the total cost in dollars
func (*FederationCostTracking) GetTotalRouteErrors ¶
func (f *FederationCostTracking) GetTotalRouteErrors() int
GetTotalRouteErrors returns the total error count across all routes
func (FederationCostTracking) TableName ¶
func (FederationCostTracking) TableName() string
TableName returns the DynamoDB table backing FederationCostTracking.
func (*FederationCostTracking) UpdateKeys ¶
func (f *FederationCostTracking) UpdateKeys() error
UpdateKeys sets the primary keys for the FederationCostTracking model
type FederationEdge ¶
type FederationEdge struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"`
SourceDomain string `theorydb:"attr:sourceDomain" json:"source_domain"`
TargetDomain string `theorydb:"attr:targetDomain" json:"target_domain"`
ConnectionType string `theorydb:"attr:connectionType" json:"connection_type"` // follows/mentions/boosts/replies
VolumeIn int64 `theorydb:"attr:volumeIn" json:"volume_in"`
VolumeOut int64 `theorydb:"attr:volumeOut" json:"volume_out"`
Strength float64 `theorydb:"attr:strength" json:"strength"` // 0.0-1.0 based on activity volume
LastActivity time.Time `theorydb:"attr:lastActivity" json:"last_activity"`
ErrorCount int64 `theorydb:"attr:errorCount" json:"error_count"`
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"`
// contains filtered or unexported fields
}
FederationEdge represents an edge between federation nodes
func (FederationEdge) TableName ¶
func (FederationEdge) TableName() string
TableName returns the DynamoDB table backing FederationEdge.
func (*FederationEdge) UpdateKeys ¶
func (f *FederationEdge) UpdateKeys()
UpdateKeys updates the GSI keys for federation edge
type FederationHealthReport ¶
type FederationHealthReport struct {
Domain string `json:"domain"`
Status string `json:"status"` // healthy/warning/critical
ResponseTime float64 `json:"response_time"`
ErrorRate float64 `json:"error_rate"`
FederationDelay float64 `json:"federation_delay"`
QueueDepth int `json:"queue_depth"`
Issues []string `json:"issues"`
Recommendations []string `json:"recommendations"`
LastChecked time.Time `json:"last_checked"`
}
FederationHealthReport represents instance health metrics (computed, not stored)
func (FederationHealthReport) TableName ¶
func (FederationHealthReport) TableName() string
TableName returns the DynamoDB table backing FederationHealthReport.
type FederationInstance ¶
type FederationInstance struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
Domain string `theorydb:"attr:domain" json:"domain"`
Software string `theorydb:"attr:software" json:"software"` // mastodon, pleroma, etc.
Version string `theorydb:"attr:version" json:"version"` // Software version
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"` // When we first saw this instance
LastSeen time.Time `theorydb:"attr:lastSeen" json:"last_seen"` // Last activity from this instance
PublicKey string `theorydb:"attr:publicKey" json:"public_key"` // Instance actor public key
TrustScore float64 `theorydb:"attr:trustScore" json:"trust_score"` // Calculated trust score
ActiveUsers int `theorydb:"attr:activeUsers" json:"active_users"` // Number of active users
TotalMessages int64 `theorydb:"attr:totalMessages" json:"total_messages"` // Total messages received
// contains filtered or unexported fields
}
FederationInstance represents federation instance information in DynamoDB
func (FederationInstance) TableName ¶
func (FederationInstance) TableName() string
TableName returns the DynamoDB table backing FederationInstance.
func (*FederationInstance) UpdateKeys ¶
func (f *FederationInstance) UpdateKeys()
UpdateKeys updates the GSI keys for federation instance
type FederationInstanceConfigTracking ¶
type FederationInstanceConfigTracking struct {
// Primary keys - INSTANCE#{domain}, CONFIG
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for tier queries - TIER#{tier}, DOMAIN#{domain}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for budget queries - BUDGET_OVERRIDE, BUDGET#{budget}#{domain}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Instance identification
Domain string `theorydb:"attr:domain" json:"domain"` // Remote instance domain
// Tier and budget configuration
Tier FederationTier `theorydb:"attr:tier" json:"tier"` // Federation tier
CustomBudgetUSD *float64 `theorydb:"attr:customBudgetUSD" json:"custom_budget_usd,omitempty"` // Custom monthly budget (if set)
RateLimitOverride *int `theorydb:"attr:rateLimitOverride" json:"rate_limit_override,omitempty"` // Custom rate limit (requests/hour)
// Retry configuration
RetryPolicy *RetryPolicy `theorydb:"attr:retryPolicy" json:"retry_policy,omitempty"` // Custom retry policy
// Feature flags
EnableSignatureValidation bool `theorydb:"attr:enableSignatureValidation" json:"enable_signature_validation"` // Whether to validate HTTP signatures
EnableRateLimiting bool `theorydb:"attr:enableRateLimiting" json:"enable_rate_limiting"` // Whether to apply rate limits
EnableBudgetEnforcement bool `theorydb:"attr:enableBudgetEnforcement" json:"enable_budget_enforcement"` // Whether to enforce budget limits
AllowPublicActivities bool `theorydb:"attr:allowPublicActivities" json:"allow_public_activities"` // Whether to accept public activities
AllowFollowers bool `theorydb:"attr:allowFollowers" json:"allow_followers"` // Whether to accept follow requests
AllowMentions bool `theorydb:"attr:allowMentions" json:"allow_mentions"` // Whether to process mentions
// Caching configuration
CacheTTLSeconds int `theorydb:"attr:cacheTTLSeconds" json:"cache_ttl_seconds"` // Actor/object cache TTL
MaxCacheSize int `theorydb:"attr:maxCacheSize" json:"max_cache_size"` // Maximum cached items per instance
EnableCaching bool `theorydb:"attr:enableCaching" json:"enable_caching"` // Whether to cache instance data
// Performance tuning
MaxConcurrentRequests int `theorydb:"attr:maxConcurrentRequests" json:"max_concurrent_requests"` // Max concurrent outbound requests
RequestTimeoutSeconds int `theorydb:"attr:requestTimeoutSeconds" json:"request_timeout_seconds"` // HTTP request timeout
ConnectionPoolSize int `theorydb:"attr:connectionPoolSize" json:"connection_pool_size"` // HTTP connection pool size
CompressionThreshold int `theorydb:"attr:compressionThreshold" json:"compression_threshold"` // Bytes threshold for compression
// Trust and reputation
TrustScore float64 `theorydb:"attr:trustScore" json:"trust_score"` // 0.0 to 1.0 trust score
ReputationMultiplier float64 `theorydb:"attr:reputationMultiplier" json:"reputation_multiplier"` // Cost multiplier based on reputation
RequireVouch bool `theorydb:"attr:requireVouch" json:"require_vouch"` // Whether vouching is required
AutoAcceptThreshold float64 `theorydb:"attr:autoAcceptThreshold" json:"auto_accept_threshold"` // Trust score for auto-accept
// Admin notes
Notes string `theorydb:"attr:notes" json:"notes,omitempty"` // Admin notes about the instance
ContactEmail string `theorydb:"attr:contactEmail" json:"contact_email,omitempty"` // Admin contact email
// Type marker for queries
Type string `theorydb:"attr:type" json:"type"` // Always "InstanceConfig"
// Timestamps
Created time.Time `theorydb:"attr:created" json:"created"`
LastModified time.Time `theorydb:"attr:lastModified" json:"last_modified"`
// contains filtered or unexported fields
}
FederationInstanceConfigTracking stores configuration for federated instances
func (*FederationInstanceConfigTracking) BeforeCreate ¶
func (f *FederationInstanceConfigTracking) BeforeCreate() error
BeforeCreate is called before creating the record
func (*FederationInstanceConfigTracking) BeforeUpdate ¶
func (f *FederationInstanceConfigTracking) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*FederationInstanceConfigTracking) GetBudgetLimit ¶
func (f *FederationInstanceConfigTracking) GetBudgetLimit() float64
GetBudgetLimit returns the effective budget limit for the instance
func (*FederationInstanceConfigTracking) GetRateLimit ¶
func (f *FederationInstanceConfigTracking) GetRateLimit() int
GetRateLimit returns the effective rate limit for the instance
func (FederationInstanceConfigTracking) TableName ¶
func (FederationInstanceConfigTracking) TableName() string
TableName returns the DynamoDB table backing FederationInstanceConfigTracking.
func (*FederationInstanceConfigTracking) UpdateKeys ¶
func (f *FederationInstanceConfigTracking) UpdateKeys()
UpdateKeys sets the primary and GSI keys for the config tracking model
type FederationInstanceHealthTracking ¶
type FederationInstanceHealthTracking struct {
// Primary keys - INSTANCE#{domain}, HEALTH
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for time-based queries - HEALTH_CHECK#{date}, TS#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for unhealthy instances - UNHEALTHY (if unhealthy), SCORE#{health_score}#{domain}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Instance identification
Domain string `theorydb:"attr:domain" json:"domain"` // Remote instance domain
// Health metrics
HealthScore float64 `theorydb:"attr:healthScore" json:"health_score"` // 0.0 to 1.0 (1.0 = perfect health)
ResponseTimeP95 int64 `theorydb:"attr:responseTimeP95" json:"response_time_p95"` // 95th percentile response time in ms
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"` // 0.0 to 1.0 (1.0 = 100% success)
ConsecutiveFails int `theorydb:"attr:consecutiveFails" json:"consecutive_fails"` // Number of consecutive failed requests
IsHealthy bool `theorydb:"attr:isHealthy" json:"is_healthy"` // Overall health status
// Performance metrics
AverageResponseTime int64 `theorydb:"attr:averageResponseTime" json:"average_response_time"` // Average response time in ms
TotalRequests int64 `theorydb:"attr:totalRequests" json:"total_requests"` // Total requests in measurement period
FailedRequests int64 `theorydb:"attr:failedRequests" json:"failed_requests"` // Failed requests in measurement period
// Capacity metrics
RateLimitRemaining int `theorydb:"attr:rateLimitRemaining" json:"rate_limit_remaining"` // Remaining rate limit capacity
RateLimitReset int64 `theorydb:"attr:rateLimitReset" json:"rate_limit_reset"` // Unix timestamp when rate limit resets
BackoffUntil *int64 `theorydb:"attr:backoffUntil" json:"backoff_until"` // Unix timestamp to back off until (if applicable)
// Timestamps
LastHealthCheck time.Time `theorydb:"attr:lastHealthCheck" json:"last_health_check"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (7 days for health records)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationInstanceHealthTracking tracks health metrics for federated instances
func (*FederationInstanceHealthTracking) BeforeCreate ¶
func (f *FederationInstanceHealthTracking) BeforeCreate() error
BeforeCreate is called before creating the record
func (*FederationInstanceHealthTracking) BeforeUpdate ¶
func (f *FederationInstanceHealthTracking) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*FederationInstanceHealthTracking) CalculateHealthScore ¶
func (f *FederationInstanceHealthTracking) CalculateHealthScore()
CalculateHealthScore calculates the overall health score based on metrics
func (*FederationInstanceHealthTracking) TableName ¶
func (f *FederationInstanceHealthTracking) TableName() string
TableName returns the DynamoDB table backing FederationInstanceHealthTracking.
func (*FederationInstanceHealthTracking) UpdateKeys ¶
func (f *FederationInstanceHealthTracking) UpdateKeys()
UpdateKeys sets the primary and GSI keys for the health tracking model
type FederationInstanceRegistry ¶
type FederationInstanceRegistry struct {
// Primary keys - using pattern: PK=INSTANCE#<domain>, SK=METADATA
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI keys for status-based queries (GSI1)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI keys for tier-based queries (GSI2)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Core instance attributes
ID string `theorydb:"attr:id" json:"id"`
Domain string `theorydb:"attr:domain" json:"domain"`
InboxURL string `theorydb:"attr:inboxURL" json:"inbox_url"`
PublicKeyPEM string `theorydb:"attr:publicKeyPEM" json:"public_key_pem"`
// Capabilities
SupportedTypes []string `theorydb:"attr:supportedTypes" json:"supported_types"`
MaxMessageSize int64 `theorydb:"attr:maxMessageSize" json:"max_message_size"`
// Rate limits (stored as nested JSON)
RateLimits map[string]interface{} `theorydb:"attr:rateLimits" json:"rate_limits"`
// Status and timestamps
Status string `theorydb:"attr:status" json:"status"`
LastSeen time.Time `theorydb:"attr:lastSeen" json:"last_seen"`
RegisteredAt time.Time `theorydb:"attr:registeredAt" json:"registered_at"`
// Performance metrics
AvgResponseTime int64 `theorydb:"attr:avgResponseTime" json:"avg_response_time"` // milliseconds
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
// Cost tracking
TierLevel string `theorydb:"attr:tierLevel" json:"tier_level"`
MonthlyQuota int64 `theorydb:"attr:monthlyQuota" json:"monthly_quota"`
CurrentUsage int64 `theorydb:"attr:currentUsage" json:"current_usage"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
FederationInstanceRegistry represents a federated instance in the routing registry
func (*FederationInstanceRegistry) GetPK ¶
func (f *FederationInstanceRegistry) GetPK() string
GetPK returns the partition key
func (*FederationInstanceRegistry) GetSK ¶
func (f *FederationInstanceRegistry) GetSK() string
GetSK returns the sort key
func (FederationInstanceRegistry) TableName ¶
func (FederationInstanceRegistry) TableName() string
TableName returns the DynamoDB table backing FederationInstanceRegistry.
func (*FederationInstanceRegistry) ToInstance ¶
func (f *FederationInstanceRegistry) ToInstance() *types.Instance
ToInstance converts the model to a federation types Instance
func (*FederationInstanceRegistry) UpdateKeys ¶
func (f *FederationInstanceRegistry) UpdateKeys() error
UpdateKeys ensures GSI keys are properly set before saving
type FederationInstanceRegistryHealthHistory ¶
type FederationInstanceRegistryHealthHistory struct {
// Primary keys - using pattern: PK=INSTANCE#<instanceID>, SK=HEALTH#<timestamp>
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Health status fields
Reachable bool `theorydb:"attr:reachable" json:"reachable"`
ResponseTime int64 `theorydb:"attr:responseTime" json:"response_time"` // milliseconds
StatusCode int `theorydb:"attr:statusCode" json:"status_code"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
InboxBacklog int `theorydb:"attr:inboxBacklog" json:"inbox_backlog"`
ProcessingDelay int64 `theorydb:"attr:processingDelay" json:"processing_delay"` // milliseconds
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// TTL for automatic cleanup (keep 7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
FederationInstanceRegistryHealthHistory represents health history records
func (*FederationInstanceRegistryHealthHistory) GetPK ¶
func (h *FederationInstanceRegistryHealthHistory) GetPK() string
GetPK returns the partition key
func (*FederationInstanceRegistryHealthHistory) GetSK ¶
func (h *FederationInstanceRegistryHealthHistory) GetSK() string
GetSK returns the sort key
func (FederationInstanceRegistryHealthHistory) TableName ¶
func (FederationInstanceRegistryHealthHistory) TableName() string
TableName returns the DynamoDB table backing FederationInstanceRegistryHealthHistory.
func (*FederationInstanceRegistryHealthHistory) UpdateKeys ¶
func (h *FederationInstanceRegistryHealthHistory) UpdateKeys() error
UpdateKeys ensures keys are properly set for health history
type FederationIssue ¶
type FederationIssue struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Domain string `theorydb:"attr:domain" json:"domain"`
IssueType string `theorydb:"attr:issueType" json:"issue_type"` // "timeout", "error", "unreachable", "blocked"
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Severity string `theorydb:"attr:severity" json:"severity"` // "low", "medium", "high", "critical"
Resolved bool `theorydb:"attr:resolved" json:"resolved"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationIssue tracks federation issues for monitoring
func (FederationIssue) TableName ¶
func (FederationIssue) TableName() string
TableName returns the DynamoDB table backing FederationIssue.
func (*FederationIssue) UpdateKeys ¶
func (f *FederationIssue) UpdateKeys()
UpdateKeys updates the GSI keys for federation issue
type FederationNode ¶
type FederationNode struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty"`
Domain string `theorydb:"attr:domain" json:"domain"`
DisplayName string `theorydb:"attr:displayName" json:"display_name"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Software string `theorydb:"attr:software" json:"software"`
Version string `theorydb:"attr:version" json:"version"`
UserCount int64 `theorydb:"attr:userCount" json:"user_count"`
StatusCount int64 `theorydb:"attr:statusCount" json:"status_count"`
ActiveUsers int64 `theorydb:"attr:activeUsers" json:"active_users"`
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"`
LastSeen time.Time `theorydb:"attr:lastSeen" json:"last_seen"`
Health string `theorydb:"attr:health" json:"health"` // healthy/warning/critical/unknown
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
ResponseTime float64 `theorydb:"attr:responseTime" json:"response_time"`
ConnectionType string `theorydb:"attr:connectionType" json:"connection_type"` // direct/relay/blocked
TotalConnections int64 `theorydb:"attr:totalConnections" json:"total_connections,omitempty"`
ActiveConnections int64 `theorydb:"attr:activeConnections" json:"active_connections,omitempty"`
ActivityVolume int64 `theorydb:"attr:activityVolume" json:"activity_volume,omitempty"`
Metadata map[string]any `theorydb:"attr:metadata" json:"metadata,omitempty"`
// contains filtered or unexported fields
}
FederationNode represents a node in the federation graph
func (FederationNode) TableName ¶
func (FederationNode) TableName() string
TableName returns the DynamoDB table backing FederationNode.
func (*FederationNode) UpdateKeys ¶
func (f *FederationNode) UpdateKeys()
UpdateKeys updates the GSI keys for federation node
type FederationRelationship ¶
type FederationRelationship struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // State-based queries
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // Last activity timestamp
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"` // User-based queries
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"` // Target instance + timestamp
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Core relationship data
ID string `theorydb:"attr:id" json:"id"`
UserID string `theorydb:"attr:userID" json:"user_id"` // Local user ID
TargetInstance string `theorydb:"attr:targetInstance" json:"target_instance"` // Remote instance domain
TargetUserID string `theorydb:"attr:targetUserID" json:"target_user_id,omitempty"` // Remote user ID (if user-level)
RelationshipType string `theorydb:"attr:relationshipType" json:"relationship_type"` // follow, mention, boost, reply, etc.
// Lifecycle management
State RelationshipState `theorydb:"attr:state" json:"state"`
LastActivity time.Time `theorydb:"attr:lastActivity" json:"last_activity"`
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"`
StateChangedAt time.Time `theorydb:"attr:stateChangedAt" json:"state_changed_at"`
// Success rate tracking (15-minute rolling window)
SuccessCount15m int64 `theorydb:"attr:successCount15m" json:"success_count_15m"`
FailureCount15m int64 `theorydb:"attr:failureCount15m" json:"failure_count_15m"`
WindowStart15m time.Time `theorydb:"attr:windowStart15m" json:"window_start_15m"`
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"`
// Aggregated metrics
TotalSuccesses int64 `theorydb:"attr:totalSuccesses" json:"total_successes"`
TotalFailures int64 `theorydb:"attr:totalFailures" json:"total_failures"`
TotalAttempts int64 `theorydb:"attr:totalAttempts" json:"total_attempts"`
AvgResponseTime float64 `theorydb:"attr:avgResponseTime" json:"avg_response_time"`
// Reactivation handling
WarmupUntil *time.Time `theorydb:"attr:warmupUntil" json:"warmup_until,omitempty"`
CurrentRate float64 `theorydb:"attr:currentRate" json:"current_rate"` // Traffic rate during warmup (0.0-1.0)
HistoricalBaseline float64 `theorydb:"attr:historicalBaseline" json:"historical_baseline"` // Pre-dormancy success rate
// Storage optimization
ArchiveLocation string `theorydb:"attr:archiveLocation" json:"archive_location,omitempty"` // S3 key if archived
CompressedMetrics string `theorydb:"attr:compressedMetrics" json:"compressed_metrics,omitempty"` // Compressed historical data
LastCompressedAttempts int64 `theorydb:"attr:lastCompressedAttempts" json:"last_compressed_attempts"` // Baseline for delta compression
LastCompressionTime time.Time `theorydb:"attr:lastCompressionTime" json:"last_compression_time"` // When metrics were last compressed
IsCompressed bool `theorydb:"attr:isCompressed" json:"is_compressed"` // Flag indicating compressed state
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
FederationRelationship represents a relationship between users or instances with lifecycle tracking
func (*FederationRelationship) GetTrafficRate ¶
func (fr *FederationRelationship) GetTrafficRate() float64
GetTrafficRate returns the current traffic rate (1.0 = 100%, 0.1 = 10%)
func (*FederationRelationship) IsInWarmup ¶
func (fr *FederationRelationship) IsInWarmup() bool
IsInWarmup checks if the relationship is in warmup period after reactivation
func (*FederationRelationship) ShouldTransitionState ¶
func (fr *FederationRelationship) ShouldTransitionState() (RelationshipState, bool)
ShouldTransitionState checks if the relationship should transition to a new state
func (FederationRelationship) TableName ¶
func (FederationRelationship) TableName() string
TableName returns the DynamoDB table backing FederationRelationship.
func (*FederationRelationship) TransitionToState ¶
func (fr *FederationRelationship) TransitionToState(newState RelationshipState)
TransitionToState changes the relationship state and handles associated logic
func (*FederationRelationship) UpdateKeys ¶
func (fr *FederationRelationship) UpdateKeys()
UpdateKeys sets the DynamoDB keys for the federation relationship
func (*FederationRelationship) UpdateSuccessRate ¶
func (fr *FederationRelationship) UpdateSuccessRate(success bool, responseTime float64)
UpdateSuccessRate recalculates the 15-minute rolling window success rate
type FederationRelationshipAggregate ¶
type FederationRelationshipAggregate struct {
PK string `theorydb:"pk"`
SK string `theorydb:"sk"`
GSI1PK string `theorydb:"index:gsi1,pk,omitempty"` // Instance-based queries
GSI1SK string `theorydb:"index:gsi1,sk,omitempty"` // Period + timestamp
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Aggregate identification
InstanceDomain string `json:"instance_domain"`
Period string `json:"period"` // 15min, hourly, daily
Timestamp time.Time `json:"timestamp"`
// Aggregated metrics
ActiveRelationships int64 `json:"active_relationships"`
IdleRelationships int64 `json:"idle_relationships"`
DormantRelationships int64 `json:"dormant_relationships"`
TotalRelationships int64 `json:"total_relationships"`
// Success rates
OverallSuccessRate float64 `json:"overall_success_rate"`
TotalSuccesses15m int64 `json:"total_successes_15m"`
TotalFailures15m int64 `json:"total_failures_15m"`
// Performance metrics
AvgResponseTime float64 `json:"avg_response_time"`
P95ResponseTime float64 `json:"p95_response_time"`
// State transitions (for lifecycle analysis)
StateTransitions map[string]int64 `json:"state_transitions"`
ReactivationCount int64 `json:"reactivation_count"`
CreatedAt time.Time `json:"created_at"`
// contains filtered or unexported fields
}
FederationRelationshipAggregate represents aggregated relationship metrics for an instance
func (FederationRelationshipAggregate) TableName ¶
func (FederationRelationshipAggregate) TableName() string
TableName returns the DynamoDB table backing FederationRelationshipAggregate.
func (*FederationRelationshipAggregate) UpdateKeys ¶
func (fra *FederationRelationshipAggregate) UpdateKeys()
UpdateKeys sets the DynamoDB keys for the relationship aggregate
type FederationRelationshipIndex ¶
type FederationRelationshipIndex struct {
PK string `theorydb:"pk"`
SK string `theorydb:"sk"`
TTL int64 `json:"ttl,omitempty" theorydb:"ttl"`
RelationshipID string `json:"relationship_id"`
UserID string `json:"user_id"`
TargetInstance string `json:"target_instance"`
State RelationshipState `json:"state"`
LastActivity time.Time `json:"last_activity"`
ArchiveLocation string `json:"archive_location,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
FederationRelationshipIndex represents a minimal index entry for archived relationships
func (FederationRelationshipIndex) TableName ¶
func (FederationRelationshipIndex) TableName() string
TableName returns the DynamoDB table backing FederationRelationshipIndex.
func (*FederationRelationshipIndex) UpdateKeys ¶
func (fri *FederationRelationshipIndex) UpdateKeys()
UpdateKeys sets the DynamoDB keys for the relationship index
type FederationRouteAggregation ¶
type FederationRouteAggregation struct {
// Primary keys - route aggregation uses FED_ROUTE_AGG#{period}#{route_id} pattern
PK string `theorydb:"pk" json:"pk"`
SK string `theorydb:"sk" json:"sk"`
// GSI1 for route comparison queries - FED_ROUTE_COMPARE#{period}, SCORE#{health_score}#{route_id}
GSI1PK string `theorydb:"index:gsi1,pk,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,omitempty" json:"gsi1_sk"`
// Aggregation metadata
RouteID string `json:"route_id"`
DestinationDomain string `json:"destination_domain"`
Period string `json:"period"` // hour, day, week, month
PeriodStart time.Time `json:"period_start"`
PeriodEnd time.Time `json:"period_end"`
// Aggregated performance metrics
AvgHealthScore float64 `json:"avg_health_score"`
MinHealthScore float64 `json:"min_health_score"`
MaxHealthScore float64 `json:"max_health_score"`
HealthScoreStdDev float64 `json:"health_score_std_dev"`
TotalAttempts int64 `json:"total_attempts"`
TotalSuccesses int64 `json:"total_successes"`
OverallSuccessRate float64 `json:"overall_success_rate"`
AvgLatencyMs int64 `json:"avg_latency_ms"`
MedianLatencyMs int64 `json:"median_latency_ms"`
P95LatencyMs int64 `json:"p95_latency_ms"`
LatencyStdDev float64 `json:"latency_std_dev"`
// Cost aggregations
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
AvgCostPerDelivery int64 `json:"avg_cost_per_delivery"`
CostEfficiencyScore float64 `json:"cost_efficiency_score"`
// Reliability metrics
UptimePercentage float64 `json:"uptime_percentage"`
DowntimeMinutes int64 `json:"downtime_minutes"`
MTBF float64 `json:"mtbf"` // Mean Time Between Failures (hours)
MTTR float64 `json:"mttr"` // Mean Time To Recovery (minutes)
MaxConsecutiveFailures int64 `json:"max_consecutive_failures"`
CircuitBreakerTrips int64 `json:"circuit_breaker_trips"`
// Ranking and comparison
PerformanceRank int `json:"performance_rank"` // Rank among all routes for this domain
ReliabilityRank int `json:"reliability_rank"` // Rank based on reliability
CostEfficiencyRank int `json:"cost_efficiency_rank"` // Rank based on cost efficiency
OverallRank int `json:"overall_rank"` // Overall ranking
PercentileScore float64 `json:"percentile_score"` // Percentile among all routes
// Trend analysis
PerformanceTrend string `json:"performance_trend"` // improving, stable, degrading
ReliabilityTrend string `json:"reliability_trend"` // improving, stable, degrading
CostTrend string `json:"cost_trend"` // improving, stable, degrading
TrendConfidence float64 `json:"trend_confidence"` // Statistical confidence in trends
// Top error codes and frequencies
TopErrors []ErrorFrequency `json:"top_errors"`
// Timestamps
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// TTL for automatic cleanup (1 year for aggregated data)
TTL int64 `json:"ttl,omitempty" theorydb:"ttl"`
// contains filtered or unexported fields
}
FederationRouteAggregation represents aggregated route metrics across multiple time periods
func (*FederationRouteAggregation) BeforeCreate ¶
func (f *FederationRouteAggregation) BeforeCreate() error
BeforeCreate is called before creating the aggregated record
func (*FederationRouteAggregation) BeforeUpdate ¶
func (f *FederationRouteAggregation) BeforeUpdate() error
BeforeUpdate is called before updating the aggregated record
func (*FederationRouteAggregation) GetRouteComparisonMetrics ¶
func (f *FederationRouteAggregation) GetRouteComparisonMetrics() map[string]interface{}
GetRouteComparisonMetrics returns metrics for comparing routes
func (FederationRouteAggregation) TableName ¶
func (FederationRouteAggregation) TableName() string
TableName returns the DynamoDB table backing FederationRouteAggregation.
func (*FederationRouteAggregation) UpdateKeys ¶
func (f *FederationRouteAggregation) UpdateKeys()
UpdateKeys sets the primary keys for the FederationRouteAggregation model
type FederationRouteMetrics ¶
type FederationRouteMetrics struct {
// Primary keys - route metrics use FED_ROUTE#{route_id}#{date} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for time-based route queries - FED_ROUTES#{date}, ROUTE#{route_id}#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for domain-route queries - FED_DOMAIN_ROUTES#{domain}, ROUTE#{route_id}#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// GSI3 for performance queries - FED_ROUTE_PERF#{performance_tier}, LATENCY#{avg_latency}#{route_id}
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"`
// Route identification
RouteID string `theorydb:"attr:routeID" json:"route_id"` // Unique route identifier
DestinationDomain string `theorydb:"attr:destinationDomain" json:"destination_domain"` // Target domain
RouteType string `theorydb:"attr:routeType" json:"route_type"` // primary, backup, failover
RoutePriority int `theorydb:"attr:routePriority" json:"route_priority"` // Priority order (1=highest)
ServerEndpoint string `theorydb:"attr:serverEndpoint" json:"server_endpoint"` // Full endpoint URL
Protocol string `theorydb:"attr:protocol" json:"protocol"` // HTTP, HTTPS
Port int `theorydb:"attr:port" json:"port"` // Target port
// Performance metrics (aggregated for the time period)
TotalAttempts int64 `theorydb:"attr:totalAttempts" json:"total_attempts"` // Total delivery attempts
SuccessfulAttempts int64 `theorydb:"attr:successfulAttempts" json:"successful_attempts"` // Successful deliveries
FailedAttempts int64 `theorydb:"attr:failedAttempts" json:"failed_attempts"` // Failed deliveries
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"` // Success percentage
AvgLatencyMs int64 `theorydb:"attr:avgLatencyMs" json:"avg_latency_ms"` // Average response time
MedianLatencyMs int64 `theorydb:"attr:medianLatencyMs" json:"median_latency_ms"` // Median response time
P95LatencyMs int64 `theorydb:"attr:p95LatencyMs" json:"p95_latency_ms"` // 95th percentile latency
P99LatencyMs int64 `theorydb:"attr:p99LatencyMs" json:"p99_latency_ms"` // 99th percentile latency
MinLatencyMs int64 `theorydb:"attr:minLatencyMs" json:"min_latency_ms"` // Fastest response
MaxLatencyMs int64 `theorydb:"attr:maxLatencyMs" json:"max_latency_ms"` // Slowest response
TimeoutCount int64 `theorydb:"attr:timeoutCount" json:"timeout_count"` // Number of timeouts
TimeoutRate float64 `theorydb:"attr:timeoutRate" json:"timeout_rate"` // Timeout percentage
// Error tracking
ErrorBreakdown map[string]int64 `theorydb:"attr:errorBreakdown" json:"error_breakdown"` // Error code -> count
ConsecutiveFailures int64 `theorydb:"attr:consecutiveFailures" json:"consecutive_failures"` // Current failure streak
MaxConsecutiveFails int64 `theorydb:"attr:maxConsecutiveFails" json:"max_consecutive_fails"` // Longest failure streak
LastErrorCode string `theorydb:"attr:lastErrorCode" json:"last_error_code"` // Most recent error
LastErrorMessage string `theorydb:"attr:lastErrorMessage" json:"last_error_message"` // Most recent error message
LastErrorTime *time.Time `theorydb:"attr:lastErrorTime" json:"last_error_time"` // When last error occurred
RecoveryTime *time.Time `theorydb:"attr:recoveryTime" json:"recovery_time"` // When route recovered
// Cost metrics (aggregated)
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost for this route
AvgCostPerDelivery int64 `theorydb:"attr:avgCostPerDelivery" json:"avg_cost_per_delivery"` // Average cost per delivery
CostEfficiencyScore float64 `theorydb:"attr:costEfficiencyScore" json:"cost_efficiency_score"` // Cost vs. performance ratio
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Total bytes transferred
AvgPayloadSize int64 `theorydb:"attr:avgPayloadSize" json:"avg_payload_size"` // Average payload size
// Retry analysis
TotalRetries int64 `theorydb:"attr:totalRetries" json:"total_retries"` // Total retry attempts
AvgRetriesPerFail float64 `theorydb:"attr:avgRetriesPerFail" json:"avg_retries_per_fail"` // Average retries before giving up
RetrySuccessRate float64 `theorydb:"attr:retrySuccessRate" json:"retry_success_rate"` // Success rate of retries
AvgRetryDelayMs int64 `theorydb:"attr:avgRetryDelayMs" json:"avg_retry_delay_ms"` // Average delay between retries
RetryBackoffFactor float64 `theorydb:"attr:retryBackoffFactor" json:"retry_backoff_factor"` // Exponential backoff factor
// Circuit breaker state
CircuitBreakerState string `theorydb:"attr:circuitBreakerState" json:"circuit_breaker_state"` // closed, open, half_open
StateChangeTime *time.Time `theorydb:"attr:stateChangeTime" json:"state_change_time"` // When state last changed
NextRetryTime *time.Time `theorydb:"attr:nextRetryTime" json:"next_retry_time"` // When to try again if open
// Health scoring
HealthScore float64 `theorydb:"attr:healthScore" json:"health_score"` // Overall route health (0.0-1.0)
ReliabilityScore float64 `theorydb:"attr:reliabilityScore" json:"reliability_score"` // Reliability metric
PerformanceScore float64 `theorydb:"attr:performanceScore" json:"performance_score"` // Speed metric
StabilityScore float64 `theorydb:"attr:stabilityScore" json:"stability_score"` // Consistency metric
HealthHistory []float64 `theorydb:"attr:healthHistory" json:"health_history"` // Historical health scores
LastHealthCheck time.Time `theorydb:"attr:lastHealthCheck" json:"last_health_check"` // When health was last calculated
HealthTrend string `theorydb:"attr:healthTrend" json:"health_trend"` // improving, stable, degrading
// Load balancing metrics
CurrentWeight float64 `theorydb:"attr:currentWeight" json:"current_weight"` // Current load balancing weight
OptimalWeight float64 `theorydb:"attr:optimalWeight" json:"optimal_weight"` // Calculated optimal weight
WeightAdjustments int `theorydb:"attr:weightAdjustments" json:"weight_adjustments"` // Number of weight changes
LastWeightChange *time.Time `theorydb:"attr:lastWeightChange" json:"last_weight_change"` // When weight was last adjusted
LoadBalancingScore float64 `theorydb:"attr:loadBalancingScore" json:"load_balancing_score"` // Effectiveness score
// Geographic and network info
DataCenter string `theorydb:"attr:dataCenter" json:"data_center"` // Which DC the route goes through
NetworkPath string `theorydb:"attr:networkPath" json:"network_path"` // Network routing information
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address"` // Resolved IP address
ASN string `theorydb:"attr:asn" json:"asn"` // Autonomous System Number
GeographicZone string `theorydb:"attr:geographicZone" json:"geographic_zone"` // Geographic region
CDNProvider string `theorydb:"attr:cdnProvider" json:"cdn_provider"` // CDN if applicable
// Aggregation period
PeriodType string `theorydb:"attr:periodType" json:"period_type"` // hour, day, week, month
PeriodStart time.Time `theorydb:"attr:periodStart" json:"period_start"` // Start of aggregation period
PeriodEnd time.Time `theorydb:"attr:periodEnd" json:"period_end"` // End of aggregation period
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
FirstUsed time.Time `theorydb:"attr:firstUsed" json:"first_used"` // When route was first used
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"` // When route was last used
LastSuccess time.Time `theorydb:"attr:lastSuccess" json:"last_success"` // When route last succeeded
// TTL for automatic cleanup (90 days for route metrics)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationRouteMetrics represents detailed per-route federation metrics with GSI optimization
func (*FederationRouteMetrics) AddDeliveryAttempt ¶
func (f *FederationRouteMetrics) AddDeliveryAttempt(success bool, latencyMs int64, errorCode string, errorMsg string, costMicroCents int64, payloadBytes int64)
AddDeliveryAttempt records a new delivery attempt
func (*FederationRouteMetrics) AddRetryAttempt ¶
func (f *FederationRouteMetrics) AddRetryAttempt(delayMs int64)
AddRetryAttempt records a retry attempt
func (*FederationRouteMetrics) BeforeCreate ¶
func (f *FederationRouteMetrics) BeforeCreate() error
BeforeCreate is called before creating the record
func (*FederationRouteMetrics) BeforeUpdate ¶
func (f *FederationRouteMetrics) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*FederationRouteMetrics) GetOptimizationRecommendations ¶
func (f *FederationRouteMetrics) GetOptimizationRecommendations() []RouteRecommendation
GetOptimizationRecommendations provides route optimization suggestions
func (*FederationRouteMetrics) GetRouteSummary ¶
func (f *FederationRouteMetrics) GetRouteSummary() map[string]interface{}
GetRouteSummary returns a summary of route performance
func (*FederationRouteMetrics) IsHealthy ¶
func (f *FederationRouteMetrics) IsHealthy() bool
IsHealthy returns whether the route is considered healthy
func (FederationRouteMetrics) TableName ¶
func (FederationRouteMetrics) TableName() string
TableName returns the DynamoDB table backing FederationRouteMetrics.
func (*FederationRouteMetrics) UpdateKeys ¶
func (f *FederationRouteMetrics) UpdateKeys()
UpdateKeys sets the primary keys for the FederationRouteMetrics model
type FederationSeverance ¶
type FederationSeverance struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Domain string `theorydb:"attr:domain" json:"domain"`
SeveredAt time.Time `theorydb:"attr:severedAt" json:"severed_at"`
Acknowledged bool `theorydb:"attr:acknowledged" json:"acknowledged"`
Reason string `theorydb:"attr:reason" json:"reason"`
Type string `theorydb:"attr:type" json:"type"` // "domain_block", "suspension", "defederation"
// contains filtered or unexported fields
}
FederationSeverance represents a severed federation relationship
func (FederationSeverance) TableName ¶
func (FederationSeverance) TableName() string
TableName returns the DynamoDB table backing FederationSeverance.
func (*FederationSeverance) UpdateKeys ¶
func (f *FederationSeverance) UpdateKeys()
UpdateKeys updates the GSI keys for federation severance
type FederationStats ¶
type FederationStats struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // FEDERATION#STATS
SK string `theorydb:"sk,attr:SK" json:"-"` // {date} (e.g., 2024-01-30)
// Attributes from interface
ActiveInstances int `theorydb:"attr:activeInstances" json:"active_instances"`
TotalMessages int64 `theorydb:"attr:totalMessages" json:"total_messages"`
TotalUsers int `theorydb:"attr:totalUsers" json:"total_users"`
// Additional metadata
Date string `theorydb:"attr:date" json:"date"` // The date these stats are for
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update time
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 90 days retention
// contains filtered or unexported fields
}
FederationStats represents federation activity statistics
func NewFederationStats ¶
func NewFederationStats(date string) *FederationStats
NewFederationStats creates a new FederationStats for a given date
func (*FederationStats) IncrementStats ¶
func (f *FederationStats) IncrementStats(activeInstances int, messages int64, users int)
IncrementStats adds values to the current stats
func (FederationStats) TableName ¶
func (FederationStats) TableName() string
TableName returns the DynamoDB table backing FederationStats.
func (*FederationStats) UpdateKeys ¶
func (f *FederationStats) UpdateKeys()
UpdateKeys updates the partition and sort keys based on the date
type FederationTier ¶
type FederationTier string
FederationTier represents the tier level for federation
const ( // FederationTierFree represents the free federation tier FederationTierFree FederationTier = "free" // FederationTierBasic represents the basic federation tier FederationTierBasic FederationTier = "basic" // FederationTierPremium represents the premium federation tier FederationTierPremium FederationTier = "premium" // FederationTierEnterprise represents the enterprise federation tier FederationTierEnterprise FederationTier = "enterprise" // FederationTierBlocked represents a blocked federation tier FederationTierBlocked FederationTier = "blocked" )
type FederationTimeSeries ¶
type FederationTimeSeries struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // "hourly", "daily", "weekly"
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Metrics map[string]interface{} `theorydb:"attr:metrics" json:"metrics"`
ActivityVolume int64 `theorydb:"attr:activityVolume" json:"activity_volume"`
ErrorCount int64 `theorydb:"attr:errorCount" json:"error_count"`
SuccessCount int64 `theorydb:"attr:successCount" json:"success_count"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationTimeSeries stores time-series federation metrics
func (FederationTimeSeries) TableName ¶
func (FederationTimeSeries) TableName() string
TableName returns the DynamoDB table backing FederationTimeSeries.
func (*FederationTimeSeries) UpdateKeys ¶
func (f *FederationTimeSeries) UpdateKeys()
UpdateKeys updates the GSI keys for federation time series
type FederationTimeseriesWindow ¶ added in v1.2.53
type FederationTimeseriesWindow struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Type string `theorydb:"attr:type" json:"type"`
Window string `theorydb:"attr:window" json:"window"`
FollowCount int `theorydb:"attr:followCount" json:"follow_count"`
LikeCount int `theorydb:"attr:likeCount" json:"like_count"`
AnnounceCount int `theorydb:"attr:announceCount" json:"announce_count"`
ActivityCount int `theorydb:"attr:activityCount" json:"activity_count"`
UniqueActorCount int `theorydb:"attr:uniqueActorCount" json:"unique_actor_count"`
UniqueInstanceCount int `theorydb:"attr:uniqueInstanceCount" json:"unique_instance_count"`
CreatedAt string `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt string `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
FederationTimeseriesWindow stores aggregated federation stream metrics for a time window.
func NewFederationTimeseriesWindow ¶ added in v1.2.53
func NewFederationTimeseriesWindow(window, now time.Time) *FederationTimeseriesWindow
NewFederationTimeseriesWindow builds the key envelope for a federation metrics window.
func (FederationTimeseriesWindow) TableName ¶ added in v1.2.53
func (FederationTimeseriesWindow) TableName() string
TableName returns the DynamoDB table backing FederationTimeseriesWindow.
type FieldVerification ¶
type FieldVerification struct {
// Primary key components
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "USER#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "FIELD_VERIFICATION#{field_name}"
// Field verification data
Username string `theorydb:"attr:username" json:"username"` // Who owns the field
FieldName string `theorydb:"attr:fieldName" json:"field_name"` // Field name (e.g., "website", "github")
FieldValue string `theorydb:"attr:fieldValue" json:"field_value"` // Field value
VerifiedAt time.Time `theorydb:"attr:verifiedAt" json:"verified_at"` // When verified
VerifiedBy string `theorydb:"attr:verifiedBy" json:"verified_by"` // How verified (e.g., "link", "dns", "manual")
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"` // When verification expires
// contains filtered or unexported fields
}
FieldVerification represents a verified field on a user's profile Key pattern: PK=USER#{username}, SK=FIELD_VERIFICATION#{field_name}
func (*FieldVerification) BeforeCreate ¶
func (f *FieldVerification) BeforeCreate() error
BeforeCreate prepares the FieldVerification for creation
func (*FieldVerification) IsExpired ¶
func (f *FieldVerification) IsExpired() bool
IsExpired checks if the field verification has expired
func (FieldVerification) TableName ¶
func (FieldVerification) TableName() string
TableName returns the DynamoDB table name
func (*FieldVerification) UpdateKeys ¶
func (f *FieldVerification) UpdateKeys()
UpdateKeys updates the primary key fields based on the current data
type Filter ¶
type Filter struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // USER#username
SK string `theorydb:"sk,attr:SK"` // FILTER#filterID
// GSI for lookup by filter ID without knowing username
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // FILTER#{filterID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // USER#{username}
// Filter fields
ID string `theorydb:"attr:id" json:"id"` // Unique filter ID
Username string `theorydb:"attr:username" json:"username"` // Owner of the filter
Title string `theorydb:"attr:title" json:"title"` // Human-readable title
Context []string `theorydb:"attr:context" json:"context"` // Where to apply: home, notifications, public, thread, account
FilterAction string `theorydb:"attr:filterAction" json:"filter_action"` // Action to take: warn, hide, blur, silence, limit_reach
Severity string `theorydb:"attr:severity" json:"severity"` // Filter severity: low, medium, high
MatchMode string `theorydb:"attr:matchMode" json:"match_mode"` // Matching mode: keyword, regex, semantic, exact
CaseSensitive bool `theorydb:"attr:caseSensitive" json:"case_sensitive"` // Case-sensitive matching
ExpiresAt *time.Time `theorydb:"attr:expiresAt" json:"expires_at"` // Optional expiration
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // Creation timestamp
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update timestamp
// contains filtered or unexported fields
}
Filter represents a user's content filter with DynamORM tags
func (*Filter) BeforeCreate ¶
BeforeCreate hook to set timestamps and update keys
func (*Filter) BeforeSave ¶
BeforeSave hook to update timestamps and keys
func (*Filter) UpdateKeys ¶
UpdateKeys updates the DynamORM keys based on filter data
type FilterKeyword ¶
type FilterKeyword struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // FILTER#filterID
SK string `theorydb:"sk,attr:SK"` // KEYWORD#keywordID
// Keyword fields
ID string `theorydb:"attr:id" json:"id"` // Unique keyword ID
FilterID string `theorydb:"attr:filterID" json:"filter_id"` // Parent filter ID
Keyword string `theorydb:"attr:keyword" json:"keyword"` // The keyword to filter
WholeWord bool `theorydb:"attr:wholeWord" json:"whole_word"` // Match whole word only
IsRegex bool `theorydb:"attr:isRegex" json:"is_regex"` // Whether keyword is a regex pattern
MatchWeight float64 `theorydb:"attr:matchWeight" json:"match_weight"` // Weight for scoring matches (0.0-1.0)
ContextTypes []string `theorydb:"attr:contextTypes" json:"context_types"` // Specific contexts where this keyword applies
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // Creation timestamp
// contains filtered or unexported fields
}
FilterKeyword represents a keyword in a filter with DynamORM tags
func (*FilterKeyword) BeforeCreate ¶
func (fk *FilterKeyword) BeforeCreate() error
BeforeCreate hook to set timestamps and update keys
func (*FilterKeyword) BeforeSave ¶
func (fk *FilterKeyword) BeforeSave() error
BeforeSave hook to update keys
func (*FilterKeyword) GetPK ¶
func (fk *FilterKeyword) GetPK() string
GetPK returns the partition key
func (FilterKeyword) TableName ¶
func (FilterKeyword) TableName() string
TableName returns the DynamoDB table name
func (*FilterKeyword) UpdateKeys ¶
func (fk *FilterKeyword) UpdateKeys() error
UpdateKeys updates the DynamORM keys based on keyword data
type FilterStatus ¶
type FilterStatus struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // FILTER#filterID
SK string `theorydb:"sk,attr:SK"` // STATUS#statusID
// Status fields
ID string `theorydb:"attr:id" json:"id"` // Unique filter status ID
FilterID string `theorydb:"attr:filterID" json:"filter_id"` // Parent filter ID
StatusID string `theorydb:"attr:statusID" json:"status_id"` // The status ID to filter
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // Creation timestamp
// contains filtered or unexported fields
}
FilterStatus represents a status in a filter with DynamORM tags
func (*FilterStatus) BeforeCreate ¶
func (fs *FilterStatus) BeforeCreate() error
BeforeCreate hook to set timestamps and update keys
func (*FilterStatus) BeforeSave ¶
func (fs *FilterStatus) BeforeSave() error
BeforeSave hook to update keys
func (FilterStatus) TableName ¶
func (FilterStatus) TableName() string
TableName returns the DynamoDB table name
func (*FilterStatus) UpdateKeys ¶
func (fs *FilterStatus) UpdateKeys() error
UpdateKeys updates the DynamORM keys based on status data
type Flag ¶
type Flag struct {
// Keys
PK string `theorydb:"pk,attr:PK"` // FLAG#objectID (first object if multiple)
SK string `theorydb:"sk,attr:SK"` // TIME#timestamp#flagID
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // ACTOR#actorID
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // FLAG#timestamp
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"` // FLAG_STATUS#status
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"` // TIME#timestamp
// Flag fields
ID string `theorydb:"attr:id" json:"id"` // The flag activity ID
Actor string `theorydb:"attr:actor" json:"actor"` // Who flagged
Object []string `theorydb:"attr:object" json:"object"` // What was flagged (can be multiple objects)
Content string `theorydb:"attr:content" json:"content"` // Reason/description for the flag
Published time.Time `theorydb:"attr:published" json:"published"` // When it was flagged
Status string `theorydb:"attr:status" json:"status"` // Current status of the flag (pending, reviewed, resolved, dismissed)
ReviewedBy string `theorydb:"attr:reviewedBy" json:"reviewed_by"` // Moderator who reviewed (if reviewed)
ReviewedAt *time.Time `theorydb:"attr:reviewedAt" json:"reviewed_at"` // When it was reviewed
ReviewNote string `theorydb:"attr:reviewNote" json:"review_note"` // Note from reviewer
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // Database timestamp
// contains filtered or unexported fields
}
Flag represents a content moderation flag with DynamORM tags
func (*Flag) BeforeCreate ¶
BeforeCreate hook to set timestamps and update keys
func (*Flag) UpdateKeys ¶
func (f *Flag) UpdateKeys()
UpdateKeys updates the DynamORM keys based on flag data
type Follow ¶
type Follow struct {
// Primary key - follower's perspective
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "follow#{follower_username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "following#{followed_username}"
// GSI1 - followed's perspective (for listing followers)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "follow#{followed_username}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "follower#{follower_username}"
// GSI2 - by state and timestamp (for pending follows)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "follow#state#{state}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{follower}#{followed}"
// Relationship data
FollowerUsername string `theorydb:"attr:followerUsername" json:"follower_username"`
FollowedUsername string `theorydb:"attr:followedUsername" json:"followed_username"`
ActivityID string `theorydb:"attr:activityID" json:"activity_id"` // The Follow activity ID
State string `theorydb:"attr:state" json:"state"` // "pending", "accepted", "rejected"
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
AcceptedAt *time.Time `theorydb:"attr:acceptedAt" json:"accepted_at,omitempty"`
// contains filtered or unexported fields
}
Follow represents a follow relationship between actors
type FollowRequestState ¶
type FollowRequestState struct {
// Primary key components
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "FOLLOW_REQUEST#{requester_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TARGET#{target_id}"
// Follow request data
RequesterID string `theorydb:"attr:requesterID" json:"requester_id"` // Who made the request
TargetID string `theorydb:"attr:targetID" json:"target_id"` // Who the request is for
State string `theorydb:"attr:state" json:"state"` // pending, accepted, rejected
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
FollowRequestState represents a follow request state Key pattern: PK=FOLLOW_REQUEST#{requester_id}, SK=TARGET#{target_id}
func (*FollowRequestState) BeforeCreate ¶
func (f *FollowRequestState) BeforeCreate() error
BeforeCreate prepares the FollowRequestState for creation
func (FollowRequestState) TableName ¶
func (FollowRequestState) TableName() string
TableName returns the DynamoDB table name
func (*FollowRequestState) UpdateKeys ¶
func (f *FollowRequestState) UpdateKeys()
UpdateKeys updates the primary key fields based on the current data
type GeographicMetric ¶
type GeographicMetric struct {
Region string `json:"region"` // US, EU, AS, etc.
ViewerCount int64 `json:"viewer_count"` // Viewers in this region
ViewerPercentage float64 `json:"viewer_percentage"` // Percentage of total viewers
AverageLatencyMs int64 `json:"average_latency_ms"` // CDN latency for this region
PreferredQuality string `json:"preferred_quality"` // Most popular quality in this region
CacheHitRate float64 `json:"cache_hit_rate"` // CDN cache performance
BandwidthUsageMbps float64 `json:"bandwidth_usage_mbps"` // Average bandwidth usage
}
GeographicMetric represents metrics for a specific geographic region
func (GeographicMetric) TableName ¶
func (GeographicMetric) TableName() string
TableName returns the DynamoDB table backing GeographicMetric.
type GlobalMetricsWindow ¶
type GlobalMetricsWindow struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // METRICS#GLOBAL#SUMMARY
SK string `theorydb:"sk,attr:SK" json:"sk"` // WINDOW#{windowStartUnix}
// GSI keys for time-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // METRICS#GLOBAL
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {windowStartUnix}
// Time info
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowSize int64 `theorydb:"attr:windowSizeMinutes" json:"window_size_minutes"`
// Aggregated metrics
TotalMessages int64 `theorydb:"attr:totalMessages" json:"total_messages"`
TotalBytes int64 `theorydb:"attr:totalBytes" json:"total_bytes"`
TotalCost float64 `theorydb:"attr:totalCost" json:"total_cost"`
UniqueInstances int64 `theorydb:"attr:uniqueInstances" json:"unique_instances"`
ActiveRoutes int64 `theorydb:"attr:activeRoutes" json:"active_routes"`
// Hourly volume (JSON-encoded [24]int64)
HourlyVolume string `theorydb:"attr:hourlyVolume" json:"hourly_volume,omitempty"`
// Top/bottom performers (JSON-encoded)
TopRoutes string `theorydb:"attr:topRoutes" json:"top_routes,omitempty"`
BottomRoutes string `theorydb:"attr:bottomRoutes" json:"bottom_routes,omitempty"`
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
GlobalMetricsWindow represents aggregated global metrics for a time window
func (*GlobalMetricsWindow) GetPK ¶
func (g *GlobalMetricsWindow) GetPK() string
GetPK returns the partition key
func (*GlobalMetricsWindow) GetSK ¶
func (g *GlobalMetricsWindow) GetSK() string
GetSK returns the sort key
func (GlobalMetricsWindow) TableName ¶
func (GlobalMetricsWindow) TableName() string
TableName returns the DynamoDB table backing GlobalMetricsWindow.
func (*GlobalMetricsWindow) UpdateKeys ¶
func (g *GlobalMetricsWindow) UpdateKeys() error
UpdateKeys updates the GSI keys based on the current data
type GraphQLStreamSubscription ¶ added in v0.1.36
type GraphQLStreamSubscription struct {
// Primary key - stream-based partitioning
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: GQLSUB#<stream>
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: CONN#<connectionID>#SUB#<subscriptionID>
// GSI1 - Query by connection to support cleanup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // Format: CONN#<connectionID>
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // Format: SUB#<subscriptionID>#STREAM#<stream>
// Business fields
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"`
SubscriptionID string `theorydb:"attr:subscriptionID" json:"subscription_id"`
Stream string `theorydb:"attr:stream" json:"stream"`
Field string `theorydb:"attr:field" json:"field"`
UserID string `theorydb:"attr:userID" json:"user_id"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
GraphQLStreamSubscription represents a GraphQL WebSocket subscription tied to a stream.
func (*GraphQLStreamSubscription) GetPK ¶ added in v0.1.36
func (g *GraphQLStreamSubscription) GetPK() string
GetPK returns the partition key (required for BaseModel).
func (*GraphQLStreamSubscription) GetSK ¶ added in v0.1.36
func (g *GraphQLStreamSubscription) GetSK() string
GetSK returns the sort key (required for BaseModel).
func (GraphQLStreamSubscription) TableName ¶ added in v0.1.36
func (GraphQLStreamSubscription) TableName() string
TableName returns the DynamoDB table backing GraphQLStreamSubscription.
func (*GraphQLStreamSubscription) UpdateKeys ¶ added in v0.1.36
func (g *GraphQLStreamSubscription) UpdateKeys() error
UpdateKeys sets PK/SK and GSI keys/state for the subscription record.
type Hashtag ¶
type Hashtag struct {
// Primary key - hashtag metadata
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "HASHTAG#{hashtag_name}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "METADATA"
// GSI3 - Hashtag search by prefix
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "HASHTAG_SEARCH#{first_2_chars}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{hashtag_name}"
// Core hashtag data
Name string `theorydb:"attr:name" json:"name"` // Hashtag name (lowercase, no #)
URL string `theorydb:"attr:url" json:"url"` // Public URL for the hashtag
UsageCount int64 `theorydb:"attr:usageCount" json:"usage_count"` // Total number of times used
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"` // When first seen
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"` // When last used
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last metadata update
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
Hashtag represents hashtag metadata stored in DynamoDB using DynamORM
func (*Hashtag) UpdateKeys ¶
UpdateKeys updates the GSI keys when the hashtag data changes
type HashtagFollow ¶
type HashtagFollow struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // user#{userID}
SK string `theorydb:"sk,attr:SK" json:"-"` // hashtag#{name}
// Fields
UserID string `theorydb:"attr:userID" json:"user_id"`
Hashtag string `theorydb:"attr:hashtag" json:"hashtag"`
NotificationsEnabled bool `theorydb:"attr:notificationsEnabled" json:"notifications_enabled"`
Muted bool `theorydb:"attr:muted" json:"muted"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
HashtagFollow represents a user following a hashtag
func (*HashtagFollow) GetPK ¶
func (h *HashtagFollow) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*HashtagFollow) GetSK ¶
func (h *HashtagFollow) GetSK() string
GetSK returns the sort key for BaseModel interface
func (HashtagFollow) TableName ¶
func (HashtagFollow) TableName() string
TableName returns the DynamoDB table backing HashtagFollow.
func (*HashtagFollow) UpdateKeys ¶
func (h *HashtagFollow) UpdateKeys() error
UpdateKeys implements BaseModel interface - updates keys without parameters
func (*HashtagFollow) UpdateKeysWithParams ¶
func (h *HashtagFollow) UpdateKeysWithParams(userID, hashtag string)
UpdateKeysWithParams updates the primary and sort keys for DynamoDB
type HashtagHistoryEntry ¶
type HashtagHistoryEntry struct {
Date time.Time `json:"date"`
UsageCount int64 `json:"usage_count"`
UserCount int64 `json:"user_count"`
}
HashtagHistoryEntry represents a historical data point for hashtag usage This is typically embedded in HashtagStats, not stored separately
func NewHashtagHistoryEntry ¶
func NewHashtagHistoryEntry(date time.Time, usageCount, userCount int64) HashtagHistoryEntry
NewHashtagHistoryEntry creates a new history entry
func (HashtagHistoryEntry) CompareWith ¶
func (h HashtagHistoryEntry) CompareWith(other HashtagHistoryEntry) float64
CompareWith compares this entry with another and returns the percentage change
func (HashtagHistoryEntry) DaysSince ¶
func (h HashtagHistoryEntry) DaysSince() int
DaysSince returns the number of days since this entry
func (HashtagHistoryEntry) GetEngagement ¶
func (h HashtagHistoryEntry) GetEngagement() float64
GetEngagement calculates a simple engagement metric
func (HashtagHistoryEntry) IsHighActivity ¶
func (h HashtagHistoryEntry) IsHighActivity(threshold int64) bool
IsHighActivity returns true if usage exceeds the threshold
func (HashtagHistoryEntry) TableName ¶
func (HashtagHistoryEntry) TableName() string
TableName returns the DynamoDB table backing HashtagHistoryEntry.
type HashtagMute ¶
type HashtagMute struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // user#{userID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // mute#{name}
Username string `theorydb:"attr:username" json:"username"`
Hashtag string `theorydb:"attr:hashtag" json:"hashtag"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // Optional expiration
// contains filtered or unexported fields
}
HashtagMute represents a user muting a hashtag
func (HashtagMute) TableName ¶
func (HashtagMute) TableName() string
TableName returns the DynamoDB table backing HashtagMute.
func (*HashtagMute) UpdateKeys ¶
func (h *HashtagMute) UpdateKeys()
UpdateKeys updates the PK/SK for a hashtag mute
type HashtagNotificationSettings ¶
type HashtagNotificationSettings struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // user#{userID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // settings#{name}
UserID string `theorydb:"attr:userID" json:"user_id"`
Hashtag string `theorydb:"attr:hashtag" json:"hashtag"`
Level string `theorydb:"attr:level" json:"level"`
Muted bool `theorydb:"attr:muted" json:"muted"`
MutedUntil *time.Time `theorydb:"attr:mutedUntil" json:"muted_until,omitempty"`
Filters []NotificationFilter `theorydb:"attr:filters" json:"filters,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
HashtagNotificationSettings stores per-hashtag notification preferences for a user.
func (*HashtagNotificationSettings) GetPK ¶
func (h *HashtagNotificationSettings) GetPK() string
GetPK returns the partition key for the BaseModel interface.
func (*HashtagNotificationSettings) GetSK ¶
func (h *HashtagNotificationSettings) GetSK() string
GetSK returns the sort key for the BaseModel interface.
func (HashtagNotificationSettings) TableName ¶
func (HashtagNotificationSettings) TableName() string
TableName returns the DynamoDB table backing HashtagNotificationSettings.
func (*HashtagNotificationSettings) UpdateKeys ¶
func (h *HashtagNotificationSettings) UpdateKeys() error
UpdateKeys implements the BaseModel interface.
func (*HashtagNotificationSettings) UpdateKeysWithParams ¶
func (h *HashtagNotificationSettings) UpdateKeysWithParams(userID, hashtag string)
UpdateKeysWithParams ensures composite keys are populated.
type HashtagSearchCache ¶
type HashtagSearchCache struct {
// Primary key - search cache
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "HASHTAG_SEARCH_CACHE#{query_hash}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "CACHE#{params_hash}"
// GSI1 - Cleanup by creation time
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "SEARCH_CACHE"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "CREATED#{timestamp}"
// Cache data
Query string `theorydb:"attr:query" json:"query"`
Parameters map[string]interface{} `theorydb:"attr:parameters" json:"parameters"`
Results []string `theorydb:"attr:results" json:"results"` // Hashtag names
TotalResults int `theorydb:"attr:totalResults" json:"total_results"` // Total available
NextCursor string `theorydb:"attr:nextCursor" json:"next_cursor,omitempty"`
HitCount int64 `theorydb:"attr:hitCount" json:"hit_count"` // Number of times used
LastAccessed time.Time `theorydb:"attr:lastAccessed" json:"last_accessed"`
// TTL for automatic cleanup (2 hours for hashtag search cache)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
HashtagSearchCache represents a cache for hashtag search results to improve performance
func (HashtagSearchCache) TableName ¶
func (HashtagSearchCache) TableName() string
TableName ensures hashtag search cache items share the main table.
func (*HashtagSearchCache) UpdateKeys ¶
func (hsc *HashtagSearchCache) UpdateKeys()
UpdateKeys updates all the GSI keys when the cache data changes
type HashtagSearchResult ¶
type HashtagSearchResult struct {
Name string `json:"name"`
URL string `json:"url"`
History []*TrendingHashtag `json:"history"`
Following *bool `json:"following,omitempty"`
}
HashtagSearchResult represents a hashtag search result This is a response type used for search results, not stored in DynamoDB
func NewHashtagSearchResult ¶
func NewHashtagSearchResult(name, url string) *HashtagSearchResult
NewHashtagSearchResult creates a new hashtag search result
func (*HashtagSearchResult) AddHistory ¶
func (h *HashtagSearchResult) AddHistory(trend *TrendingHashtag)
AddHistory adds a trending history entry
func (*HashtagSearchResult) GetLatestUsage ¶
func (h *HashtagSearchResult) GetLatestUsage() int64
GetLatestUsage returns the most recent usage count, or 0 if no history
func (*HashtagSearchResult) GetTotalUsage ¶
func (h *HashtagSearchResult) GetTotalUsage() int64
GetTotalUsage returns the sum of all usage counts in history
func (*HashtagSearchResult) HasRecentActivity ¶
func (h *HashtagSearchResult) HasRecentActivity() bool
HasRecentActivity returns true if the hashtag has been used in the last 24 hours
func (*HashtagSearchResult) IsFollowing ¶
func (h *HashtagSearchResult) IsFollowing() bool
IsFollowing returns whether the user is following this hashtag
func (*HashtagSearchResult) SetFollowing ¶
func (h *HashtagSearchResult) SetFollowing(following bool)
SetFollowing sets whether the user is following this hashtag
func (HashtagSearchResult) TableName ¶
func (HashtagSearchResult) TableName() string
TableName returns the DynamoDB table backing HashtagSearchResult.
type HashtagStats ¶
type HashtagStats struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Name string `theorydb:"attr:name" json:"name"`
UsageCount int64 `theorydb:"attr:usageCount" json:"usage_count"`
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users"`
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"`
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"`
TrendingScore float64 `theorydb:"attr:trendingScore" json:"trending_score"`
TotalUses int64 `theorydb:"attr:totalUses" json:"total_uses"` // Total usage count
TotalAccounts int64 `theorydb:"attr:totalAccounts" json:"total_accounts"` // Total unique accounts
History []HashtagHistoryEntry `theorydb:"attr:history" json:"history"` // Historical data
// contains filtered or unexported fields
}
HashtagStats represents statistics for a hashtag Stored in DynamoDB with pattern: PK: HASHTAG#name SK: STATS
func NewHashtagStats ¶
func NewHashtagStats(name string) *HashtagStats
NewHashtagStats creates a new hashtag stats entry
func (*HashtagStats) AddHistoryEntry ¶
func (h *HashtagStats) AddHistoryEntry(date time.Time, usageCount, userCount int64)
AddHistoryEntry adds a new history entry for tracking trends
func (*HashtagStats) AddUniqueUser ¶
func (h *HashtagStats) AddUniqueUser()
AddUniqueUser increments the unique user count
func (*HashtagStats) GetAverageUsage ¶
func (h *HashtagStats) GetAverageUsage() float64
GetAverageUsage calculates the average usage over the history period
func (*HashtagStats) GetGrowthRate ¶
func (h *HashtagStats) GetGrowthRate() float64
GetGrowthRate calculates the growth rate between first and last history entries
func (*HashtagStats) IncrementUsage ¶
func (h *HashtagStats) IncrementUsage()
IncrementUsage increments the usage count and updates last used time
func (*HashtagStats) IsActive ¶
func (h *HashtagStats) IsActive() bool
IsActive returns true if the hashtag has been used in the last 7 days
func (*HashtagStats) IsTrending ¶
func (h *HashtagStats) IsTrending(threshold float64) bool
IsTrending returns true if the trending score is above a threshold
func (HashtagStats) TableName ¶
func (HashtagStats) TableName() string
TableName returns the DynamoDB table backing HashtagStats.
func (*HashtagStats) UpdateKeys ¶
func (h *HashtagStats) UpdateKeys()
UpdateKeys updates the DynamoDB keys based on the hashtag name
func (*HashtagStats) UpdateTrendingScore ¶
func (h *HashtagStats) UpdateTrendingScore()
UpdateTrendingScore updates the trending score based on recent activity
type HashtagStatusIndex ¶
type HashtagStatusIndex struct {
// Primary key - hashtag timeline
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "HASHTAG_TIMELINE#{hashtag_name}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "STATUS#{timestamp_desc}#{status_id}"
// GSI1 - Status-to-hashtag reverse index for cleanup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "STATUS_HASHTAGS#{status_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "HASHTAG#{hashtag_name}"
// GSI2 - Timeline by visibility for filtering
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "HASHTAG_VIS#{hashtag_name}#{visibility}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "TIMELINE#{timestamp_desc}"
// Status data
StatusID string `theorydb:"attr:statusID" json:"status_id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
AuthorHandle string `theorydb:"attr:authorHandle" json:"author_handle"`
StatusURL string `theorydb:"attr:statusURL" json:"status_url,omitempty"`
Content string `theorydb:"attr:content" json:"content,omitempty"` // Excerpt for search results
MediaCount int `theorydb:"attr:mediaCount" json:"media_count,omitempty"` // Number of media attachments
Language string `theorydb:"attr:language" json:"language,omitempty"` // Content language
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Published time.Time `theorydb:"attr:published" json:"published"` // When the status was published
HashtagName string `theorydb:"attr:hashtagName" json:"hashtag_name"` // The hashtag (for reverse index)
// TTL for automatic cleanup (90 days for efficient hashtag timelines)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
HashtagStatusIndex represents an efficient index for hashtag-to-status mapping This enables fast hashtag timeline queries without scanning all statuses
func (*HashtagStatusIndex) GetPK ¶
func (hsi *HashtagStatusIndex) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*HashtagStatusIndex) GetSK ¶
func (hsi *HashtagStatusIndex) GetSK() string
GetSK returns the sort key for BaseModel interface
func (HashtagStatusIndex) TableName ¶
func (HashtagStatusIndex) TableName() string
TableName ensures HashtagStatusIndex records persist in the shared Dynamo table.
func (*HashtagStatusIndex) UpdateKeys ¶
func (hsi *HashtagStatusIndex) UpdateKeys() error
UpdateKeys updates all the GSI keys when the index data changes
type HashtagTrend ¶
type HashtagTrend struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"`
Name string `theorydb:"attr:name" json:"name"`
URL string `theorydb:"attr:url" json:"url"`
UsageCount int64 `theorydb:"attr:usageCount" json:"usage_count"`
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users"`
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"`
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"`
TrendScore float64 `theorydb:"attr:trendScore" json:"trend_score"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
HashtagTrend represents a trending hashtag
func (*HashtagTrend) GetPK ¶
func (h *HashtagTrend) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*HashtagTrend) GetSK ¶
func (h *HashtagTrend) GetSK() string
GetSK returns the sort key for BaseModel interface
func (HashtagTrend) TableName ¶
func (HashtagTrend) TableName() string
TableName returns the DynamoDB table backing HashtagTrend.
func (*HashtagTrend) UpdateKeys ¶
func (h *HashtagTrend) UpdateKeys() error
UpdateKeys updates the GSI keys for hashtag trend
type HashtagTrendingData ¶
type HashtagTrendingData struct {
// Primary key - trending hashtag data
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "TRENDING_HASHTAG#{date}#{hour}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "HASHTAG#{score_padded}#{hashtag_name}"
// GSI1 - Query by hashtag across time periods
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "HASHTAG_TREND#{hashtag_name}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "TIME#{timestamp}"
// GSI2 - Query trending for time period
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "TRENDING_PERIOD#{time_window}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "SCORE#{score_padded}#{hashtag_name}"
// Hashtag info
HashtagName string `theorydb:"attr:hashtagName" json:"hashtag_name"`
URL string `theorydb:"attr:url" json:"url"`
Period time.Time `theorydb:"attr:period" json:"period"` // Start of the time period
TimeWindow string `theorydb:"attr:timeWindow" json:"time_window"` // "1h", "6h", "24h", "7d"
// Trending metrics
TrendScore float64 `theorydb:"attr:trendScore" json:"trend_score"` // Overall trending score
UsageCount int64 `theorydb:"attr:usageCount" json:"usage_count"` // Usage count in period
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users"` // Unique users in period
Growth float64 `theorydb:"attr:growth" json:"growth"` // Growth rate vs previous period
Velocity float64 `theorydb:"attr:velocity" json:"velocity"` // Usage per hour
MomentumScore float64 `theorydb:"attr:momentumScore" json:"momentum_score"` // Acceleration indicator
TrustScore float64 `theorydb:"attr:trustScore" json:"trust_score"` // Trust-weighted score
EngagementRate float64 `theorydb:"attr:engagementRate" json:"engagement_rate"` // Engagement per usage
DiversityScore float64 `theorydb:"attr:diversityScore" json:"diversity_score"` // User diversity score
// Component scores for analysis
ComponentScores map[string]float64 `theorydb:"attr:componentScores" json:"component_scores,omitempty"`
// TTL for automatic cleanup (30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
HashtagTrendingData represents trending data for hashtags with time-windowed metrics
func (HashtagTrendingData) TableName ¶
func (HashtagTrendingData) TableName() string
TableName ensures trending data records use the shared single table.
func (*HashtagTrendingData) UpdateKeys ¶
func (htd *HashtagTrendingData) UpdateKeys()
UpdateKeys updates all the GSI keys when the trending data changes
type HashtagUsage ¶
type HashtagUsage struct {
// Primary key - hashtag usage
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "HASHTAG#{hashtag_name}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "USAGE#{timestamp}#{status_id}"
// Usage data
StatusID string `theorydb:"attr:statusID" json:"status_id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
UsedAt time.Time `theorydb:"attr:usedAt" json:"used_at"`
Visibility string `theorydb:"attr:visibility" json:"visibility"`
// TTL for automatic cleanup (30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
HashtagUsage represents a single usage of a hashtag stored in DynamoDB using DynamORM
func (*HashtagUsage) GetPK ¶
func (hu *HashtagUsage) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*HashtagUsage) GetSK ¶
func (hu *HashtagUsage) GetSK() string
GetSK returns the sort key for BaseModel interface
func (HashtagUsage) TableName ¶
func (HashtagUsage) TableName() string
TableName ensures hashtag usage records live in the shared single-table schema.
func (*HashtagUsage) UpdateKeys ¶
func (hu *HashtagUsage) UpdateKeys() error
UpdateKeys implements BaseModel interface - updates keys without parameters
func (*HashtagUsage) UpdateKeysWithHashtag ¶
func (hu *HashtagUsage) UpdateKeysWithHashtag(hashtag string)
UpdateKeysWithHashtag updates the keys when the usage data changes (parameterized version)
type HealthCheckResult ¶
type HealthCheckResult struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // HEALTH_CHECK#timestamp
SK string `theorydb:"sk,attr:SK" json:"sk"` // RESULT#component_type#identifier
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // COMPONENT#component_type#identifier
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // timestamp
Component string `theorydb:"attr:component" json:"component"` // component identifier
ComponentType string `theorydb:"attr:componentType" json:"component_type"` // "dynamodb", "lambda", "sqs"
Status string `theorydb:"attr:status" json:"status"` // "healthy", "warning", "critical", "unknown"
CheckTime time.Time `theorydb:"attr:checkTime" json:"check_time"`
LatencyMs int64 `theorydb:"attr:latencyMs" json:"latency_ms"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
RequestID string `theorydb:"attr:requestID" json:"request_id"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Auto-expire after 30 days
// contains filtered or unexported fields
}
HealthCheckResult represents a stored health check result in DynamoDB
func NewHealthCheckResult ¶
func NewHealthCheckResult(componentType, component, status, requestID string, checkTime time.Time, latencyMs int64) *HealthCheckResult
NewHealthCheckResult creates a new health check result
func (HealthCheckResult) TableName ¶
func (HealthCheckResult) TableName() string
TableName returns the DynamoDB table backing HealthCheckResult.
func (*HealthCheckResult) UpdateKeys ¶
func (h *HealthCheckResult) UpdateKeys()
UpdateKeys updates the partition and sort keys for the health check result
type HealthCheckSummaryResult ¶
type HealthCheckSummaryResult struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // HEALTH_SUMMARY#date
SK string `theorydb:"sk,attr:SK" json:"sk"` // SUMMARY#hour
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // DATE#date
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // HOUR#hour
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD
Hour int `theorydb:"attr:hour" json:"hour"` // 0-23
TotalChecks int `theorydb:"attr:totalChecks" json:"total_checks"`
HealthyChecks int `theorydb:"attr:healthyChecks" json:"healthy_checks"`
WarningChecks int `theorydb:"attr:warningChecks" json:"warning_checks"`
CriticalChecks int `theorydb:"attr:criticalChecks" json:"critical_checks"`
UnknownChecks int `theorydb:"attr:unknownChecks" json:"unknown_checks"`
AvgLatencyMs float64 `theorydb:"attr:avgLatencyMs" json:"avg_latency_ms"`
MaxLatencyMs int64 `theorydb:"attr:maxLatencyMs" json:"max_latency_ms"`
MinLatencyMs int64 `theorydb:"attr:minLatencyMs" json:"min_latency_ms"`
LastUpdated time.Time `theorydb:"attr:lastUpdated" json:"last_updated"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Auto-expire after 90 days
// contains filtered or unexported fields
}
HealthCheckSummaryResult represents aggregated health check data
func NewHealthCheckSummaryResult ¶
func NewHealthCheckSummaryResult(date string, hour int) *HealthCheckSummaryResult
NewHealthCheckSummaryResult creates a new health check summary result
func (*HealthCheckSummaryResult) AddCheckResult ¶
func (h *HealthCheckSummaryResult) AddCheckResult(status string, latencyMs int64)
AddCheckResult adds a check result to the summary statistics
func (HealthCheckSummaryResult) TableName ¶
func (HealthCheckSummaryResult) TableName() string
TableName returns the DynamoDB table backing HealthCheckSummaryResult.
func (*HealthCheckSummaryResult) UpdateKeys ¶
func (h *HealthCheckSummaryResult) UpdateKeys()
UpdateKeys updates the partition and sort keys for the health check summary
type Import ¶
type Import struct {
// Primary keys - import records use IMPORT#{import_id} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for user queries - USER#{username}, CREATED#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// Import metadata
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
Type string `theorydb:"attr:type" json:"type"` // followers, following, blocks, mutes, lists, bookmarks, archive
Mode string `theorydb:"attr:mode" json:"mode"` // merge, overwrite
Status string `theorydb:"attr:status" json:"status"` // pending, processing, completed, failed
S3Key string `theorydb:"attr:s3Key" json:"s3_key"` // Location of import file
// Progress tracking
Total int `theorydb:"attr:total" json:"total"`
Progress int `theorydb:"attr:progress" json:"progress"`
SuccessCount int `theorydb:"attr:successCount" json:"success_count"`
SkipCount int `theorydb:"attr:skipCount" json:"skip_count"`
ErrorCount int `theorydb:"attr:errorCount" json:"error_count"`
Errors []string `theorydb:"attr:errors" json:"errors,omitempty"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
// Error information
Error string `theorydb:"attr:error" json:"error,omitempty"`
// contains filtered or unexported fields
}
Import represents a data import request
func (*Import) GetCreatedAt ¶
GetCreatedAt returns the creation timestamp of the import
func (*Import) UpdateKeys ¶
func (i *Import) UpdateKeys()
UpdateKeys sets the primary keys for the Import model
type ImportBudget ¶
type ImportBudget struct {
// Primary keys - user budget records use USER_BUDGET#{username}#{period} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for period queries - BUDGET#{period}, USER#{username}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// Budget configuration
Username string `theorydb:"attr:username" json:"username"`
Period string `theorydb:"attr:period" json:"period"` // daily, weekly, monthly
// Cost limits (all in microcents)
ImportLimitMicroCents int64 `theorydb:"attr:importLimitMicroCents" json:"import_limit_micro_cents"` // Maximum import cost per period
ExportLimitMicroCents int64 `theorydb:"attr:exportLimitMicroCents" json:"export_limit_micro_cents"` // Maximum export cost per period
CombinedLimitMicroCents int64 `theorydb:"attr:combinedLimitMicroCents" json:"combined_limit_micro_cents"` // Maximum combined cost per period
// Current usage (resets each period)
CurrentImportCost int64 `theorydb:"attr:currentImportCost" json:"current_import_cost"` // Current import spending
CurrentExportCost int64 `theorydb:"attr:currentExportCost" json:"current_export_cost"` // Current export spending
CurrentCombinedCost int64 `theorydb:"attr:currentCombinedCost" json:"current_combined_cost"` // Current combined spending
// Operation counts
ImportCount int64 `theorydb:"attr:importCount" json:"import_count"` // Number of imports this period
ExportCount int64 `theorydb:"attr:exportCount" json:"export_count"` // Number of exports this period
// Alert configuration
AlertThresholdPercent float64 `theorydb:"attr:alertThresholdPercent" json:"alert_threshold_percent"` // Alert when usage exceeds this percentage
AlertSendingEnabled bool `theorydb:"attr:alertSendingEnabled" json:"alert_sending_enabled"` // Whether to send alerts
LastAlertSent *time.Time `theorydb:"attr:lastAlertSent" json:"last_alert_sent,omitempty"` // When last alert was sent
// Status tracking
IsActive bool `theorydb:"attr:isActive" json:"is_active"` // Whether budget enforcement is active
LastImportAt *time.Time `theorydb:"attr:lastImportAt" json:"last_import_at,omitempty"` // When last import occurred
LastExportAt *time.Time `theorydb:"attr:lastExportAt" json:"last_export_at,omitempty"` // When last export occurred
PeriodStart time.Time `theorydb:"attr:periodStart" json:"period_start"` // Start of current budget period
PeriodEnd time.Time `theorydb:"attr:periodEnd" json:"period_end"` // End of current budget period
NextResetAt time.Time `theorydb:"attr:nextResetAt" json:"next_reset_at"` // When budget will reset
LastResetAt *time.Time `theorydb:"attr:lastResetAt" json:"last_reset_at,omitempty"` // When budget was last reset
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ImportBudget represents budget limits for import/export operations
func (*ImportBudget) BeforeCreate ¶
func (b *ImportBudget) BeforeCreate() error
BeforeCreate is called before creating the record
func (*ImportBudget) BeforeUpdate ¶
func (b *ImportBudget) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*ImportBudget) GetCombinedUsagePercent ¶
func (b *ImportBudget) GetCombinedUsagePercent() float64
GetCombinedUsagePercent returns the current combined usage as a percentage of limit
func (*ImportBudget) GetExportUsagePercent ¶
func (b *ImportBudget) GetExportUsagePercent() float64
GetExportUsagePercent returns the current export usage as a percentage of limit
func (*ImportBudget) GetImportUsagePercent ¶
func (b *ImportBudget) GetImportUsagePercent() float64
GetImportUsagePercent returns the current import usage as a percentage of limit
func (*ImportBudget) GetRemainingCombinedBudget ¶
func (b *ImportBudget) GetRemainingCombinedBudget() int64
GetRemainingCombinedBudget returns remaining combined budget in microcents
func (*ImportBudget) GetRemainingExportBudget ¶
func (b *ImportBudget) GetRemainingExportBudget() int64
GetRemainingExportBudget returns remaining export budget in microcents
func (*ImportBudget) GetRemainingImportBudget ¶
func (b *ImportBudget) GetRemainingImportBudget() int64
GetRemainingImportBudget returns remaining import budget in microcents
func (*ImportBudget) IsCombinedOverLimit ¶
func (b *ImportBudget) IsCombinedOverLimit(additionalImportCost, additionalExportCost int64) bool
IsCombinedOverLimit checks if combined spending would exceed limit
func (*ImportBudget) IsExportOverLimit ¶
func (b *ImportBudget) IsExportOverLimit(additionalCost int64) bool
IsExportOverLimit checks if export spending would exceed limit
func (*ImportBudget) IsImportOverLimit ¶
func (b *ImportBudget) IsImportOverLimit(additionalCost int64) bool
IsImportOverLimit checks if import spending would exceed limit
func (*ImportBudget) NeedsReset ¶
func (b *ImportBudget) NeedsReset() bool
NeedsReset checks if the budget period has ended and needs reset
func (*ImportBudget) Reset ¶
func (b *ImportBudget) Reset()
Reset resets the budget for a new period
func (*ImportBudget) ShouldSendAlert ¶
func (b *ImportBudget) ShouldSendAlert() bool
ShouldSendAlert checks if an alert should be sent based on usage
func (ImportBudget) TableName ¶
func (ImportBudget) TableName() string
TableName returns the DynamoDB table backing ImportBudget.
func (*ImportBudget) UpdateKeys ¶
func (b *ImportBudget) UpdateKeys()
UpdateKeys sets the primary keys for the ImportBudget model
type ImportCostSummary ¶
type ImportCostSummary struct {
Username string `json:"username"`
Period string `json:"period"` // daily, weekly, monthly
StartDate time.Time `json:"start_date"`
EndDate time.Time `json:"end_date"`
TotalImports int64 `json:"total_imports"`
CompletedImports int64 `json:"completed_imports"`
FailedImports int64 `json:"failed_imports"`
TotalLambdaCost int64 `json:"total_lambda_cost"`
TotalS3Cost int64 `json:"total_s3_cost"`
TotalDynamoDBCost int64 `json:"total_dynamodb_cost"`
TotalNetworkCost int64 `json:"total_network_cost"`
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
TotalRecordsProcessed int64 `json:"total_records_processed"`
TotalRecordsSucceeded int64 `json:"total_records_succeeded"`
TotalRecordsFailed int64 `json:"total_records_failed"`
AverageCostPerImport float64 `json:"average_cost_per_import"`
AverageCostPerRecord float64 `json:"average_cost_per_record"`
OverallSuccessRate float64 `json:"overall_success_rate"`
TypeBreakdown map[string]*ImportTypeCostStats `json:"type_breakdown"`
}
ImportCostSummary represents aggregated import costs (same structure as ExportCostSummary)
func (ImportCostSummary) TableName ¶
func (ImportCostSummary) TableName() string
TableName returns the DynamoDB table backing ImportCostSummary.
type ImportCostTracking ¶
type ImportCostTracking struct {
// Primary keys - import cost tracking uses IMPORT_COST#{import_id}#{timestamp} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for user queries - USER#{username}, COST#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for date range queries - IMPORT_COSTS#{date}, TS#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Import metadata
ImportID string `theorydb:"attr:importID" json:"import_id"`
Username string `theorydb:"attr:username" json:"username"`
Type string `theorydb:"attr:type" json:"type"` // followers, following, blocks, mutes, lists, bookmarks, archive
Mode string `theorydb:"attr:mode" json:"mode"` // merge, overwrite
// Cost breakdown (all in microcents)
LambdaExecutionCost int64 `theorydb:"attr:lambdaExecutionCost" json:"lambda_execution_cost"` // Lambda compute cost
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Lambda execution time
S3StorageCost int64 `theorydb:"attr:s3StorageCost" json:"s3_storage_cost"` // S3 storage for import file
S3GetRequestCost int64 `theorydb:"attr:s3GetRequestCost" json:"s3_get_request_cost"` // S3 GET operations to download file
S3DataTransferCost int64 `theorydb:"attr:s3DataTransferCost" json:"s3_data_transfer_cost"` // Data transfer costs
DynamoDBWriteCost int64 `theorydb:"attr:dynamodbWriteCost" json:"dynamodb_write_cost"` // DynamoDB write operations
DynamoDBReadCost int64 `theorydb:"attr:dynamodbReadCost" json:"dynamodb_read_cost"` // DynamoDB read operations (for lookups)
DynamoDBWriteUnits float64 `theorydb:"attr:dynamodbWriteUnits" json:"dynamodb_write_units"` // Write capacity consumed
DynamoDBReadUnits float64 `theorydb:"attr:dynamodbReadUnits" json:"dynamodb_read_units"` // Read capacity consumed
DynamoDBOperations int64 `theorydb:"attr:dynamodbOperations" json:"dynamodb_operations"` // Number of DB operations
ExternalAPICallCost int64 `theorydb:"attr:externalAPICallCost" json:"external_api_call_cost"` // Cost of WebFinger/ActivityPub lookups
ExternalAPICalls int64 `theorydb:"attr:externalAPICalls" json:"external_api_calls"` // Number of external API calls
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost in microcents
// Operation metrics
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // Size of imported file in bytes
RecordCount int64 `theorydb:"attr:recordCount" json:"record_count"` // Number of records in import file
ProcessedCount int64 `theorydb:"attr:processedCount" json:"processed_count"` // Number of records processed
SuccessCount int64 `theorydb:"attr:successCount" json:"success_count"` // Number of successful operations
SkipCount int64 `theorydb:"attr:skipCount" json:"skip_count"` // Number of skipped operations
ErrorCount int64 `theorydb:"attr:errorCount" json:"error_count"` // Number of failed operations
S3GetRequests int64 `theorydb:"attr:s3GetRequests" json:"s3_get_requests"` // Number of S3 GET requests
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Bytes transferred
// Network operations (for federated follows/blocks)
DNSLookups int64 `theorydb:"attr:dnsLookups" json:"dns_lookups"` // DNS lookups performed
HTTPRequests int64 `theorydb:"attr:httpRequests" json:"http_requests"` // HTTP requests made
NetworkBytes int64 `theorydb:"attr:networkBytes" json:"network_bytes"` // Network bytes transferred
// Status tracking
Status string `theorydb:"attr:status" json:"status"` // pending, processing, completed, failed
StartedAt time.Time `theorydb:"attr:startedAt" json:"started_at"` // When import processing started
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"` // When import completed
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ImportCostTracking represents cost tracking for import operations
func (*ImportCostTracking) BeforeCreate ¶
func (i *ImportCostTracking) BeforeCreate() error
BeforeCreate is called before creating the record
func (*ImportCostTracking) BeforeUpdate ¶
func (i *ImportCostTracking) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*ImportCostTracking) CalculateTotalCost ¶
func (i *ImportCostTracking) CalculateTotalCost()
CalculateTotalCost calculates the total cost from all components
func (*ImportCostTracking) GetSuccessRate ¶
func (i *ImportCostTracking) GetSuccessRate() float64
GetSuccessRate calculates the success rate of the import
func (*ImportCostTracking) GetTimestamp ¶
func (i *ImportCostTracking) GetTimestamp() time.Time
GetTimestamp returns the timestamp for cost tracking
func (*ImportCostTracking) GetTotalCostDollars ¶
func (i *ImportCostTracking) GetTotalCostDollars() float64
GetTotalCostDollars returns the total cost in dollars
func (*ImportCostTracking) GetTotalCostMicroCents ¶
func (i *ImportCostTracking) GetTotalCostMicroCents() int64
GetTotalCostMicroCents returns the total cost in microcents
func (*ImportCostTracking) TableName ¶
func (i *ImportCostTracking) TableName() string
TableName returns the DynamoDB table backing ImportCostTracking.
func (*ImportCostTracking) UpdateKeys ¶
func (i *ImportCostTracking) UpdateKeys()
UpdateKeys sets the primary keys for the ImportCostTracking model
type ImportTypeCostStats ¶
type ImportTypeCostStats struct {
Type string `json:"type"`
Count int64 `json:"count"`
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
TotalCostDollars float64 `json:"total_cost_dollars"`
AverageCostMicroCents int64 `json:"average_cost_micro_cents"`
TotalRecords int64 `json:"total_records"`
SuccessfulRecords int64 `json:"successful_records"`
FailedRecords int64 `json:"failed_records"`
SuccessRate float64 `json:"success_rate"`
}
ImportTypeCostStats represents cost statistics for a specific import type
func (ImportTypeCostStats) TableName ¶
func (ImportTypeCostStats) TableName() string
TableName returns the DynamoDB table backing ImportTypeCostStats.
type InboxItem ¶
type InboxItem struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI fields for inbox queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// Business fields
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // The recipient actor ID
ActivityID string `theorydb:"attr:activityID" json:"activity_id"` // The activity ID
Activity *activitypub.Activity `theorydb:"attr:activity" json:"activity"` // The full activity object
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When the activity was received
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
InboxItem represents an activity delivered to an actor's inbox
func (*InboxItem) UpdateKeys ¶
func (i *InboxItem) UpdateKeys()
UpdateKeys updates the composite keys based on the inbox item data
type InboxProcessingReceipt ¶ added in v1.2.48
type InboxProcessingReceipt struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
ActivityID string `theorydb:"attr:activityID" json:"activity_id"`
TargetActorID string `theorydb:"attr:targetActorID" json:"target_actor_id"`
ActivityType string `theorydb:"attr:activityType" json:"activity_type,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
InboxProcessingReceipt records that one ActivityPub activity has been routed to one local target actor. It is a short-lived idempotency guard for inbox side effects when the same remote Create/Like/Announce/Undo reaches both a shared inbox and an actor inbox.
func NewInboxProcessingReceipt ¶ added in v1.2.48
func NewInboxProcessingReceipt(activityID, targetActorID, activityType string, now time.Time) *InboxProcessingReceipt
NewInboxProcessingReceipt builds a target-scoped inbox idempotency receipt.
func (*InboxProcessingReceipt) BeforeCreate ¶ added in v1.2.48
func (r *InboxProcessingReceipt) BeforeCreate() error
BeforeCreate derives keys and TTL before persistence.
func (*InboxProcessingReceipt) BeforeUpdate ¶ added in v1.2.48
func (r *InboxProcessingReceipt) BeforeUpdate() error
BeforeUpdate derives keys before persistence.
func (*InboxProcessingReceipt) GetPK ¶ added in v1.2.48
func (r *InboxProcessingReceipt) GetPK() string
GetPK returns the partition key.
func (*InboxProcessingReceipt) GetSK ¶ added in v1.2.48
func (r *InboxProcessingReceipt) GetSK() string
GetSK returns the sort key.
func (InboxProcessingReceipt) TableName ¶ added in v1.2.48
func (InboxProcessingReceipt) TableName() string
TableName returns the DynamoDB table backing InboxProcessingReceipt.
func (*InboxProcessingReceipt) UpdateKeys ¶ added in v1.2.48
func (r *InboxProcessingReceipt) UpdateKeys() error
UpdateKeys derives the receipt's storage keys.
type InstanceCluster ¶
type InstanceCluster struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ClusterID string `theorydb:"attr:clusterID" json:"cluster_id"`
Name string `theorydb:"attr:name" json:"name"`
Instances []string `theorydb:"attr:instances" json:"instances"`
CenterNode string `theorydb:"attr:centerNode" json:"center_node"` // Most connected instance
Cohesion float64 `theorydb:"attr:cohesion" json:"cohesion"` // How tightly connected (0.0-1.0)
Size int `theorydb:"attr:size" json:"size"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceCluster represents a group of closely connected instances
func (InstanceCluster) TableName ¶
func (InstanceCluster) TableName() string
TableName returns the DynamoDB table backing InstanceCluster.
func (*InstanceCluster) UpdateKeys ¶
func (i *InstanceCluster) UpdateKeys()
UpdateKeys updates the GSI keys for instance cluster
type InstanceConfig ¶
type InstanceConfig struct {
// Primary key fields - EXACT pattern from legacy
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#CONFIG
SK string `theorydb:"sk,attr:SK" json:"-"` // RULES or EXTENDED_DESC
// Configuration data - use storage.InstanceRule to avoid dependency cycle
RulesJSON string `theorydb:"attr:rulesJSON" json:"rules_json,omitempty"` // JSON serialized rules
ExtendedDescription string `theorydb:"attr:extendedDescription" json:"extended_description,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceConfig represents instance configuration data stored in DynamoDB Matches legacy InstanceData structure from dynamodb/instance.go
func NewExtendedDescriptionConfig ¶
func NewExtendedDescriptionConfig(description string) *InstanceConfig
NewExtendedDescriptionConfig creates a new config for storing extended description
func NewInstanceRulesConfig ¶
func NewInstanceRulesConfig(rulesJSON string) *InstanceConfig
NewInstanceRulesConfig creates a new config for storing rules
func (*InstanceConfig) GetPK ¶
func (c *InstanceConfig) GetPK() string
GetPK returns the partition key
func (InstanceConfig) TableName ¶
func (InstanceConfig) TableName() string
TableName returns the DynamoDB table backing InstanceConfig.
func (*InstanceConfig) UpdateKeys ¶
func (c *InstanceConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys (no GSI needed for this simple structure)
type InstanceConnection ¶
type InstanceConnection struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
Domain string `theorydb:"attr:domain" json:"domain"`
TargetDomain string `theorydb:"attr:targetDomain" json:"target_domain"`
Direction string `theorydb:"attr:direction" json:"direction"` // inbound/outbound
ConnectionType string `theorydb:"attr:connectionType" json:"connection_type"`
VolumeIn int64 `theorydb:"attr:volumeIn" json:"volume_in"`
VolumeOut int64 `theorydb:"attr:volumeOut" json:"volume_out"`
LastActivity time.Time `theorydb:"attr:lastActivity" json:"last_activity"`
Success bool `theorydb:"attr:success" json:"success"`
// contains filtered or unexported fields
}
InstanceConnection represents a specific connection type between instances
func (InstanceConnection) TableName ¶
func (InstanceConnection) TableName() string
TableName returns the DynamoDB table backing InstanceConnection.
func (*InstanceConnection) UpdateKeys ¶
func (i *InstanceConnection) UpdateKeys()
UpdateKeys updates the GSI keys for instance connection
type InstanceDomainBlock ¶
type InstanceDomainBlock struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
ID string `theorydb:"attr:id" json:"ID"`
Domain string `theorydb:"attr:domain" json:"Domain"`
Severity string `theorydb:"attr:severity" json:"Severity"` // "silence" or "suspend"
RejectMedia bool `theorydb:"attr:rejectMedia" json:"RejectMedia"`
RejectReports bool `theorydb:"attr:rejectReports" json:"RejectReports"`
PrivateComment string `theorydb:"attr:privateComment" json:"PrivateComment"` // Admin-only notes
PublicComment string `theorydb:"attr:publicComment" json:"PublicComment"` // Public reason
Obfuscate bool `theorydb:"attr:obfuscate" json:"Obfuscate"` // Whether to obfuscate in public lists
CreatedBy string `theorydb:"attr:createdBy" json:"CreatedBy"` // Admin username who created
CreatedByID string `theorydb:"attr:createdByID" json:"CreatedByID"` // Admin actor ID
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"UpdatedAt"`
Type string `theorydb:"attr:type" json:"Type"`
// contains filtered or unexported fields
}
InstanceDomainBlock represents an instance-level domain block
func (*InstanceDomainBlock) GetPK ¶
func (d *InstanceDomainBlock) GetPK() string
GetPK returns the partition key (required by BaseModel)
func (*InstanceDomainBlock) GetSK ¶
func (d *InstanceDomainBlock) GetSK() string
GetSK returns the sort key (required by BaseModel)
func (InstanceDomainBlock) TableName ¶
func (InstanceDomainBlock) TableName() string
TableName returns the DynamoDB table backing InstanceDomainBlock.
func (*InstanceDomainBlock) UpdateKeys ¶
func (d *InstanceDomainBlock) UpdateKeys() error
UpdateKeys updates the keys for the instance domain block
type InstanceHealth ¶
type InstanceHealth struct {
// Keys - Using same pattern as legacy health checker
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#domain
SK string `theorydb:"sk,attr:SK" json:"-"` // HEALTH#timestamp_nano
// Core health data
Domain string `theorydb:"attr:domain" json:"domain"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Reachable bool `theorydb:"attr:reachable" json:"reachable"`
ResponseTime time.Duration `theorydb:"attr:responseTime" json:"response_time"`
StatusCode int `theorydb:"attr:statusCode" json:"status_code"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
// Resource usage metrics
CPUUsage float64 `theorydb:"attr:cpuUsage" json:"cpu_usage,omitempty"`
MemoryUsage float64 `theorydb:"attr:memoryUsage" json:"memory_usage,omitempty"`
DiskUsage float64 `theorydb:"attr:diskUsage" json:"disk_usage,omitempty"`
// Federation metrics
InboxBacklog int `theorydb:"attr:inboxBacklog" json:"inbox_backlog,omitempty"`
ProcessingDelay time.Duration `theorydb:"attr:processingDelay" json:"processing_delay,omitempty"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate,omitempty"`
// Additional metadata
CheckerVersion string `theorydb:"attr:checkerVersion" json:"checker_version,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
// TTL for automatic cleanup (7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceHealth represents health status for a federated instance
func NewInstanceHealth ¶
func NewInstanceHealth(domain string) *InstanceHealth
NewInstanceHealth creates a new instance health record
func (*InstanceHealth) GetHealthScore ¶
func (h *InstanceHealth) GetHealthScore() float64
GetHealthScore calculates a health score from 0-100
func (*InstanceHealth) GetPK ¶
func (h *InstanceHealth) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*InstanceHealth) GetSK ¶
func (h *InstanceHealth) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*InstanceHealth) IsCritical ¶
func (h *InstanceHealth) IsCritical() bool
IsCritical returns true if the instance is in critical state
func (*InstanceHealth) IsHealthy ¶
func (h *InstanceHealth) IsHealthy() bool
IsHealthy returns true if the instance is considered healthy
func (InstanceHealth) TableName ¶
func (InstanceHealth) TableName() string
TableName returns the DynamoDB table backing InstanceHealth.
func (*InstanceHealth) UpdateKeys ¶
func (h *InstanceHealth) UpdateKeys() error
UpdateKeys updates the partition and sort keys
type InstanceHealthReport ¶
type InstanceHealthReport struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#domain
SK string `theorydb:"sk,attr:SK" json:"-"` // HEALTH#{timestamp}
// Attributes from interface
Domain string `theorydb:"attr:domain" json:"domain"`
Status string `theorydb:"attr:status" json:"status"` // healthy/warning/critical
ResponseTime float64 `theorydb:"attr:responseTime" json:"response_time"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
FederationDelay float64 `theorydb:"attr:federationDelay" json:"federation_delay"`
QueueDepth int `theorydb:"attr:queueDepth" json:"queue_depth"`
Issues []string `theorydb:"attr:issues" json:"issues"`
Recommendations []string `theorydb:"attr:recommendations" json:"recommendations"`
LastChecked time.Time `theorydb:"attr:lastChecked" json:"last_checked"`
// Additional metadata
Timestamp string `theorydb:"attr:timestamp" json:"timestamp"` // ISO timestamp for sorting
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 30 days retention
// contains filtered or unexported fields
}
InstanceHealthReport represents health metrics for a federated instance
func NewInstanceHealthReport ¶
func NewInstanceHealthReport(domain string) *InstanceHealthReport
NewInstanceHealthReport creates a new health report
func (*InstanceHealthReport) IsCritical ¶
func (h *InstanceHealthReport) IsCritical() bool
IsCritical returns true if the instance is in critical state
func (*InstanceHealthReport) IsHealthy ¶
func (h *InstanceHealthReport) IsHealthy() bool
IsHealthy returns true if the instance is healthy
func (*InstanceHealthReport) SetHealthStatus ¶
func (h *InstanceHealthReport) SetHealthStatus()
SetHealthStatus updates the health status based on metrics
func (InstanceHealthReport) TableName ¶
func (InstanceHealthReport) TableName() string
TableName returns the DynamoDB table backing InstanceHealthReport.
func (*InstanceHealthReport) UpdateKeys ¶
func (h *InstanceHealthReport) UpdateKeys()
UpdateKeys updates the partition and sort keys
type InstanceHealthSummary ¶
type InstanceHealthSummary struct {
// Keys for summary data
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#domain
SK string `theorydb:"sk,attr:SK" json:"-"` // SUMMARY#window (e.g., SUMMARY#1h, SUMMARY#24h)
// Metadata
Domain string `theorydb:"attr:domain" json:"domain"`
Window time.Duration `theorydb:"attr:window" json:"window"` // Time window for aggregation
LastUpdated time.Time `theorydb:"attr:lastUpdated" json:"last_updated"`
SampleCount int `theorydb:"attr:sampleCount" json:"sample_count"`
// Aggregated metrics
Availability float64 `theorydb:"attr:availability" json:"availability"` // Percentage of successful checks
AvgResponseTime time.Duration `theorydb:"attr:avgResponseTime" json:"avg_response_time"`
MaxResponseTime time.Duration `theorydb:"attr:maxResponseTime" json:"max_response_time"`
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"`
AvgInboxBacklog int `theorydb:"attr:avgInboxBacklog" json:"avg_inbox_backlog"`
MaxInboxBacklog int `theorydb:"attr:maxInboxBacklog" json:"max_inbox_backlog"`
HealthScore float64 `theorydb:"attr:healthScore" json:"health_score"` // 0-100
// Status code distribution
StatusCodeCounts map[string]int `theorydb:"attr:statusCodeCounts" json:"status_code_counts"` // JSON serialized map
// TTL for cleanup (summaries kept longer - 30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceHealthSummary represents aggregated health data for an instance
func NewInstanceHealthSummary ¶
func NewInstanceHealthSummary(domain string, window time.Duration) *InstanceHealthSummary
NewInstanceHealthSummary creates a new health summary
func (*InstanceHealthSummary) GetPK ¶
func (s *InstanceHealthSummary) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*InstanceHealthSummary) GetSK ¶
func (s *InstanceHealthSummary) GetSK() string
GetSK returns the sort key for BaseModel interface
func (InstanceHealthSummary) TableName ¶
func (InstanceHealthSummary) TableName() string
TableName returns the DynamoDB table backing InstanceHealthSummary.
func (*InstanceHealthSummary) UpdateKeys ¶
func (s *InstanceHealthSummary) UpdateKeys() error
UpdateKeys updates the partition and sort keys for health summary
type InstanceHistory ¶
type InstanceHistory struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK"` // INSTANCE#HISTORY
SK string `theorydb:"sk,attr:SK"` // DAILY#{date} or MONTHLY#{date} or WEEKLY#{date}
// GSI1 for metric-specific time queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // METRIC#{metric_type}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // DATE#{YYYY-MM-DD}
// Business fields
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD format
MetricType string `theorydb:"attr:metricType" json:"metric_type"` // user_count, storage_bytes, post_count
Granularity string `theorydb:"attr:granularity" json:"granularity"` // daily, weekly, monthly
Value int64 `theorydb:"attr:value" json:"value"` // Current value
Delta int64 `theorydb:"attr:delta" json:"delta"` // Change from previous period
RecordedAt time.Time `theorydb:"attr:recordedAt" json:"recorded_at"` // When this metric was recorded
// Specific metric fields for detailed tracking
TotalUsers int64 `theorydb:"attr:totalUsers" json:"total_users,omitempty"` // Total registered users
ActiveUsers int64 `theorydb:"attr:activeUsers" json:"active_users,omitempty"` // Users active in period
NewUsers int64 `theorydb:"attr:newUsers" json:"new_users,omitempty"` // New registrations in period
TotalPosts int64 `theorydb:"attr:totalPosts" json:"total_posts,omitempty"` // Total posts/statuses
NewPosts int64 `theorydb:"attr:newPosts" json:"new_posts,omitempty"` // New posts in period
StorageBytes int64 `theorydb:"attr:storageBytes" json:"storage_bytes,omitempty"` // Total storage used
MediaBytes int64 `theorydb:"attr:mediaBytes" json:"media_bytes,omitempty"` // Media storage used
DatabaseBytes int64 `theorydb:"attr:databaseBytes" json:"database_bytes,omitempty"` // Database storage used
FederatedPosts int64 `theorydb:"attr:federatedPosts" json:"federated_posts,omitempty"` // Posts from other instances
LocalPosts int64 `theorydb:"attr:localPosts" json:"local_posts,omitempty"` // Posts from local users
KnownInstances int64 `theorydb:"attr:knownInstances" json:"known_instances,omitempty"` // Number of federated instances
ActiveInstances int64 `theorydb:"attr:activeInstances" json:"active_instances,omitempty"` // Active federation partners
// TTL field for automatic cleanup (90 days for daily, keep monthly forever)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceHistory stores time-series data for instance metrics Pattern: PK=INSTANCE#HISTORY, SK=DAILY#{YYYY-MM-DD} or MONTHLY#{YYYY-MM} or WEEKLY#{YYYY-WW} GSI1: PK=METRIC#{metric_type}, SK=DATE#{YYYY-MM-DD} for efficient time range queries
func NewDailyInstanceHistory ¶
func NewDailyInstanceHistory(date string, metricType string) *InstanceHistory
NewDailyInstanceHistory creates a new daily history record
func NewMonthlyInstanceHistory ¶
func NewMonthlyInstanceHistory(monthStart string, metricType string) *InstanceHistory
NewMonthlyInstanceHistory creates a new monthly history record (no TTL - keep forever)
func NewWeeklyInstanceHistory ¶
func NewWeeklyInstanceHistory(weekStart string, metricType string) *InstanceHistory
NewWeeklyInstanceHistory creates a new weekly history record
func (*InstanceHistory) CalculateDelta ¶
func (i *InstanceHistory) CalculateDelta(previousValue int64)
CalculateDelta calculates the delta from a previous period's value
func (*InstanceHistory) GetPK ¶
func (i *InstanceHistory) GetPK() string
GetPK returns the partition key
func (*InstanceHistory) SetFederationMetrics ¶
func (i *InstanceHistory) SetFederationMetrics(knownInstances, activeInstances int64)
SetFederationMetrics sets federation-related metrics
func (*InstanceHistory) SetPostMetrics ¶
func (i *InstanceHistory) SetPostMetrics(total, newPosts, local, federated int64)
SetPostMetrics sets post-related metrics
func (*InstanceHistory) SetStorageMetrics ¶
func (i *InstanceHistory) SetStorageMetrics(totalBytes, mediaBytes, dbBytes int64)
SetStorageMetrics sets storage-related metrics
func (*InstanceHistory) SetUserMetrics ¶
func (i *InstanceHistory) SetUserMetrics(total, active, newUsers int64)
SetUserMetrics sets user-related metrics
func (*InstanceHistory) TableName ¶
func (i *InstanceHistory) TableName() string
TableName returns the DynamoDB table backing InstanceHistory.
func (*InstanceHistory) UpdateKeys ¶
func (i *InstanceHistory) UpdateKeys() error
UpdateKeys updates the GSI keys when the primary keys change
type InstanceInfo ¶
type InstanceInfo struct {
Domain string `json:"domain"`
Software string `json:"software,omitempty"` // Mastodon, Pleroma, etc.
Version string `json:"version,omitempty"` // Software version
PublicKey string `json:"public_key,omitempty"` // Instance public key
LastSeen time.Time `json:"last_seen"`
FirstSeen time.Time `json:"first_seen"`
}
InstanceInfo contains information about a federated instance
func (InstanceInfo) TableName ¶
func (InstanceInfo) TableName() string
TableName returns the DynamoDB table backing InstanceInfo.
type InstanceMetadata ¶
type InstanceMetadata struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Domain string `theorydb:"attr:domain" json:"domain"`
DisplayName string `theorydb:"attr:displayName" json:"display_name,omitempty"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Software string `theorydb:"attr:software" json:"software,omitempty"`
Version string `theorydb:"attr:version" json:"version,omitempty"`
UserCount int64 `theorydb:"attr:userCount" json:"user_count,omitempty"`
StatusCount int64 `theorydb:"attr:statusCount" json:"status_count,omitempty"`
NodeInfo string `theorydb:"attr:nodeInfo" json:"nodeinfo"` // JSON string of nodeinfo response
InstanceInfo string `theorydb:"attr:instanceInfo" json:"instance_info"` // JSON string of instance API response
AdminContact string `theorydb:"attr:adminContact" json:"admin_contact,omitempty"`
Rules []string `theorydb:"attr:rules" json:"rules,omitempty"`
Languages []string `theorydb:"attr:languages" json:"languages,omitempty"`
Categories []string `theorydb:"attr:categories" json:"categories,omitempty"`
FederationNotes string `theorydb:"attr:federationNotes" json:"federation_notes,omitempty"`
LastUpdated time.Time `theorydb:"attr:lastUpdated" json:"last_updated"`
// contains filtered or unexported fields
}
InstanceMetadata contains detailed metadata about a federated instance
func (InstanceMetadata) TableName ¶
func (InstanceMetadata) TableName() string
TableName returns the DynamoDB table backing InstanceMetadata.
func (*InstanceMetadata) UpdateKeys ¶
func (i *InstanceMetadata) UpdateKeys()
UpdateKeys updates the GSI keys for instance metadata
type InstanceMetrics ¶
type InstanceMetrics struct {
// Key fields - EXACT pattern from legacy: PK=`INSTANCE_METRICS#date`, SK=`METRIC#type`
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI fields for time-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// Business fields from legacy
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD format
MetricType string `theorydb:"attr:metricType" json:"metric_type"` // total_users, active_users_daily, etc.
Value int64 `theorydb:"attr:value" json:"value"`
Delta int64 `theorydb:"attr:delta" json:"delta"` // change from previous period
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Additional metric types from legacy
TotalUsers int64 `theorydb:"attr:totalUsers" json:"total_users,omitempty"`
ActiveUsersDaily int64 `theorydb:"attr:activeUsersDaily" json:"active_users_daily,omitempty"`
ActiveUsersWeekly int64 `theorydb:"attr:activeUsersWeekly" json:"active_users_weekly,omitempty"`
TotalStatuses int64 `theorydb:"attr:totalStatuses" json:"total_statuses,omitempty"`
TotalMedia int64 `theorydb:"attr:totalMedia" json:"total_media,omitempty"`
FederationInbound int64 `theorydb:"attr:federationInbound" json:"federation_inbound,omitempty"`
FederationOutbound int64 `theorydb:"attr:federationOutbound" json:"federation_outbound,omitempty"`
// Weekly activity tracking
Week int64 `theorydb:"attr:week" json:"week,omitempty"` // Unix timestamp of week start
Statuses int32 `theorydb:"attr:statuses" json:"statuses,omitempty"` // Status count for the week
Logins int32 `theorydb:"attr:logins" json:"logins,omitempty"` // Login count for the week
Registrations int32 `theorydb:"attr:registrations" json:"registrations,omitempty"` // Registration count for the week
// TTL field
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceMetrics tracks platform-wide metrics and statistics
func (*InstanceMetrics) GetPK ¶
func (i *InstanceMetrics) GetPK() string
GetPK returns the partition key
func (*InstanceMetrics) TableName ¶
func (i *InstanceMetrics) TableName() string
TableName returns the DynamoDB table backing InstanceMetrics.
func (*InstanceMetrics) UpdateKeys ¶
func (i *InstanceMetrics) UpdateKeys() error
UpdateKeys updates the GSI keys when the primary keys change
type InstanceMetricsWindow ¶
type InstanceMetricsWindow struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // METRICS#INSTANCE#{instanceID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // WINDOW#{windowStartUnix}
// Instance and time info
InstanceID string `theorydb:"attr:instanceID" json:"instance_id"`
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowSize int64 `theorydb:"attr:windowSizeMinutes" json:"window_size_minutes"`
// Aggregated metrics
TotalMessages int64 `theorydb:"attr:totalMessages" json:"total_messages"`
TotalBytes int64 `theorydb:"attr:totalBytes" json:"total_bytes"`
TotalCost float64 `theorydb:"attr:totalCost" json:"total_cost"`
HealthChecks int64 `theorydb:"attr:healthChecks" json:"health_checks"`
Availability float64 `theorydb:"attr:availability" json:"availability"`
// Message type distribution (JSON-encoded map[string]int64)
MessageTypes string `theorydb:"attr:messageTypes" json:"message_types,omitempty"`
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceMetricsWindow represents aggregated instance metrics for a time window
func (*InstanceMetricsWindow) GetPK ¶
func (i *InstanceMetricsWindow) GetPK() string
GetPK returns the partition key
func (*InstanceMetricsWindow) GetSK ¶
func (i *InstanceMetricsWindow) GetSK() string
GetSK returns the sort key
func (InstanceMetricsWindow) TableName ¶
func (InstanceMetricsWindow) TableName() string
TableName returns the DynamoDB table backing InstanceMetricsWindow.
func (*InstanceMetricsWindow) UpdateKeys ¶
func (i *InstanceMetricsWindow) UpdateKeys() error
UpdateKeys updates the keys based on the current data
type InstanceRule ¶
type InstanceRule struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#RULES
SK string `theorydb:"sk,attr:SK" json:"-"` // RULE#{order}#{id}
// GSI for active rules
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // INSTANCE#ACTIVE_RULES
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // {order}#{id}
// Rule data
ID string `theorydb:"attr:id" json:"id"`
Text string `theorydb:"attr:text" json:"text"`
Order int `theorydb:"attr:order" json:"order"` // Display order
Category string `theorydb:"attr:category" json:"category,omitempty"` // Optional category
Severity string `theorydb:"attr:severity" json:"severity,omitempty"` // info, warning, critical
Active bool `theorydb:"attr:active" json:"active"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CreatedBy string `theorydb:"attr:createdBy" json:"created_by,omitempty"` // Admin who created
EnforcedAt *time.Time `theorydb:"attr:enforcedAt" json:"enforced_at,omitempty"` // When enforcement started
Description string `theorydb:"attr:description" json:"description,omitempty"` // Extended description
Examples []string `theorydb:"attr:examples" json:"examples,omitempty"` // Example violations
// contains filtered or unexported fields
}
InstanceRule represents a server rule stored in DynamoDB
func (*InstanceRule) Activate ¶
func (r *InstanceRule) Activate()
Activate marks the rule as active and enforced
func (*InstanceRule) Deactivate ¶
func (r *InstanceRule) Deactivate()
Deactivate marks the rule as inactive
func (*InstanceRule) GetSeverityLevel ¶
func (r *InstanceRule) GetSeverityLevel() int
GetSeverityLevel returns a numeric severity level for sorting
func (*InstanceRule) SetOrder ¶
func (r *InstanceRule) SetOrder(order int)
SetOrder updates the display order
func (InstanceRule) TableName ¶
func (InstanceRule) TableName() string
TableName returns the DynamoDB table backing InstanceRule.
func (*InstanceRule) UpdateKeys ¶
func (r *InstanceRule) UpdateKeys()
UpdateKeys updates the GSI keys based on the rule data
type InstanceSoulBindingIdempotencyReceipt ¶ added in v1.5.21
type InstanceSoulBindingIdempotencyReceipt struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
CallerID string `theorydb:"attr:callerId" json:"caller_id"`
IdempotencyKeyHash string `theorydb:"attr:idempotencyKeyHash" json:"idempotency_key_hash"`
PayloadHash string `theorydb:"attr:payloadHash" json:"payload_hash"`
AgentID string `theorydb:"attr:agentId" json:"agent_id"`
ActorUsername string `theorydb:"attr:actorUsername" json:"actor_username"`
BodyActorID string `theorydb:"attr:bodyActorId,omitempty" json:"body_actor_id,omitempty"`
Status string `theorydb:"attr:status" json:"status"`
BindingState string `theorydb:"attr:bindingState,omitempty" json:"binding_state,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
InstanceSoulBindingIdempotencyReceipt stores TTL-scoped replay evidence for server-side soul-binding requests. It is control-plane evidence only; the terminal binding truth remains the SOUL_BODY_BINDING rows.
func NewInstanceSoulBindingIdempotencyReceipt ¶ added in v1.5.21
func NewInstanceSoulBindingIdempotencyReceipt(callerID string, idempotencyKey string, payloadHash string, agentID string, actorUsername string, ttl time.Time) *InstanceSoulBindingIdempotencyReceipt
NewInstanceSoulBindingIdempotencyReceipt creates a new TTL-scoped soul-binding receipt.
func (*InstanceSoulBindingIdempotencyReceipt) GetPK ¶ added in v1.5.21
func (r *InstanceSoulBindingIdempotencyReceipt) GetPK() string
GetPK returns the partition key.
func (*InstanceSoulBindingIdempotencyReceipt) GetSK ¶ added in v1.5.21
func (r *InstanceSoulBindingIdempotencyReceipt) GetSK() string
GetSK returns the sort key.
func (InstanceSoulBindingIdempotencyReceipt) TableName ¶ added in v1.5.21
func (InstanceSoulBindingIdempotencyReceipt) TableName() string
TableName returns the DynamoDB table backing InstanceSoulBindingIdempotencyReceipt.
func (*InstanceSoulBindingIdempotencyReceipt) UpdateKeys ¶ added in v1.5.21
func (r *InstanceSoulBindingIdempotencyReceipt) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceSoulBodyBinding ¶ added in v0.1.36
type InstanceSoulBodyBinding struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
AgentID string `theorydb:"attr:agentId" json:"agent_id"`
Username string `theorydb:"attr:username" json:"username"`
PrincipalAddress string `theorydb:"attr:principalAddress,omitempty" json:"principal_address,omitempty"`
BoundAt time.Time `theorydb:"attr:boundAt" json:"bound_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceSoulBodyBinding stores an explicit soul -> local body binding.
This record lives under PK="INSTANCE#CONFIG" and SK="SOUL_BODY_BINDING#<agentId>".
func NewInstanceSoulBodyBinding ¶ added in v0.1.36
func NewInstanceSoulBodyBinding(agentID string, username string, principalAddress string) *InstanceSoulBodyBinding
NewInstanceSoulBodyBinding creates a new soul/body binding record.
func (*InstanceSoulBodyBinding) GetPK ¶ added in v0.1.36
func (b *InstanceSoulBodyBinding) GetPK() string
GetPK returns the partition key.
func (*InstanceSoulBodyBinding) GetSK ¶ added in v0.1.36
func (b *InstanceSoulBodyBinding) GetSK() string
GetSK returns the sort key.
func (InstanceSoulBodyBinding) TableName ¶ added in v0.1.36
func (InstanceSoulBodyBinding) TableName() string
TableName returns the DynamoDB table backing InstanceSoulBodyBinding.
func (*InstanceSoulBodyBinding) UpdateKeys ¶ added in v0.1.36
func (b *InstanceSoulBodyBinding) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceSoulBodyBindingUsername ¶ added in v0.1.36
type InstanceSoulBodyBindingUsername struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Username string `theorydb:"attr:username" json:"username"`
AgentID string `theorydb:"attr:agentId" json:"agent_id"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceSoulBodyBindingUsername stores the reverse username -> soul binding lookup.
This record lives under PK="SOUL_BODY_BINDING_USERNAME#<username>" and SK="SOUL_BODY_BINDING".
func NewInstanceSoulBodyBindingUsername ¶ added in v0.1.36
func NewInstanceSoulBodyBindingUsername(username string, agentID string) *InstanceSoulBodyBindingUsername
NewInstanceSoulBodyBindingUsername creates a new reverse username binding record.
func (*InstanceSoulBodyBindingUsername) GetPK ¶ added in v0.1.36
func (b *InstanceSoulBodyBindingUsername) GetPK() string
GetPK returns the partition key.
func (*InstanceSoulBodyBindingUsername) GetSK ¶ added in v0.1.36
func (b *InstanceSoulBodyBindingUsername) GetSK() string
GetSK returns the sort key.
func (InstanceSoulBodyBindingUsername) TableName ¶ added in v0.1.36
func (InstanceSoulBodyBindingUsername) TableName() string
TableName returns the DynamoDB table backing InstanceSoulBodyBindingUsername.
func (*InstanceSoulBodyBindingUsername) UpdateKeys ¶ added in v0.1.36
func (b *InstanceSoulBodyBindingUsername) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceSoulENSChannel ¶ added in v0.1.36
type InstanceSoulENSChannel struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
AgentID string `theorydb:"attr:agentId" json:"agent_id"`
Name string `theorydb:"attr:name" json:"name"`
ResolverAddress string `theorydb:"attr:resolverAddress,omitempty" json:"resolver_address,omitempty"`
Chain string `theorydb:"attr:chain" json:"chain"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceSoulENSChannel stores instance-owned ENS channel publication config for a soul agent.
This record lives under PK="INSTANCE#CONFIG" and SK="SOUL_ENS_CHANNEL#<agentId>".
func NewInstanceSoulENSChannel ¶ added in v0.1.36
func NewInstanceSoulENSChannel(agentID string) *InstanceSoulENSChannel
NewInstanceSoulENSChannel creates a new soul ENS channel config.
func (*InstanceSoulENSChannel) GetPK ¶ added in v0.1.36
func (c *InstanceSoulENSChannel) GetPK() string
GetPK returns the partition key.
func (*InstanceSoulENSChannel) GetSK ¶ added in v0.1.36
func (c *InstanceSoulENSChannel) GetSK() string
GetSK returns the sort key.
func (InstanceSoulENSChannel) TableName ¶ added in v0.1.36
func (InstanceSoulENSChannel) TableName() string
TableName returns the DynamoDB table backing InstanceSoulENSChannel.
func (*InstanceSoulENSChannel) UpdateKeys ¶ added in v0.1.36
func (c *InstanceSoulENSChannel) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceState ¶
type InstanceState struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // INSTANCE#CONFIG
SK string `theorydb:"sk,attr:SK" json:"-"` // STATE
// Activation state
Locked bool `theorydb:"attr:locked" json:"locked"`
// Bootstrap identity (public-only)
BootstrapUsername string `theorydb:"attr:bootstrapUsername" json:"bootstrap_username"`
BootstrapWalletAddress string `theorydb:"attr:bootstrapWalletAddress" json:"bootstrap_wallet_address,omitempty"`
// Setup progression
PrimaryAdminUsername string `theorydb:"attr:primaryAdminUsername" json:"primary_admin_username,omitempty"`
ActivatedAt *time.Time `theorydb:"attr:activatedAt" json:"activated_at,omitempty"`
// Audit timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceState represents instance activation/bootstrapping state stored in DynamoDB. This record is stage-scoped because each stage has its own DynamoDB table.
func NewDefaultInstanceState ¶
func NewDefaultInstanceState() *InstanceState
NewDefaultInstanceState returns the default locked instance state.
func (*InstanceState) BeforeCreate ¶
func (s *InstanceState) BeforeCreate() error
BeforeCreate sets defaults before creating the record.
func (*InstanceState) BeforeUpdate ¶
func (s *InstanceState) BeforeUpdate() error
BeforeUpdate updates timestamps and defaults before updating the record.
func (*InstanceState) GetPK ¶
func (s *InstanceState) GetPK() string
GetPK returns the partition key.
func (InstanceState) TableName ¶
func (InstanceState) TableName() string
TableName returns the DynamoDB table backing InstanceState.
func (*InstanceState) UpdateKeys ¶
func (s *InstanceState) UpdateKeys() error
UpdateKeys sets the fixed DynamoDB keys for the singleton state record.
type InstanceTimeseriesWindow ¶ added in v1.2.53
type InstanceTimeseriesWindow struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Type string `theorydb:"attr:type" json:"type"`
Instance string `theorydb:"attr:instance" json:"instance"`
Window string `theorydb:"attr:window" json:"window"`
CreatedAt string `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt string `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
InstanceTimeseriesWindow stores per-instance stream observation metadata for a time window.
func NewInstanceTimeseriesWindow ¶ added in v1.2.53
func NewInstanceTimeseriesWindow(instance string, window, now time.Time) *InstanceTimeseriesWindow
NewInstanceTimeseriesWindow builds the key envelope for an instance metrics window.
func (InstanceTimeseriesWindow) TableName ¶ added in v1.2.53
func (InstanceTimeseriesWindow) TableName() string
TableName returns the DynamoDB table backing InstanceTimeseriesWindow.
type InstanceTipsConfig ¶ added in v0.1.36
type InstanceTipsConfig struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Managed *InstanceTipsConfigManaged `theorydb:"attr:managed" json:"managed"`
Override *InstanceTipsConfigOverride `theorydb:"attr:override,omitempty" json:"override,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceTipsConfig stores instance-owned on-chain tipping configuration.
This record lives under PK="INSTANCE#CONFIG" and SK="TIPS_CONFIG".
func NewInstanceTipsConfig ¶ added in v0.1.36
func NewInstanceTipsConfig() *InstanceTipsConfig
NewInstanceTipsConfig creates a new tips config with built-in defaults.
func (*InstanceTipsConfig) GetPK ¶ added in v0.1.36
func (c *InstanceTipsConfig) GetPK() string
GetPK returns the partition key.
func (*InstanceTipsConfig) GetSK ¶ added in v0.1.36
func (c *InstanceTipsConfig) GetSK() string
GetSK returns the sort key.
func (InstanceTipsConfig) TableName ¶ added in v0.1.36
func (InstanceTipsConfig) TableName() string
TableName returns the DynamoDB table backing InstanceTipsConfig.
func (*InstanceTipsConfig) UpdateKeys ¶ added in v0.1.36
func (c *InstanceTipsConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceTipsConfigManaged ¶ added in v0.1.36
type InstanceTipsConfigManaged struct {
Enabled bool `theorydb:"attr:enabled" json:"enabled"`
ChainID int `theorydb:"attr:chainID" json:"chain_id"`
ContractAddress string `theorydb:"attr:contractAddress,omitempty" json:"contract_address,omitempty"`
}
InstanceTipsConfigManaged stores managed/default tips configuration values.
type InstanceTipsConfigOverride ¶ added in v0.1.36
type InstanceTipsConfigOverride struct {
Enabled *bool `theorydb:"attr:enabled,omitempty" json:"enabled,omitempty"`
ChainID *int `theorydb:"attr:chainID,omitempty" json:"chain_id,omitempty"`
ContractAddress *string `theorydb:"attr:contractAddress,omitempty" json:"contract_address,omitempty"`
}
InstanceTipsConfigOverride stores operator overrides for tips configuration values. Nil fields mean "no override".
type InstanceTipsConfigPatch ¶ added in v0.1.36
InstanceTipsConfigPatch is a merge-safe patch for the tips configuration layers.
type InstanceTranslationConfig ¶ added in v0.1.36
type InstanceTranslationConfig struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Managed *InstanceTranslationConfigManaged `theorydb:"attr:managed" json:"managed"`
Override *InstanceTranslationConfigOverride `theorydb:"attr:override,omitempty" json:"override,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceTranslationConfig stores instance-owned translation configuration.
This record lives under PK="INSTANCE#CONFIG" and SK="TRANSLATION_CONFIG".
func NewInstanceTranslationConfig ¶ added in v0.1.36
func NewInstanceTranslationConfig() *InstanceTranslationConfig
NewInstanceTranslationConfig creates a new translation config with built-in defaults.
func (*InstanceTranslationConfig) GetPK ¶ added in v0.1.36
func (c *InstanceTranslationConfig) GetPK() string
GetPK returns the partition key.
func (*InstanceTranslationConfig) GetSK ¶ added in v0.1.36
func (c *InstanceTranslationConfig) GetSK() string
GetSK returns the sort key.
func (InstanceTranslationConfig) TableName ¶ added in v0.1.36
func (InstanceTranslationConfig) TableName() string
TableName returns the DynamoDB table backing InstanceTranslationConfig.
func (*InstanceTranslationConfig) UpdateKeys ¶ added in v0.1.36
func (c *InstanceTranslationConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceTranslationConfigManaged ¶ added in v0.1.36
type InstanceTranslationConfigManaged struct {
Enabled bool `theorydb:"attr:enabled" json:"enabled"`
}
InstanceTranslationConfigManaged stores managed/default translation configuration values.
type InstanceTranslationConfigOverride ¶ added in v0.1.36
type InstanceTranslationConfigOverride struct {
Enabled *bool `theorydb:"attr:enabled,omitempty" json:"enabled,omitempty"`
}
InstanceTranslationConfigOverride stores operator overrides for translation configuration values. Nil fields mean "no override".
type InstanceTranslationConfigPatch ¶ added in v0.1.36
type InstanceTranslationConfigPatch struct {
Enabled *bool
}
InstanceTranslationConfigPatch is a merge-safe patch for the translation configuration layers.
type InstanceTrustConfig ¶ added in v0.1.36
type InstanceTrustConfig struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Managed *InstanceTrustConfigManaged `theorydb:"attr:managed" json:"managed"`
Override *InstanceTrustConfigOverride `theorydb:"attr:override,omitempty" json:"override,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceTrustConfig stores instance-owned trust configuration.
This record lives under PK="INSTANCE#CONFIG" and SK="TRUST_CONFIG".
func NewInstanceTrustConfig ¶ added in v0.1.36
func NewInstanceTrustConfig() *InstanceTrustConfig
NewInstanceTrustConfig creates a new trust config with built-in defaults.
func (*InstanceTrustConfig) GetPK ¶ added in v0.1.36
func (c *InstanceTrustConfig) GetPK() string
GetPK returns the partition key.
func (*InstanceTrustConfig) GetSK ¶ added in v0.1.36
func (c *InstanceTrustConfig) GetSK() string
GetSK returns the sort key.
func (InstanceTrustConfig) TableName ¶ added in v0.1.36
func (InstanceTrustConfig) TableName() string
TableName returns the DynamoDB table backing InstanceTrustConfig.
func (*InstanceTrustConfig) UpdateKeys ¶ added in v0.1.36
func (c *InstanceTrustConfig) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type InstanceTrustConfigManaged ¶ added in v0.1.36
type InstanceTrustConfigManaged struct {
BaseURL string `theorydb:"attr:baseURL,omitempty" json:"base_url,omitempty"`
AttestationsURL string `theorydb:"attr:attestationsURL,omitempty" json:"attestations_url,omitempty"`
InstanceKeySecretARN string `theorydb:"attr:instanceKeySecretARN,omitempty" json:"instance_key_secret_arn,omitempty"`
}
InstanceTrustConfigManaged stores managed/default trust configuration values.
type InstanceTrustConfigOverride ¶ added in v0.1.36
type InstanceTrustConfigOverride struct {
BaseURL *string `theorydb:"attr:baseURL,omitempty" json:"base_url,omitempty"`
AttestationsURL *string `theorydb:"attr:attestationsURL,omitempty" json:"attestations_url,omitempty"`
InstanceKeySecretARN *string `theorydb:"attr:instanceKeySecretARN,omitempty" json:"instance_key_secret_arn,omitempty"`
}
InstanceTrustConfigOverride stores operator overrides for trust configuration values. Nil fields mean "no override".
type InstanceTrustConfigPatch ¶ added in v0.1.36
type InstanceTrustConfigPatch struct {
BaseURL *string
AttestationsURL *string
InstanceKeySecretARN *string
}
InstanceTrustConfigPatch is a merge-safe patch for the trust configuration layers. Nil fields mean "no change".
type InstanceWellKnownLesserSoulAgent ¶ added in v0.1.36
type InstanceWellKnownLesserSoulAgent struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// ProofValue is served at `GET /.well-known/lesser-soul-agent` as:
// `{"lesser-soul-agent":"<token>"}`.
ProofValue string `theorydb:"attr:proofValue,omitempty" json:"proof_value,omitempty"`
// ExpiresAt gates responses so old proof tokens don't linger indefinitely.
ExpiresAt time.Time `theorydb:"attr:expiresAt,omitempty" json:"expires_at,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
InstanceWellKnownLesserSoulAgent stores the current HTTPS proof value served at GET /.well-known/lesser-soul-agent.
This record lives under PK="INSTANCE#CONFIG" and SK="WELL_KNOWN_LESSER_SOUL_AGENT".
func NewInstanceWellKnownLesserSoulAgent ¶ added in v0.1.36
func NewInstanceWellKnownLesserSoulAgent() *InstanceWellKnownLesserSoulAgent
NewInstanceWellKnownLesserSoulAgent creates a new record with built-in defaults.
func (*InstanceWellKnownLesserSoulAgent) GetPK ¶ added in v0.1.36
func (c *InstanceWellKnownLesserSoulAgent) GetPK() string
GetPK returns the partition key.
func (*InstanceWellKnownLesserSoulAgent) GetSK ¶ added in v0.1.36
func (c *InstanceWellKnownLesserSoulAgent) GetSK() string
GetSK returns the sort key.
func (InstanceWellKnownLesserSoulAgent) TableName ¶ added in v0.1.36
func (InstanceWellKnownLesserSoulAgent) TableName() string
TableName returns the DynamoDB table backing InstanceWellKnownLesserSoulAgent.
func (*InstanceWellKnownLesserSoulAgent) UpdateKeys ¶ added in v0.1.36
func (c *InstanceWellKnownLesserSoulAgent) UpdateKeys() error
UpdateKeys updates the DynamoDB keys.
type Like ¶
type Like struct {
// Primary key - by object and actor (to prevent duplicate likes)
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "object#{object_id}#likes"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "actor#{actor_id}"
// GSI1 - by actor (to list user's likes)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "actor#{actor_id}#likes"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{object_id}"
// Like data
ID string `theorydb:"attr:id" json:"id"` // Like activity ID
Actor string `theorydb:"attr:actor" json:"actor"` // Who liked (actor URL)
Object string `theorydb:"attr:object" json:"object"` // What was liked (object URL)
StatusAuthorID string `theorydb:"attr:statusAuthorID" json:"status_author_id"` // Author of the status being liked
Published time.Time `theorydb:"attr:published" json:"published"` // When it was liked
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When stored in DB
// contains filtered or unexported fields
}
Like represents a Like activity in DynamoDB
func (*Like) GetStatusAuthorID ¶
GetStatusAuthorID returns the author of the status being liked
func (*Like) GetStatusID ¶
GetStatusID returns the object that was liked (status)
func (*Like) UpdateKeys ¶
UpdateKeys updates the primary and GSI keys based on current field values This ensures consistency when Actor, Object, or timestamps change
type LinkMetadata ¶
type LinkMetadata struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // LINK#{url}
SK string `theorydb:"sk,attr:SK" json:"-"` // METADATA
// Attributes from interface
URL string `theorydb:"attr:url" json:"url"`
Title string `theorydb:"attr:title" json:"title"`
Description string `theorydb:"attr:description" json:"description"`
Image string `theorydb:"attr:image" json:"image"`
Domain string `theorydb:"attr:domain" json:"domain"`
// Additional metadata
FetchedAt time.Time `theorydb:"attr:fetchedAt" json:"fetched_at"`
LastAccessed time.Time `theorydb:"attr:lastAccessed" json:"last_accessed"`
AccessCount int64 `theorydb:"attr:accessCount" json:"access_count"`
ContentType string `theorydb:"attr:contentType" json:"content_type,omitempty"` // MIME type
Language string `theorydb:"attr:language" json:"language,omitempty"` // Detected language
Author string `theorydb:"attr:author" json:"author,omitempty"` // Article author if available
PublishedAt *time.Time `theorydb:"attr:publishedAt" json:"published_at,omitempty"` // Publication date if available
Keywords []string `theorydb:"attr:keywords" json:"keywords,omitempty"` // SEO keywords
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 30 days cache
// contains filtered or unexported fields
}
LinkMetadata represents metadata about a link
func NewLinkMetadata ¶
func NewLinkMetadata(linkURL string) *LinkMetadata
NewLinkMetadata creates a new link metadata entry
func (*LinkMetadata) GetDisplayDomain ¶
func (l *LinkMetadata) GetDisplayDomain() string
GetDisplayDomain returns a cleaned domain name for display
func (*LinkMetadata) HasImage ¶
func (l *LinkMetadata) HasImage() bool
HasImage returns true if the link has an associated image
func (*LinkMetadata) IsStale ¶
func (l *LinkMetadata) IsStale(maxAge time.Duration) bool
IsStale checks if the metadata should be refreshed
func (*LinkMetadata) RecordAccess ¶
func (l *LinkMetadata) RecordAccess()
RecordAccess updates access tracking information
func (*LinkMetadata) SanitizeMetadata ¶
func (l *LinkMetadata) SanitizeMetadata()
SanitizeMetadata cleans up the metadata fields
func (*LinkMetadata) SetFromOpenGraph ¶
func (l *LinkMetadata) SetFromOpenGraph(ogTitle, ogDescription, ogImage string)
SetFromOpenGraph sets metadata from OpenGraph tags
func (*LinkMetadata) SetFromTwitterCard ¶
func (l *LinkMetadata) SetFromTwitterCard(twitterTitle, twitterDescription, twitterImage string)
SetFromTwitterCard sets metadata from Twitter Card tags
func (LinkMetadata) TableName ¶
func (LinkMetadata) TableName() string
TableName returns the DynamoDB table backing LinkMetadata.
func (*LinkMetadata) TruncateDescription ¶
func (l *LinkMetadata) TruncateDescription(maxLength int)
TruncateDescription ensures description doesn't exceed a reasonable length
func (*LinkMetadata) UpdateKeys ¶
func (l *LinkMetadata) UpdateKeys()
UpdateKeys updates the partition and sort keys
type LinkShare ¶
type LinkShare struct {
// contains filtered or unexported fields
}
LinkShare tracks when links are shared in statuses
func (*LinkShare) UpdateKeys ¶
UpdateKeys updates GSI keys for LinkShare - no GSIs needed for this model
type LinkTrend ¶
type LinkTrend struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"`
URL string `theorydb:"attr:url" json:"url"`
Title string `theorydb:"attr:title" json:"title"`
Description string `theorydb:"attr:description" json:"description"`
Type string `theorydb:"attr:type" json:"type"` // "link", "video", "photo"
AuthorName string `theorydb:"attr:authorName" json:"author_name"`
Image string `theorydb:"attr:image" json:"image"`
TrendScore float64 `theorydb:"attr:trendScore" json:"trend_score"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
LinkTrend represents a trending link
func (*LinkTrend) UpdateKeys ¶
UpdateKeys updates the GSI keys for link trend
type List ¶
type List struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // LIST#listID
SK string `theorydb:"sk,attr:SK" json:"SK"` // METADATA
// GSI1 for user's lists index
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK,omitempty"` // USER_LISTS#username
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"` // listID
// Core fields from legacy
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"` // Owner of the list
Title string `theorydb:"attr:title" json:"title"`
RepliesPolicy string `theorydb:"attr:repliesPolicy" json:"replies_policy"` // list, followed, none
Exclusive bool `theorydb:"attr:exclusive" json:"exclusive"` // Whether list is exclusive
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
List represents a user-created list for organizing followed accounts
func (*List) BeforeCreate ¶
BeforeCreate sets up the keys before creating
func (*List) BeforeUpdate ¶
BeforeUpdate sets the updated timestamp
func (*List) UpdateKeys ¶
UpdateKeys updates the GSI keys based on current field values
type ListMember ¶
type ListMember struct {
// Primary keys for list membership
PK string `theorydb:"pk,attr:PK" json:"PK"` // LIST_MEMBERS#listID
SK string `theorydb:"sk,attr:SK" json:"SK"` // accountID
// GSI1 for reverse lookup (what lists is an account in)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK,omitempty"` // ACCOUNT_LISTS#accountID
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"` // listID#username
// Core fields
ListID string `theorydb:"attr:listID" json:"list_id"`
AccountID string `theorydb:"attr:accountID" json:"account_id"`
ListUsername string `theorydb:"attr:listUsername" json:"list_username"` // Owner of the list (for reverse index)
AddedAt time.Time `theorydb:"attr:addedAt" json:"added_at"`
// contains filtered or unexported fields
}
ListMember represents membership of an account in a list
func (*ListMember) BeforeCreate ¶
func (lm *ListMember) BeforeCreate() error
BeforeCreate sets up the keys before creating
func (*ListMember) GetPK ¶
func (lm *ListMember) GetPK() string
GetPK returns the partition key (required by BaseModel)
func (*ListMember) GetSK ¶
func (lm *ListMember) GetSK() string
GetSK returns the sort key (required by BaseModel)
func (ListMember) TableName ¶
func (ListMember) TableName() string
TableName returns the DynamoDB table name
func (*ListMember) UpdateKeys ¶
func (lm *ListMember) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type LoginAttempt ¶
type LoginAttempt struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // RATELIMIT#{identifier}
SK string `theorydb:"sk,attr:SK" json:"sk"` // timestamp in RFC3339Nano format
// Attributes
Type string `theorydb:"attr:type" json:"type"` // "LoginAttempt"
Success bool `theorydb:"attr:success" json:"success"` // whether the login was successful
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // when the attempt occurred
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // automatic cleanup after 24 hours
// contains filtered or unexported fields
}
LoginAttempt represents a login attempt record for rate limiting
func NewLoginAttempt ¶
func NewLoginAttempt(identifier string, success bool) *LoginAttempt
NewLoginAttempt creates a new LoginAttempt record
func (*LoginAttempt) GetPK ¶
func (la *LoginAttempt) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*LoginAttempt) GetSK ¶
func (la *LoginAttempt) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (LoginAttempt) TableName ¶
func (LoginAttempt) TableName() string
TableName returns the DynamoDB table name for login attempts
func (*LoginAttempt) UpdateKeys ¶
func (la *LoginAttempt) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the LoginAttempt model
type MLPollRequest ¶
type MLPollRequest struct {
// Primary key - Poll requests
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLPOLL#{job_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "REQUEST#{timestamp}"
// GSI1 - Status queries (for finding pending polls)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "MLPOLL#PENDING"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_POLL_REQUEST"
// Poll fields
JobID string `theorydb:"attr:jobID" json:"job_id"` // Bedrock job ARN
JobName string `theorydb:"attr:jobName" json:"job_name"` // Human-readable job name
Attempt int `theorydb:"attr:attempt" json:"attempt"` // Poll attempt number
MaxAttempts int `theorydb:"attr:maxAttempts" json:"max_attempts"` // Maximum poll attempts
NextPollAfter time.Time `theorydb:"attr:nextPollAfter" json:"next_poll_after"` // When to poll next
Status string `theorydb:"attr:status" json:"status"` // PENDING, PROCESSING, COMPLETED, FAILED
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// DynamoDB TTL (poll requests expire after completion or timeout)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MLPollRequest tracks pending status checks for training jobs
func (*MLPollRequest) GetPK ¶
func (m *MLPollRequest) GetPK() string
GetPK returns the primary partition key
func (*MLPollRequest) GetSK ¶
func (m *MLPollRequest) GetSK() string
GetSK returns the primary sort key
func (MLPollRequest) TableName ¶
func (MLPollRequest) TableName() string
TableName returns the DynamoDB table name
func (*MLPollRequest) UpdateKeys ¶
func (m *MLPollRequest) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type MLPrediction ¶
type MLPrediction struct {
// Primary key - Predictions by object
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLPRED#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{RFC3339}#{prediction_id}"
// GSI1 - Model version queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "MODEL#{model_version}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Human label queries (for validation)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "REVIEW#{reviewed}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "TIME#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_PREDICTION"
// Prediction fields
PredictionID string `theorydb:"attr:predictionID" json:"prediction_id"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
ObjectType string `theorydb:"attr:objectType" json:"object_type"`
ModelVersion string `theorydb:"attr:modelVersion" json:"model_version"`
PredictedLabel string `theorydb:"attr:predictedLabel" json:"predicted_label"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
HumanLabel string `theorydb:"attr:humanLabel" json:"human_label"` // Set when human reviews
Reviewed bool `theorydb:"attr:reviewed" json:"reviewed"` // Whether human has reviewed
ReviewedBy string `theorydb:"attr:reviewedBy" json:"reviewed_by"` // Who reviewed
ReviewedAt time.Time `theorydb:"attr:reviewedAt" json:"reviewed_at"` // When reviewed
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
// DynamoDB TTL (predictions can expire after 90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
MLPrediction tracks ML model inference predictions for effectiveness metrics
func (*MLPrediction) GetPK ¶
func (m *MLPrediction) GetPK() string
GetPK returns the primary partition key
func (*MLPrediction) GetSK ¶
func (m *MLPrediction) GetSK() string
GetSK returns the primary sort key
func (MLPrediction) TableName ¶
func (MLPrediction) TableName() string
TableName returns the DynamoDB table name
func (*MLPrediction) UpdateKeys ¶
func (m *MLPrediction) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type Marker ¶
type Marker struct {
// Primary key - matches legacy pattern exactly
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "USER#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "MARKER#{timeline}"
// Timeline marker data - matches legacy MarkerRecord exactly
LastReadID string `theorydb:"attr:lastReadID" json:"LastReadID"` // Preserve exact case from legacy
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"UpdatedAt"` // Preserve exact case from legacy
Version int `theorydb:"attr:version" json:"Version"` // Preserve exact case from legacy
// Internal fields for DynamORM operations
Username string `theorydb:"attr:username" json:"username"` // Extracted from PK for convenience
Timeline string `theorydb:"attr:timeline" json:"timeline"` // Extracted from SK for convenience
// contains filtered or unexported fields
}
Marker represents a timeline position marker stored in DynamoDB using DynamORM Tracks user's last read positions for various timelines (home, notifications, etc.)
func (*Marker) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Marker) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Marker) UpdateKeys ¶
UpdateKeys updates the primary key fields based on username and timeline This method allows for key updates when username or timeline changes
type Media ¶
type Media struct {
// Primary key - using media ID as partition key with version as sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "media#{mediaID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "version#{version}"
// GSI1 - User media lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USER_MEDIA#{userID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{uploaded_at}#{mediaID}"
// GSI2 - Status-based queries (pending, processing, ready, failed)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "MEDIA_STATUS#{status}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{uploaded_at}#{mediaID}"
// GSI3 - Content type queries
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "CONTENT_TYPE#{content_type}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{uploaded_at}#{mediaID}"
// Core media data
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
Version string `theorydb:"attr:version" json:"version"` // "original", "v1", "v2", etc.
UserID string `theorydb:"attr:userID" json:"user_id"` // Owner of the media
FileName string `theorydb:"attr:fileName" json:"file_name"` // Original filename
ContentType string `theorydb:"attr:contentType" json:"content_type"` // MIME type
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // Size in bytes
ContentHash string `theorydb:"attr:contentHash,omitempty" json:"-"` // Canonical sha256:<hex> digest of original bytes
// Storage details
S3Bucket string `theorydb:"attr:s3Bucket" json:"s3_bucket"`
S3Key string `theorydb:"attr:s3Key" json:"s3_key"`
CDNUrl string `theorydb:"attr:cdnUrl" json:"cdn_url,omitempty"`
// Processing status
Status string `theorydb:"attr:status" json:"status"` // "pending", "processing", "ready", "failed"
ProcessedAt *time.Time `theorydb:"attr:processedAt" json:"processed_at,omitempty"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
// Media analysis results
Width int `theorydb:"attr:width" json:"width,omitempty"` // For images/videos
Height int `theorydb:"attr:height" json:"height,omitempty"` // For images/videos
Duration int `theorydb:"attr:duration" json:"duration,omitempty"` // For videos/audio in seconds
Blurhash string `theorydb:"attr:blurhash" json:"blurhash,omitempty"` // For images
// Media variants (thumbnails, different sizes, formats)
Variants map[string]MediaVariant `theorydb:"attr:variants" json:"variants,omitempty"`
// Media metadata for Mastodon API compatibility
Description string `theorydb:"attr:description" json:"description,omitempty"` // Alt text description
Focus string `theorydb:"attr:focus" json:"focus,omitempty"` // Focus point for cropping (x,y)
SpoilerText string `theorydb:"attr:spoilerText" json:"spoiler_text,omitempty"`
// Content moderation
IsNSFW bool `theorydb:"attr:isNSFW" json:"is_nsfw"`
ModerationScore float64 `theorydb:"attr:moderationScore" json:"moderation_score"` // 0.0 - 1.0
Labels []string `theorydb:"attr:labels" json:"labels,omitempty"` // Content labels from moderation
// Client-provided classification (image/video/gifv/etc.)
MediaCategory MediaCategory `theorydb:"attr:mediaCategory" json:"media_category,omitempty"`
// Editorial state is optional so historical and social media retain the
// existing public posture. Internal assets never expose CDNUrl through the
// application contract and carry private provenance separately from credits.
Visibility MediaVisibility `theorydb:"attr:visibility,omitempty" json:"visibility,omitempty"`
Provenance *MediaProvenance `theorydb:"attr:provenance,omitempty" json:"provenance,omitempty"`
// Editorial lifecycle and durable published serving. These are editorial
// concerns distinct from the processing Status enum and from the public
// CDNUrl minted for social media at upload. PublishedURL is minted exactly
// once at the publish transition and serves the approved original bytes.
EditorialState EditorialLifecycle `theorydb:"attr:editorialState,omitempty" json:"editorial_state,omitempty"`
SupersededByMediaID string `theorydb:"attr:supersededByMediaID,omitempty" json:"superseded_by_media_id,omitempty"`
PublishedS3Key string `theorydb:"attr:publishedS3Key,omitempty" json:"published_s3_key,omitempty"`
PublishedURL string `theorydb:"attr:publishedURL,omitempty" json:"published_url,omitempty"`
PublishedAt *time.Time `theorydb:"attr:publishedAt,omitempty" json:"published_at,omitempty"`
// Usage tracking
UsageCount int `theorydb:"attr:usageCount" json:"usage_count"`
LastUsedAt *time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at,omitempty"`
// Timestamps
UploadedAt time.Time `theorydb:"attr:uploadedAt" json:"uploaded_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for unused media (30 days)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at,omitempty"` // Unix timestamp
// Version for optimistic locking
ModelVersion int `theorydb:"version,attr:modelVersion" json:"model_version"`
// contains filtered or unexported fields
}
Media represents a media file (image, video, audio) stored in the system
func (*Media) AddVariant ¶
func (m *Media) AddVariant(name string, variant MediaVariant)
AddVariant adds a processed variant to the media
func (*Media) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Media) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Media) EditorialLifecycleAvailableForPublish ¶ added in v1.6.23
EditorialLifecycleAvailableForPublish reports whether the asset may serve as a required bound asset at the publish gate. Withdrawn, superseded, and unavailable assets fail closed; the empty lifecycle is the default available state for assets created before the M2 lifecycle surface existed.
func (*Media) GetAvailableVariants ¶
GetAvailableVariants returns a list of all available variant names
func (*Media) GetBestVariant ¶
func (m *Media) GetBestVariant(maxWidth, maxHeight int) MediaVariant
GetBestVariant returns the best variant for the requested dimensions
func (*Media) GetTotalSize ¶
GetTotalSize returns the total size including all variants
func (*Media) GetVariant ¶
func (m *Media) GetVariant(name string) (MediaVariant, bool)
GetVariant retrieves a specific variant by name
func (*Media) IsInternalEditorial ¶ added in v1.6.23
IsInternalEditorial reports whether the asset is restricted to the CMS owner and exact draft-review grants.
func (*Media) IsProcessing ¶
IsProcessing returns true if the media is currently being processed
func (*Media) IsPublished ¶ added in v1.6.23
IsPublished reports whether the publish transition has minted durable public serving for this asset's exact approved bytes.
func (*Media) MarkUsed ¶
func (m *Media) MarkUsed()
MarkUsed increments usage count and removes expiry for used media
func (*Media) SetModeration ¶
SetModeration sets moderation results
func (*Media) SetProcessed ¶
func (m *Media) SetProcessed()
SetProcessed marks the media as successfully processed
func (*Media) SetProcessing ¶
func (m *Media) SetProcessing()
SetProcessing marks the media as currently being processed
func (*Media) UpdateKeys ¶
UpdateKeys ensures all key fields are properly set
type MediaAnalytics ¶
type MediaAnalytics struct {
// DynamoDB Keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // MEDIA_ANALYTICS#{format} or MANIFEST#{format}
SK string `theorydb:"sk,attr:SK" json:"sk"` // {timestamp}#{mediaID} or {date}#{mediaID}
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // DATE#{date}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {format}#{timestamp}
// GSI2 for variant-level queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk"` // VARIANT#{variant_key}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk"` // COST#{timestamp}
// Business fields
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
Format string `theorydb:"attr:format" json:"format"` // hls, dash
Duration float64 `theorydb:"attr:duration" json:"duration"` // Media duration in seconds
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When the event occurred
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD for daily aggregation
// Metadata
EventType string `theorydb:"attr:eventType" json:"event_type,omitempty"` // manifest_generated, quality_changed, etc.
UserID string `theorydb:"attr:userID" json:"user_id,omitempty"` // User requesting the manifest
Quality string `theorydb:"attr:quality" json:"quality,omitempty"` // Video quality if applicable
// NEW: Variant-level cost metrics (all costs in microdollars)
VariantCosts map[string]MediaVariantCost `theorydb:"attr:variantCosts" json:"variant_costs"` // Per-variant cost breakdown
TotalVariantCost int64 `theorydb:"attr:totalVariantCost" json:"total_variant_cost"` // Sum of all variant costs
DominantVariant string `theorydb:"attr:dominantVariant" json:"dominant_variant"` // Most expensive variant
// NEW: Processing cost breakdown by service
MediaConvertCost int64 `theorydb:"attr:mediaConvertCost" json:"mediaconvert_cost"` // MediaConvert processing costs
S3StorageCost int64 `theorydb:"attr:s3StorageCost" json:"s3_storage_cost"` // S3 storage costs for variants
CloudFrontCost int64 `theorydb:"attr:cloudFrontCost" json:"cloudfront_cost"` // CDN delivery costs
LambdaCost int64 `theorydb:"attr:lambdaCost" json:"lambda_cost"` // Lambda processing costs
RekognitionCost int64 `theorydb:"attr:rekognitionCost" json:"rekognition_cost"` // Content analysis costs
// NEW: Bandwidth and streaming metrics
TotalBandwidthBytes int64 `theorydb:"attr:totalBandwidthBytes" json:"total_bandwidth_bytes"` // Total bytes delivered
VariantBandwidth map[string]int64 `theorydb:"attr:variantBandwidth" json:"variant_bandwidth"` // Bytes per variant
StreamingSessions int `theorydb:"attr:streamingSessions" json:"streaming_sessions"` // Number of active sessions
QualityDistribution map[string]int `theorydb:"attr:qualityDistribution" json:"quality_distribution"` // Viewer count per quality
// NEW: Performance metrics per variant
VariantLatency map[string]int64 `theorydb:"attr:variantLatency" json:"variant_latency"` // Response time per variant (ms)
VariantErrorRate map[string]float64 `theorydb:"attr:variantErrorRate" json:"variant_error_rate"` // Error rate per variant
VariantCacheHitRate map[string]float64 `theorydb:"attr:variantCacheHitRate" json:"variant_cache_hit_rate"` // CDN cache hit rate per variant
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MediaAnalytics tracks media streaming analytics with variant-level cost attribution
func (*MediaAnalytics) AddQualityViewer ¶
func (m *MediaAnalytics) AddQualityViewer(quality string)
AddQualityViewer tracks a viewer switching to a specific quality
func (*MediaAnalytics) AddVariantCost ¶
func (m *MediaAnalytics) AddVariantCost(resolution, codec string, bitrate int, cost MediaVariantCost)
AddVariantCost adds cost tracking for a specific media variant
func (*MediaAnalytics) GetCostEfficiencyMetrics ¶
func (m *MediaAnalytics) GetCostEfficiencyMetrics() map[string]interface{}
GetCostEfficiencyMetrics returns cost efficiency metrics per variant
func (*MediaAnalytics) GetMostPopularQuality ¶
func (m *MediaAnalytics) GetMostPopularQuality() (string, int)
GetMostPopularQuality returns the quality with the most viewers
func (*MediaAnalytics) GetPK ¶
func (m *MediaAnalytics) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*MediaAnalytics) GetSK ¶
func (m *MediaAnalytics) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*MediaAnalytics) RemoveQualityViewer ¶
func (m *MediaAnalytics) RemoveQualityViewer(quality string)
RemoveQualityViewer tracks a viewer leaving a specific quality
func (*MediaAnalytics) SetGeneralEvent ¶
func (m *MediaAnalytics) SetGeneralEvent(eventType, mediaID, userID string)
SetGeneralEvent configures this record for general media events
func (*MediaAnalytics) SetManifestGeneration ¶
func (m *MediaAnalytics) SetManifestGeneration(mediaID, format string, duration float64)
SetManifestGeneration configures this record for manifest generation tracking
func (*MediaAnalytics) SetQualityChange ¶
func (m *MediaAnalytics) SetQualityChange(mediaID, userID, _, newQuality string)
SetQualityChange configures this record for quality change tracking
func (MediaAnalytics) TableName ¶
func (MediaAnalytics) TableName() string
TableName returns the DynamoDB table backing MediaAnalytics.
func (*MediaAnalytics) TrackVariantDelivery ¶
func (m *MediaAnalytics) TrackVariantDelivery(variantKey string, bytes int64, latencyMs int64, cacheHit bool, success bool)
TrackVariantDelivery tracks delivery metrics for a specific variant
func (*MediaAnalytics) UpdateKeys ¶
func (m *MediaAnalytics) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type MediaAttachment ¶
type MediaAttachment struct {
// Primary composite key - flexible to support different entity types
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format varies by entity type
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "MEDIA#{mediaID}"
// Entity identifiers
EntityType string `theorydb:"attr:entityType" json:"entity_type"` // "user", "scheduled_status", etc.
EntityID string `theorydb:"attr:entityID" json:"entity_id"` // Username, status ID, etc.
MediaID string `theorydb:"attr:mediaID" json:"media_id"` // The attached media ID
// Media metadata (denormalized for quick access)
MediaType string `theorydb:"attr:mediaType" json:"media_type"` // "image", "video", "audio"
ContentType string `theorydb:"attr:contentType" json:"content_type"` // Full MIME type
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // Size in bytes
// Display metadata
Description string `theorydb:"attr:description" json:"description,omitempty"` // Alt text or description
FocalPoint string `theorydb:"attr:focalPoint" json:"focal_point,omitempty"` // Focal point for cropping (x,y format)
Order int `theorydb:"attr:order" json:"order"` // Display order when multiple attachments
// Timestamps
AttachedAt time.Time `theorydb:"attr:attachedAt" json:"attached_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
MediaAttachment represents the association between media files and their parent entities (users, scheduled statuses, etc.) This model handles the relationships where media is attached to different types of entities
func (*MediaAttachment) BeforeCreate ¶
func (m *MediaAttachment) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*MediaAttachment) BeforeUpdate ¶
func (m *MediaAttachment) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*MediaAttachment) GetFocalPoint ¶
func (m *MediaAttachment) GetFocalPoint() (x, y float64, ok bool)
GetFocalPoint returns the focal point coordinates
func (*MediaAttachment) IsForScheduledStatus ¶
func (m *MediaAttachment) IsForScheduledStatus() bool
IsForScheduledStatus returns true if this attachment is for a scheduled status
func (*MediaAttachment) IsForUser ¶
func (m *MediaAttachment) IsForUser() bool
IsForUser returns true if this attachment is for a user
func (*MediaAttachment) SetFocalPoint ¶
func (m *MediaAttachment) SetFocalPoint(x, y float64)
SetFocalPoint sets the focal point for image cropping
func (MediaAttachment) TableName ¶
func (MediaAttachment) TableName() string
TableName returns the DynamoDB table name
func (*MediaAttachment) UpdateKeys ¶
func (m *MediaAttachment) UpdateKeys(entityType, entityID string)
UpdateKeys updates the primary key based on entity type and ID
func (*MediaAttachment) Validate ¶
func (m *MediaAttachment) Validate() error
Validate performs validation on the MediaAttachment
type MediaCategory ¶
type MediaCategory string
MediaCategory represents the high-level category for a media attachment.
const ( MediaCategoryImage MediaCategory = "image" MediaCategoryVideo MediaCategory = "video" MediaCategoryAudio MediaCategory = "audio" MediaCategoryGifv MediaCategory = "gifv" MediaCategoryDocument MediaCategory = "document" MediaCategoryUnknown MediaCategory = "unknown" )
Media category constants define the canonical classifications for stored media.
func DetermineMediaCategory ¶
func DetermineMediaCategory(contentType string) MediaCategory
DetermineMediaCategory derives a category from the MIME type when none is provided.
func NormalizeMediaCategory ¶
func NormalizeMediaCategory(category string) (MediaCategory, bool)
NormalizeMediaCategory converts arbitrary input into a canonical media category value. The boolean return indicates whether the provided category was recognized.
type MediaJob ¶
type MediaJob struct {
// Primary key - using job ID
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "JOB#{jobID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "JOB#{jobID}"
// GSI1 - User jobs lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USER_JOBS#{userID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{created_at}#{jobID}"
// GSI2 - Status-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "STATUS#{status}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "UPDATED#{updated_at}"
// Core job data
JobID string `theorydb:"attr:jobID" json:"job_id"`
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
Username string `theorydb:"attr:username" json:"username"`
Status string `theorydb:"attr:status" json:"status"` // pending, processing, completed, failed, cancelled
ProcessingTasks []string `theorydb:"attr:processingTasks" json:"processing_tasks"`
S3Key string `theorydb:"attr:s3Key" json:"s3_key"`
MimeType string `theorydb:"attr:mimeType" json:"mime_type"`
Results map[string]any `theorydb:"attr:results" json:"results,omitempty"`
Error string `theorydb:"attr:error" json:"error,omitempty"`
// Idempotency and duplicate prevention
IdempotencyKey string `theorydb:"attr:idempotencyKey" json:"idempotency_key"` // Hash of user_id + file_hash + timestamp
FileHash string `theorydb:"attr:fileHash" json:"file_hash"` // SHA256 hash of file contents
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // File size in bytes
// Processing state tracking
StartedAt *time.Time `theorydb:"attr:startedAt" json:"started_at,omitempty"` // When processing actually began
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"` // When processing completed
LastAttemptAt *time.Time `theorydb:"attr:lastAttemptAt" json:"last_attempt_at,omitempty"` // Last retry attempt
Progress int `theorydb:"attr:progress" json:"progress"` // Progress percentage (0-100)
// Retry logic
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"` // Number of retries attempted
MaxRetries int `theorydb:"attr:maxRetries" json:"max_retries"` // Maximum retries allowed
LastError string `theorydb:"attr:lastError" json:"last_error,omitempty"` // Last error encountered
RetryScheduledAt *time.Time `theorydb:"attr:retryScheduledAt" json:"retry_scheduled_at,omitempty"` // When next retry is scheduled
// Budget and timeout enforcement
EstimatedCostMicros int64 `theorydb:"attr:estimatedCostMicros" json:"estimated_cost_micros"` // Estimated processing cost
ActualCostMicros int64 `theorydb:"attr:actualCostMicros" json:"actual_cost_micros"` // Actual cost incurred
MaxProcessingTime time.Duration `theorydb:"attr:maxProcessingTime" json:"max_processing_time"` // Maximum allowed processing time
ProcessingStartedAt *time.Time `theorydb:"attr:processingStartedAt" json:"processing_started_at,omitempty"` // When current processing attempt started
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for abandoned jobs (24 hours)
ExpiresAt *int64 `theorydb:"ttl,attr:ttl" json:"expires_at,omitempty"` // Unix timestamp
// Version for optimistic locking
ModelVersion int `theorydb:"version,attr:modelVersion" json:"model_version"`
// contains filtered or unexported fields
}
MediaJob represents a media processing job in the system
func (*MediaJob) AddProcessingTask ¶
AddProcessingTask adds a task to the processing tasks list
func (*MediaJob) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*MediaJob) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*MediaJob) CanRetry ¶
CanRetry determines if the job can be retried based on error type and retry count
func (*MediaJob) GenerateIdempotencyKey ¶
GenerateIdempotencyKey creates an idempotency key from user, file hash, and timestamp
func (*MediaJob) GetProcessingDuration ¶
GetProcessingDuration returns how long the job has been processing
func (*MediaJob) GetRemainingProcessingTime ¶
GetRemainingProcessingTime returns remaining processing time before timeout
func (*MediaJob) HasProcessingTask ¶
HasProcessingTask checks if a specific task is in the processing tasks
func (*MediaJob) IsAbandoned ¶
IsAbandoned checks if the job has been abandoned (no updates for too long)
func (*MediaJob) IsBudgetExceeded ¶
IsBudgetExceeded checks if processing has exceeded time budget
func (*MediaJob) IsCancelled ¶
IsCancelled returns true if the job is cancelled
func (*MediaJob) IsCompleted ¶
IsCompleted returns true if the job is completed
func (*MediaJob) IsProcessing ¶
IsProcessing returns true if the job is processing
func (*MediaJob) IsReadyForRetry ¶
IsReadyForRetry checks if job is ready to be retried
func (*MediaJob) IsRetryableError ¶
IsRetryableError determines if an error is retryable
func (*MediaJob) ScheduleRetry ¶
ScheduleRetry schedules the next retry with exponential backoff
func (*MediaJob) SetCancelled ¶
SetCancelled marks the job as cancelled
func (*MediaJob) SetCompleted ¶
SetCompleted marks the job as completed with results
func (*MediaJob) SetProcessing ¶
func (mj *MediaJob) SetProcessing()
SetProcessing marks the job as processing
func (*MediaJob) UpdateKeys ¶
UpdateKeys sets up all the composite keys (BaseModel interface implementation)
func (*MediaJob) UpdateProgress ¶
UpdateProgress updates the job progress percentage
type MediaMetadata ¶
type MediaMetadata struct {
// Primary keys following legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // MEDIA#{mediaID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // METADATA
// GSI keys for queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // STATUS#{status}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // PROCESSED#{timestamp}
// Media identification
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
// Basic metadata
OriginalURL string `theorydb:"attr:originalURL" json:"original_url,omitempty"`
Duration float64 `theorydb:"attr:duration" json:"duration"` // Duration in seconds
Width int `theorydb:"attr:width" json:"width"` // Video width in pixels
Height int `theorydb:"attr:height" json:"height"` // Video height in pixels
Bitrate int `theorydb:"attr:bitrate" json:"bitrate"` // Bitrate in kbps
FileSize int64 `theorydb:"attr:fileSize" json:"file_size"` // Size in bytes
Blurhash string `theorydb:"attr:blurhash" json:"blurhash,omitempty"` // Blurhash for images/video thumbnails
ProcessedAt time.Time `theorydb:"attr:processedAt" json:"processed_at"` // When processing completed
AvailableQualities []string `theorydb:"attr:availableQualities" json:"available_qualities"` // Available quality levels
Status string `theorydb:"attr:status" json:"status"` // pending, processing, complete, failed
// Codec information for HLS/DASH manifest generation
VideoCodec string `theorydb:"attr:videoCodec" json:"video_codec,omitempty"` // e.g., "avc1.640028"
AudioCodec string `theorydb:"attr:audioCodec" json:"audio_codec,omitempty"` // e.g., "mp4a.40.2"
VideoProfile string `theorydb:"attr:videoProfile" json:"video_profile,omitempty"` // e.g., "High", "Main", "Baseline"
VideoLevel string `theorydb:"attr:videoLevel" json:"video_level,omitempty"` // e.g., "4.0", "3.1"
QualitySettings map[string]QualityCodecInfo `theorydb:"attr:qualitySettings" json:"quality_settings,omitempty"` // Per-quality codec info
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for cleanup of failed/temporary media
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MediaMetadata represents metadata about media files stored in S3 This model handles the DynamoDB storage of metadata while S3 handles actual file storage
func (*MediaMetadata) AddQuality ¶
func (m *MediaMetadata) AddQuality(quality string)
AddQuality adds a quality level to the available qualities
func (*MediaMetadata) BeforeCreate ¶
func (m *MediaMetadata) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*MediaMetadata) BeforeUpdate ¶
func (m *MediaMetadata) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*MediaMetadata) GetCodecInfo ¶
func (m *MediaMetadata) GetCodecInfo(quality string) (QualityCodecInfo, bool)
GetCodecInfo returns codec information for a specific quality
func (*MediaMetadata) GetPK ¶
func (m *MediaMetadata) GetPK() string
GetPK returns the partition key (required by BaseModel)
func (*MediaMetadata) GetSK ¶
func (m *MediaMetadata) GetSK() string
GetSK returns the sort key (required by BaseModel)
func (*MediaMetadata) HasQuality ¶
func (m *MediaMetadata) HasQuality(quality string) bool
HasQuality returns true if the specified quality is available
func (*MediaMetadata) IsComplete ¶
func (m *MediaMetadata) IsComplete() bool
IsComplete returns true if the media processing is complete
func (*MediaMetadata) IsFailed ¶
func (m *MediaMetadata) IsFailed() bool
IsFailed returns true if the media processing failed
func (*MediaMetadata) IsPending ¶
func (m *MediaMetadata) IsPending() bool
IsPending returns true if the media is pending processing
func (*MediaMetadata) IsProcessing ¶
func (m *MediaMetadata) IsProcessing() bool
IsProcessing returns true if the media is currently being processed
func (*MediaMetadata) SetCodecInfo ¶
func (m *MediaMetadata) SetCodecInfo(quality string, info QualityCodecInfo)
SetCodecInfo sets codec information for a specific quality
func (*MediaMetadata) SetComplete ¶
func (m *MediaMetadata) SetComplete()
SetComplete marks the media as processing complete
func (*MediaMetadata) SetFailed ¶
func (m *MediaMetadata) SetFailed()
SetFailed marks the media as processing failed
func (*MediaMetadata) SetProcessing ¶
func (m *MediaMetadata) SetProcessing()
SetProcessing marks the media as being processed
func (MediaMetadata) TableName ¶
func (MediaMetadata) TableName() string
TableName returns the DynamoDB table name
func (*MediaMetadata) UpdateKeys ¶
func (m *MediaMetadata) UpdateKeys() error
UpdateKeys sets the primary and GSI keys based on the media metadata
func (*MediaMetadata) Validate ¶
func (m *MediaMetadata) Validate() error
Validate performs validation on the MediaMetadata
type MediaPopularity ¶
type MediaPopularity struct {
// DynamoDB Keys (STABLE - never change)
PK string `theorydb:"pk,attr:PK" json:"pk"` // MEDIA_POPULARITY#{period}
SK string `theorydb:"sk,attr:SK" json:"sk"` // MEDIA#{mediaID}
// GSI1 - Sorted by popularity (UPDATEABLE)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // PERIOD#{period}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {inverted_view_count} for descending sort
// GSI2 - Query by date
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk"` // DATE#{date}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk"` // MEDIA#{mediaID}
// Business fields
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
ViewCount int64 `theorydb:"attr:viewCount" json:"view_count"`
UniqueViewers int64 `theorydb:"attr:uniqueViewers" json:"unique_viewers"`
CompletionCount int64 `theorydb:"attr:completionCount" json:"completion_count"`
TotalWatchTime int64 `theorydb:"attr:totalWatchTime" json:"total_watch_time"` // seconds
BufferingEvents int64 `theorydb:"attr:bufferingEvents" json:"buffering_events"`
LastViewed time.Time `theorydb:"attr:lastViewed" json:"last_viewed"`
FirstViewed time.Time `theorydb:"attr:firstViewed" json:"first_viewed"`
Period string `theorydb:"attr:period" json:"period"` // DAY, WEEK, MONTH
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// Quality distribution
QualityViews map[string]int64 `theorydb:"attr:qualityViews" json:"quality_views"` // quality -> view count
// Popularity score (calculated)
PopularityScore float64 `theorydb:"attr:popularityScore" json:"popularity_score"`
TrendScore float64 `theorydb:"attr:trendScore" json:"trend_score"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MediaPopularity tracks aggregated popularity metrics for media items This is maintained by streaming analytics ingestion for efficient trending queries
func (*MediaPopularity) AddQualityView ¶
func (m *MediaPopularity) AddQualityView(quality string, count int64)
AddQualityView increments view count for a specific quality
func (*MediaPopularity) CalculateAvgWatchTime ¶
func (m *MediaPopularity) CalculateAvgWatchTime() float64
CalculateAvgWatchTime calculates average watch time in seconds
func (*MediaPopularity) CalculateCompletionRate ¶
func (m *MediaPopularity) CalculateCompletionRate() float64
CalculateCompletionRate calculates the completion rate
func (*MediaPopularity) GetPK ¶
func (m *MediaPopularity) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*MediaPopularity) GetSK ¶
func (m *MediaPopularity) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*MediaPopularity) IncrementViews ¶
func (m *MediaPopularity) IncrementViews(count int64)
IncrementViews atomically increments the view count
func (*MediaPopularity) SetForPeriod ¶
func (m *MediaPopularity) SetForPeriod(mediaID string, period string, viewCount int64)
SetForPeriod configures this record for a specific time period
func (MediaPopularity) TableName ¶
func (MediaPopularity) TableName() string
TableName returns the DynamoDB table backing MediaPopularity.
func (*MediaPopularity) UpdateKeys ¶
func (m *MediaPopularity) UpdateKeys() error
UpdateKeys sets the keys based on the current values
type MediaProvenance ¶ added in v1.6.23
type MediaProvenance struct {
Origin EditorialMediaOrigin `json:"origin"`
Tool string `json:"tool,omitempty"`
ResponsibleActor string `json:"responsible_actor"`
SourceReferences []string `json:"source_references,omitempty"`
RightsLicenseNotes string `json:"rights_license_notes,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
RecordedAt time.Time `json:"recorded_at"`
ContentIntegrity string `json:"content_integrity"`
}
MediaProvenance is internal editorial evidence about an asset. CreditLine on DraftMediaUsage is the distinct reader-facing attribution surface.
type MediaSession ¶
type MediaSession struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // SESSION#{sessionID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // METADATA
// GSI keys for querying by user and media
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // USER#{userID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // SESSION#{startTime}
// Business fields
SessionID string `theorydb:"attr:sessionID" json:"session_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
Format string `theorydb:"attr:format" json:"format"` // hls, dash
CurrentQuality string `theorydb:"attr:currentQuality" json:"current_quality"` // 4k, 1080p, 720p, etc.
StartTime time.Time `theorydb:"attr:startTime" json:"start_time"`
EndTime *time.Time `theorydb:"attr:endTime" json:"end_time,omitempty"`
LastSegmentIndex int `theorydb:"attr:lastSegmentIndex" json:"last_segment_index"`
BytesTransferred int64 `theorydb:"attr:bytesTransferred" json:"bytes_transferred"`
BufferHealth float64 `theorydb:"attr:bufferHealth" json:"buffer_health"` // 0.0 to 1.0
Active bool `theorydb:"attr:active" json:"active"`
Duration float64 `theorydb:"attr:duration" json:"duration,omitempty"` // in seconds
LastUpdate *time.Time `theorydb:"attr:lastUpdate" json:"last_update,omitempty"`
// TTL for automatic cleanup (24 hours default)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MediaSession represents a streaming session using DynamORM
func (*MediaSession) SetTTL ¶
func (m *MediaSession) SetTTL(ttl time.Duration)
SetTTL sets the TTL for automatic session cleanup
func (MediaSession) TableName ¶
func (MediaSession) TableName() string
TableName returns the DynamoDB table backing MediaSession.
func (*MediaSession) UpdateKeys ¶
func (m *MediaSession) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type MediaSpending ¶
type MediaSpending struct {
// Primary key - using user ID as partition key with time period as sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MEDIA_SPENDING#{userID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PERIOD#{year}-{month}" or "DAILY#{year}-{month}-{day}"
// GSI1 - Global spending queries across all users
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "SPENDING#{period_type}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{year}-{month}-{day}#{userID}"
// GSI2 - Cost category queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "COST_CATEGORY#{category}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{userID}"
// Core spending data
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
Period string `theorydb:"attr:period" json:"period"` // "2024-01", "2024-01-15" (monthly or daily)
PeriodType string `theorydb:"attr:periodType" json:"period_type"` // "monthly", "daily"
// Spending totals (in microdollars - $1 = 1,000,000 microdollars)
TotalSpendMicros int64 `theorydb:"attr:totalSpendMicros" json:"total_spend_micros"`
ProcessingSpendMicros int64 `theorydb:"attr:processingSpendMicros" json:"processing_spend_micros"` // MediaConvert, Rekognition, etc.
StorageSpendMicros int64 `theorydb:"attr:storageSpendMicros" json:"storage_spend_micros"` // S3 storage costs
BandwidthSpendMicros int64 `theorydb:"attr:bandwidthSpendMicros" json:"bandwidth_spend_micros"` // CloudFront/CDN costs
ComputeSpendMicros int64 `theorydb:"attr:computeSpendMicros" json:"compute_spend_micros"` // Lambda compute costs
// Operation counts
TotalOperations int64 `theorydb:"attr:totalOperations" json:"total_operations"`
ImageProcessingOps int64 `theorydb:"attr:imageProcessingOps" json:"image_processing_ops"`
VideoProcessingOps int64 `theorydb:"attr:videoProcessingOps" json:"video_processing_ops"`
AudioProcessingOps int64 `theorydb:"attr:audioProcessingOps" json:"audio_processing_ops"`
StorageOperations int64 `theorydb:"attr:storageOperations" json:"storage_operations"` // S3 PUT/GET operations
BandwidthBytes int64 `theorydb:"attr:bandwidthBytes" json:"bandwidth_bytes"` // Bytes transferred
ComputeTimeMs int64 `theorydb:"attr:computeTimeMs" json:"compute_time_ms"` // Lambda execution time
// Detailed cost breakdown by service
S3StorageCostMicros int64 `theorydb:"attr:s3StorageCostMicros" json:"s3_storage_cost_micros"`
S3RequestCostMicros int64 `theorydb:"attr:s3RequestCostMicros" json:"s3_request_cost_micros"`
CloudFrontCostMicros int64 `theorydb:"attr:cloudFrontCostMicros" json:"cloudfront_cost_micros"`
MediaConvertCostMicros int64 `theorydb:"attr:mediaConvertCostMicros" json:"mediaconvert_cost_micros"`
RekognitionCostMicros int64 `theorydb:"attr:rekognitionCostMicros" json:"rekognition_cost_micros"`
LambdaCostMicros int64 `theorydb:"attr:lambdaCostMicros" json:"lambda_cost_micros"`
// Usage statistics
FilesProcessed int64 `theorydb:"attr:filesProcessed" json:"files_processed"`
BytesProcessed int64 `theorydb:"attr:bytesProcessed" json:"bytes_processed"`
StorageBytesUsed int64 `theorydb:"attr:storageBytesUsed" json:"storage_bytes_used"`
MediaConvertMinutes int64 `theorydb:"attr:mediaConvertMinutes" json:"mediaconvert_minutes"` // Total minutes processed
RekognitionImages int64 `theorydb:"attr:rekognitionImages" json:"rekognition_images"` // Images analyzed
ThumbnailsGenerated int64 `theorydb:"attr:thumbnailsGenerated" json:"thumbnails_generated"`
// Error tracking
FailedOperations int64 `theorydb:"attr:failedOperations" json:"failed_operations"`
ErrorCostMicros int64 `theorydb:"attr:errorCostMicros" json:"error_cost_micros"` // Costs from failed operations
// Budget tracking
BudgetLimitMicros int64 `theorydb:"attr:budgetLimitMicros" json:"budget_limit_micros"` // User's budget limit
BudgetUsagePercent float64 `theorydb:"attr:budgetUsagePercent" json:"budget_usage_percent"` // Percentage of budget used
BudgetExceeded bool `theorydb:"attr:budgetExceeded" json:"budget_exceeded"` // True if over budget
BudgetExceededAt *time.Time `theorydb:"attr:budgetExceededAt" json:"budget_exceeded_at,omitempty"` // When budget was exceeded
// Timestamps
PeriodStartAt time.Time `theorydb:"attr:periodStartAt" json:"period_start_at"`
PeriodEndAt time.Time `theorydb:"attr:periodEndAt" json:"period_end_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for old spending records (keep for 2 years)
ExpiresAt *int64 `theorydb:"ttl,attr:ttl" json:"expires_at,omitempty"` // Unix timestamp
// Version for optimistic locking
ModelVersion int `theorydb:"version,attr:modelVersion" json:"model_version"`
// contains filtered or unexported fields
}
MediaSpending tracks spending and costs for media processing operations per user
func (*MediaSpending) AddSpending ¶
func (ms *MediaSpending) AddSpending(transaction *MediaSpendingTransaction)
AddSpending adds a transaction amount to the spending record
func (*MediaSpending) BeforeCreate ¶
func (ms *MediaSpending) BeforeCreate() error
BeforeCreate sets up the MediaSpending model before creation
func (*MediaSpending) BeforeUpdate ¶
func (ms *MediaSpending) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*MediaSpending) GetCostBreakdown ¶
func (ms *MediaSpending) GetCostBreakdown() map[string]int64
GetCostBreakdown returns a breakdown of costs by category
func (*MediaSpending) GetEfficiencyMetrics ¶
func (ms *MediaSpending) GetEfficiencyMetrics() map[string]float64
GetEfficiencyMetrics returns efficiency metrics
func (*MediaSpending) GetPK ¶
func (ms *MediaSpending) GetPK() string
GetPK returns the partition key for this media spending record
func (*MediaSpending) GetRemainingBudget ¶
func (ms *MediaSpending) GetRemainingBudget() int64
GetRemainingBudget returns the remaining budget in microdollars
func (*MediaSpending) GetSK ¶
func (ms *MediaSpending) GetSK() string
GetSK returns the sort key for this media spending record
func (*MediaSpending) GetServiceBreakdown ¶
func (ms *MediaSpending) GetServiceBreakdown() map[string]int64
GetServiceBreakdown returns a breakdown of costs by AWS service
func (*MediaSpending) IsOverBudget ¶
func (ms *MediaSpending) IsOverBudget() bool
IsOverBudget checks if spending has exceeded the budget limit
func (MediaSpending) TableName ¶
func (MediaSpending) TableName() string
TableName returns the DynamoDB table name for MediaSpending
func (*MediaSpending) UpdateKeys ¶
func (ms *MediaSpending) UpdateKeys() error
UpdateKeys ensures all key fields are properly set
func (*MediaSpending) Validate ¶
func (ms *MediaSpending) Validate() error
Validate performs validation on the MediaSpending
type MediaSpendingTransaction ¶
type MediaSpendingTransaction struct {
// Primary key - using user ID as partition key with transaction ID as sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "SPENDING_TXN#{userID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TXN#{timestamp}#{transactionID}"
// GSI1 - Time-based transaction queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "TXN_TIME#{date}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{userID}#{transactionID}"
// Core transaction data
TransactionID string `theorydb:"attr:transactionID" json:"transaction_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
// Cost details
CostMicros int64 `theorydb:"attr:costMicros" json:"cost_micros"` // Cost in microdollars
Category string `theorydb:"attr:category" json:"category"` // "processing", "storage", "bandwidth", "compute"
Service string `theorydb:"attr:service" json:"service"` // "s3", "mediaconvert", "cloudfront", "lambda", "rekognition"
Operation string `theorydb:"attr:operation" json:"operation"` // "image_resize", "video_transcode", "storage_put", etc.
Description string `theorydb:"attr:description" json:"description"` // Human-readable description
// Associated media
MediaID string `theorydb:"attr:mediaID" json:"media_id,omitempty"`
JobID string `theorydb:"attr:jobID" json:"job_id,omitempty"`
FileName string `theorydb:"attr:fileName" json:"file_name,omitempty"`
FileSize int64 `theorydb:"attr:fileSize" json:"file_size,omitempty"`
ContentType string `theorydb:"attr:contentType" json:"content_type,omitempty"`
// Processing details
ProcessingTimeMs int64 `theorydb:"attr:processingTimeMs" json:"processing_time_ms,omitempty"` // How long the operation took
BytesProcessed int64 `theorydb:"attr:bytesProcessed" json:"bytes_processed,omitempty"` // Bytes processed
UnitsConsumed int64 `theorydb:"attr:unitsConsumed" json:"units_consumed,omitempty"` // Service-specific units
// Error information
IsError bool `theorydb:"attr:isError" json:"is_error"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for old transactions (keep for 1 year)
ExpiresAt *int64 `theorydb:"ttl,attr:ttl" json:"expires_at,omitempty"` // Unix timestamp
// contains filtered or unexported fields
}
MediaSpendingTransaction represents a single spending transaction
func (*MediaSpendingTransaction) BeforeCreate ¶
func (mst *MediaSpendingTransaction) BeforeCreate() error
BeforeCreate sets up the MediaSpendingTransaction model before creation
func (*MediaSpendingTransaction) GetPK ¶
func (mst *MediaSpendingTransaction) GetPK() string
GetPK returns the partition key for this media spending transaction
func (*MediaSpendingTransaction) GetSK ¶
func (mst *MediaSpendingTransaction) GetSK() string
GetSK returns the sort key for this media spending transaction
func (MediaSpendingTransaction) TableName ¶
func (MediaSpendingTransaction) TableName() string
TableName returns the DynamoDB table name for MediaSpendingTransaction
func (*MediaSpendingTransaction) UpdateKeys ¶
func (mst *MediaSpendingTransaction) UpdateKeys() error
UpdateKeys ensures all key fields are properly set
func (*MediaSpendingTransaction) Validate ¶
func (mst *MediaSpendingTransaction) Validate() error
Validate performs validation on the MediaSpendingTransaction
type MediaVariant ¶
type MediaVariant struct {
S3Key string `json:"s3_key"`
CDNUrl string `json:"cdn_url,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
FileSize int64 `json:"file_size"`
ContentType string `json:"content_type"`
Quality string `json:"quality,omitempty"` // "low", "medium", "high"
}
MediaVariant represents a processed variant of the original media
func (MediaVariant) TableName ¶
func (MediaVariant) TableName() string
TableName returns the DynamoDB table backing MediaVariant.
type MediaVariantCost ¶
type MediaVariantCost struct {
// Variant identification
Resolution string `json:"resolution"` // e.g., "1080p", "720p", "480p"
Codec string `json:"codec"` // e.g., "h264", "h265", "av1"
Bitrate int `json:"bitrate"` // Target bitrate in kbps
VariantKey string `json:"variant_key"` // Unique identifier: "{resolution}_{codec}_{bitrate}"
// Processing costs (microdollars)
ProcessingCost int64 `json:"processing_cost"` // Cost to create this variant
StorageCost int64 `json:"storage_cost"` // Storage cost for variant files
BandwidthCost int64 `json:"bandwidth_cost"` // Delivery cost for this variant
TotalCost int64 `json:"total_cost"` // Sum of all costs for this variant
// Processing metrics
ProcessingTimeMs int64 `json:"processing_time_ms"` // Time to process this variant
OutputSizeBytes int64 `json:"output_size_bytes"` // Size of processed variant
CompressionRatio float64 `json:"compression_ratio"` // Compression efficiency
// Quality metrics
VMAF float64 `json:"vmaf,omitempty"` // Video quality score (if available)
PSNR float64 `json:"psnr,omitempty"` // Peak signal-to-noise ratio
SSIM float64 `json:"ssim,omitempty"` // Structural similarity index
// Usage metrics
DeliveryCount int64 `json:"delivery_count"` // Number of times served
BandwidthBytes int64 `json:"bandwidth_bytes"` // Total bytes delivered
ViewerMinutes int64 `json:"viewer_minutes"` // Total viewing time in minutes
// Performance metrics
AverageLatencyMs int64 `json:"average_latency_ms"` // Average response time
ErrorRate float64 `json:"error_rate"` // Error rate for this variant
CacheHitRate float64 `json:"cache_hit_rate"` // CDN cache performance
}
MediaVariantCost represents cost metrics for a specific media variant
func (MediaVariantCost) TableName ¶
func (MediaVariantCost) TableName() string
TableName returns the DynamoDB table backing MediaVariantCost.
type MediaVisibility ¶ added in v1.6.23
type MediaVisibility string
MediaVisibility describes whether media bytes may use the public social-media delivery posture or must remain inside the authenticated editorial workflow.
const ( // MediaVisibilityPublic preserves the existing Mastodon/social-media posture. MediaVisibilityPublic MediaVisibility = "public" // MediaVisibilityInternal requires an owner or exact draft-review grant before access. MediaVisibilityInternal MediaVisibility = "internal" )
type Mention ¶
type Mention struct {
ID string `json:"id"`
Username string `json:"username"`
URL string `json:"url"`
Acct string `json:"acct"`
}
Mention represents a mention in an announcement
type MetricRecord ¶
type MetricRecord struct {
// Primary key pattern: METRICS#<type>#<bucket>
PK string `theorydb:"pk" json:"pk"`
SK string `theorydb:"sk" json:"sk"` // timestamp ISO format
// GSI1: Service-based queries - SERVICE#<name> / TIMESTAMP#<iso>
GSI1PK string `theorydb:"index:gsi1,pk,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,omitempty" json:"gsi1_sk"`
// GSI2: Metric type queries - METRIC_TYPE#<type> / TIMESTAMP#<iso>
GSI2PK string `theorydb:"index:gsi2,pk,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,omitempty" json:"gsi2_sk"`
// GSI3: Date-based queries - DATE#<yyyy-mm-dd> / SERVICE#<name>#<timestamp>
GSI3PK string `theorydb:"index:gsi3,pk,omitempty" json:"gsi3_pk"`
GSI3SK string `theorydb:"index:gsi3,sk,omitempty" json:"gsi3_sk"`
// GSI4: Aggregation queries - AGGREGATION#<level> / TIMESTAMP#<iso>
GSI4PK string `theorydb:"index:gsi4,pk,omitempty" json:"gsi4_pk"`
GSI4SK string `theorydb:"index:gsi4,sk,omitempty" json:"gsi4_sk"`
// Core fields
MetricType string `json:"metric_type"`
ServiceName string `json:"service_name"`
Timestamp time.Time `json:"timestamp"`
MetricID string `json:"metric_id"` // UUID for uniqueness
// Metric Values (statistical aggregates)
Count int64 `json:"count,omitempty"`
Sum float64 `json:"sum,omitempty"`
Min float64 `json:"min,omitempty"`
Max float64 `json:"max,omitempty"`
P50 float64 `json:"p50,omitempty"`
P95 float64 `json:"p95,omitempty"`
P99 float64 `json:"p99,omitempty"`
// Dimensions for filtering/grouping
Dimensions map[string]string `json:"dimensions,omitempty"`
// Metadata
AggregationLevel string `json:"aggregation_level"` // raw, 5min, hourly, daily
Unit string `json:"unit,omitempty"` // ms, count, bytes, etc.
// Timestamps
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
// TTL for automatic cleanup (data retention per aggregation level)
TTL int64 `theorydb:"ttl" json:"ttl,omitempty"` // Unix timestamp
// contains filtered or unexported fields
}
MetricRecord represents the new reporting table schema with extensive indexing Following Architecture Decisions pattern: METRICS#<type>#<timestamp>
func (*MetricRecord) AddDimension ¶
func (m *MetricRecord) AddDimension(key, value string)
AddDimension adds a dimension to the metric record
func (*MetricRecord) BeforeCreate ¶
func (m *MetricRecord) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*MetricRecord) BeforeUpdate ¶
func (m *MetricRecord) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*MetricRecord) GetPK ¶
func (m *MetricRecord) GetPK() string
GetPK implements BaseModel interface
func (*MetricRecord) GetSK ¶
func (m *MetricRecord) GetSK() string
GetSK implements BaseModel interface
func (MetricRecord) TableName ¶
func (MetricRecord) TableName() string
TableName returns the DynamoDB table backing MetricRecord.
func (*MetricRecord) UpdateKeys ¶
func (m *MetricRecord) UpdateKeys() error
UpdateKeys implements BaseModel interface and populates ALL GSI keys based on record data
func (*MetricRecord) Validate ¶
func (m *MetricRecord) Validate() error
Validate performs validation on the MetricRecord
type MetricRecordBuilder ¶
type MetricRecordBuilder struct {
// contains filtered or unexported fields
}
MetricRecordBuilder helps create metric records
func NewMetricRecordBuilder ¶
func NewMetricRecordBuilder() *MetricRecordBuilder
NewMetricRecordBuilder creates a new metric record builder
func (*MetricRecordBuilder) Build ¶
func (mb *MetricRecordBuilder) Build() *MetricRecord
Build creates the metric record
func (*MetricRecordBuilder) ForService ¶
func (mb *MetricRecordBuilder) ForService(serviceName string) *MetricRecordBuilder
ForService sets the service name
func (*MetricRecordBuilder) OfType ¶
func (mb *MetricRecordBuilder) OfType(metricType string) *MetricRecordBuilder
OfType sets the metric type
func (MetricRecordBuilder) TableName ¶
func (MetricRecordBuilder) TableName() string
TableName returns the DynamoDB table backing MetricRecordBuilder.
func (*MetricRecordBuilder) WithAggregationLevel ¶
func (mb *MetricRecordBuilder) WithAggregationLevel(level string) *MetricRecordBuilder
WithAggregationLevel sets the aggregation level
func (*MetricRecordBuilder) WithDimension ¶
func (mb *MetricRecordBuilder) WithDimension(key, value string) *MetricRecordBuilder
WithDimension adds a dimension
func (*MetricRecordBuilder) WithStats ¶
func (mb *MetricRecordBuilder) WithStats(count int64, sum, minVal, maxVal, p50, p95, p99 float64) *MetricRecordBuilder
WithStats sets statistical values
func (*MetricRecordBuilder) WithTimestamp ¶
func (mb *MetricRecordBuilder) WithTimestamp(timestamp time.Time) *MetricRecordBuilder
WithTimestamp sets the timestamp
func (*MetricRecordBuilder) WithUnit ¶
func (mb *MetricRecordBuilder) WithUnit(unit string) *MetricRecordBuilder
WithUnit sets the unit
type Metrics ¶
type Metrics struct {
// Primary key - using metric type as partition key with timestamp sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "metrics#{type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "ts#{timestamp}#{id}"
// GSI1 - Service queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "METRICS_SVC#{service}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{type}#{id}"
// GSI2 - Aggregation queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "METRICS_AGG#{period}#{type}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{id}"
// Core metrics data
ID string `theorydb:"attr:id" json:"id"`
Type string `theorydb:"attr:type" json:"type"` // request, error, latency, throughput, etc.
Service string `theorydb:"attr:service" json:"service"` // api, auth, federation, etc.
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Period string `theorydb:"attr:period" json:"period"` // minute, hour, day
// Metric values
Value float64 `theorydb:"attr:value" json:"value"`
Count int64 `theorydb:"attr:count" json:"count"`
Sum float64 `theorydb:"attr:sum" json:"sum"`
Min float64 `theorydb:"attr:min" json:"min"`
Max float64 `theorydb:"attr:max" json:"max"`
Average float64 `theorydb:"attr:average" json:"average"`
Percentiles map[string]float64 `theorydb:"attr:percentiles" json:"percentiles,omitempty"` // p50, p90, p95, p99
// Dimensions for filtering
Dimensions map[string]string `theorydb:"attr:dimensions" json:"dimensions,omitempty"`
// Resource information
ResourceID string `theorydb:"attr:resourceID" json:"resource_id,omitempty"` // Lambda function name, etc.
ResourceType string `theorydb:"attr:resourceType" json:"resource_type,omitempty"` // lambda, dynamodb, etc.
// Additional metadata
Unit string `theorydb:"attr:unit" json:"unit,omitempty"` // ms, count, bytes, etc.
Tags map[string]string `theorydb:"attr:tags" json:"tags,omitempty"`
Properties map[string]interface{} `theorydb:"attr:properties" json:"properties,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (30 days for raw, 90 days for aggregated)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
Metrics represents system metrics data
func (*Metrics) AddDimension ¶
AddDimension adds a dimension to the metrics
func (*Metrics) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Metrics) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Metrics) GetProperty ¶
GetProperty gets a custom property
func (*Metrics) SetPercentile ¶
SetPercentile sets a percentile value
func (*Metrics) SetProperty ¶
SetProperty sets a custom property
func (*Metrics) UpdateKeys ¶
UpdateKeys implements BaseModel interface and sets up all primary and GSI keys
type MetricsBuilder ¶
type MetricsBuilder struct {
// contains filtered or unexported fields
}
MetricsBuilder helps create metrics
func NewMetricsBuilder ¶
func NewMetricsBuilder() *MetricsBuilder
NewMetricsBuilder creates a new metrics builder
func (*MetricsBuilder) ForService ¶
func (mb *MetricsBuilder) ForService(service string) *MetricsBuilder
ForService sets the service
func (*MetricsBuilder) OfType ¶
func (mb *MetricsBuilder) OfType(metricType string) *MetricsBuilder
OfType sets the metric type
func (MetricsBuilder) TableName ¶
func (MetricsBuilder) TableName() string
TableName returns the DynamoDB table backing MetricsBuilder.
func (*MetricsBuilder) WithDimension ¶
func (mb *MetricsBuilder) WithDimension(key, value string) *MetricsBuilder
WithDimension adds a dimension
func (*MetricsBuilder) WithPeriod ¶
func (mb *MetricsBuilder) WithPeriod(period string) *MetricsBuilder
WithPeriod sets the period
func (*MetricsBuilder) WithResource ¶
func (mb *MetricsBuilder) WithResource(resourceID, resourceType string) *MetricsBuilder
WithResource sets resource information
func (*MetricsBuilder) WithStats ¶
func (mb *MetricsBuilder) WithStats(count int64, sum, minVal, maxVal float64) *MetricsBuilder
WithStats sets statistical values
func (*MetricsBuilder) WithTag ¶
func (mb *MetricsBuilder) WithTag(key, value string) *MetricsBuilder
WithTag adds a tag
func (*MetricsBuilder) WithUnit ¶
func (mb *MetricsBuilder) WithUnit(unit string) *MetricsBuilder
WithUnit sets the unit
func (*MetricsBuilder) WithValue ¶
func (mb *MetricsBuilder) WithValue(value float64) *MetricsBuilder
WithValue sets the metric value
type MetricsCompression ¶
type MetricsCompression struct {
Version uint8 `json:"v"`
CompressedAt time.Time `json:"ca"`
// Delta-encoded counters (saves space for large numbers)
TotalAttemptsDelta int64 `json:"tad"`
SuccessCountDelta int64 `json:"scd"`
FailureCountDelta int64 `json:"fcd"`
// Quantized success rate (0-255 for 0-100% with 0.4% precision)
QuantizedSuccessRate uint8 `json:"qsr"`
// Quantized response times in milliseconds (log scale)
ResponseTimeP50 uint16 `json:"rtp50"`
ResponseTimeP95 uint16 `json:"rtp95"`
ResponseTimeP99 uint16 `json:"rtp99"`
// Compressed state history (run-length encoded)
StateTransitions []byte `json:"st"`
// Activity pattern bitmap (daily activity over 30 days)
ActivityPattern uint32 `json:"ap"`
}
MetricsCompression holds compressed metrics data using various compression techniques
func (MetricsCompression) TableName ¶
func (MetricsCompression) TableName() string
TableName returns the DynamoDB table backing MetricsCompression.
func (*MetricsCompression) ToBinary ¶
func (mc *MetricsCompression) ToBinary() []byte
ToBinary serializes the compression struct to compact binary format
type MissingReply ¶
type MissingReply struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // THREAD#{rootStatusID}
SK string `theorydb:"sk,attr:SK" json:"-"` // MISSING#{replyID}
// GSI for querying by parent status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{parentStatusID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // MISSING_REPLY
// Missing reply data
RootStatusID string `theorydb:"attr:rootStatusID" json:"root_status_id"` // Root of the thread
ParentStatusID string `theorydb:"attr:parentStatusID" json:"parent_status_id"` // Parent that references this reply
ReplyID string `theorydb:"attr:replyID" json:"reply_id"` // The missing reply ID (could be URL)
ReplyURL string `theorydb:"attr:replyURL" json:"reply_url,omitempty"` // URL if known
DetectedAt time.Time `theorydb:"attr:detectedAt" json:"detected_at"` // When we first detected this gap
LastAttemptAt *time.Time `theorydb:"attr:lastAttemptAt" json:"last_attempt_at,omitempty"` // Last fetch attempt
AttemptCount int `theorydb:"attr:attemptCount" json:"attempt_count"` // Number of fetch attempts
LastError string `theorydb:"attr:lastError" json:"last_error,omitempty"` // Last error message
Status string `theorydb:"attr:status" json:"status"` // pending, fetching, failed, resolved
FailureReason string `theorydb:"attr:failureReason" json:"failure_reason,omitempty"` // deleted, 404, 403, timeout, etc.
ResolvedAt *time.Time `theorydb:"attr:resolvedAt" json:"resolved_at,omitempty"` // When the reply was successfully fetched
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update
// Metadata for retry logic
NextRetryAt *time.Time `theorydb:"attr:nextRetryAt" json:"next_retry_at,omitempty"` // When to retry (exponential backoff)
Priority int `theorydb:"attr:priority" json:"priority"` // Priority for fetching (1=high, 5=low)
// TTL for auto-cleanup (7 days for resolved, 30 days for failed)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
MissingReply represents a reply that we know should exist but haven't fetched yet Used for tracking gaps in thread synchronization
func NewMissingReply ¶
func NewMissingReply(rootStatusID, parentStatusID, replyID string) *MissingReply
NewMissingReply creates a new missing reply record
func (*MissingReply) IsPermanentFailure ¶
func (m *MissingReply) IsPermanentFailure() bool
IsPermanentFailure checks if the failure is permanent (no need to retry)
func (*MissingReply) MarkFailed ¶
func (m *MissingReply) MarkFailed(errorMsg, failureReason string)
MarkFailed marks the reply fetch as failed with a reason
func (*MissingReply) MarkFetching ¶
func (m *MissingReply) MarkFetching()
MarkFetching marks the reply as being fetched
func (*MissingReply) MarkResolved ¶
func (m *MissingReply) MarkResolved()
MarkResolved marks the reply as successfully fetched
func (*MissingReply) SetPriority ¶
func (m *MissingReply) SetPriority(priority int)
SetPriority sets the fetch priority
func (*MissingReply) ShouldRetry ¶
func (m *MissingReply) ShouldRetry() bool
ShouldRetry checks if we should retry fetching this reply
func (MissingReply) TableName ¶
func (MissingReply) TableName() string
TableName returns the DynamoDB table backing MissingReply.
func (*MissingReply) UpdateKeys ¶
func (m *MissingReply) UpdateKeys() error
UpdateKeys updates the primary and GSI keys
type ModelTrainingJob ¶
type ModelTrainingJob struct {
// Primary key - Training jobs
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLJOB#{job_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "JOB"
// GSI1 - Status queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "MLJOB#{status}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Tenant queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "TENANT#{tenant_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "TIME#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_TRAINING_JOB"
// Job fields
JobID string `theorydb:"attr:jobID" json:"job_id"` // Bedrock job ARN/ID
JobName string `theorydb:"attr:jobName" json:"job_name"` // Human-readable job name
Status string `theorydb:"attr:status" json:"status"` // SUBMITTED, IN_PROGRESS, COMPLETED, FAILED, STOPPED
TenantID string `theorydb:"attr:tenantID" json:"tenant_id"` // Tenant that initiated training
InitiatedBy string `theorydb:"attr:initiatedBy" json:"initiated_by"` // User who started the training
DatasetS3Key string `theorydb:"attr:datasetS3Key" json:"dataset_s3_key"` // S3 key of training dataset
DatasetSamples int `theorydb:"attr:datasetSamples" json:"dataset_samples"` // Number of samples in dataset
BaseModelID string `theorydb:"attr:baseModelID" json:"base_model_id"` // Base Bedrock model
ModelARN string `theorydb:"attr:modelARN" json:"model_arn"` // Output model ARN (when completed)
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message"` // Error details (when failed)
StartedAt time.Time `theorydb:"attr:startedAt" json:"started_at"` // When job was submitted
CompletedAt time.Time `theorydb:"attr:completedAt" json:"completed_at"` // When job finished
Metrics TrainingMetrics `theorydb:"attr:metrics" json:"metrics"` // Training metrics (when completed)
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"` // Additional context
// DynamoDB TTL (jobs can expire after 90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ModelTrainingJob tracks asynchronous ML model training jobs
func (*ModelTrainingJob) GetPK ¶
func (m *ModelTrainingJob) GetPK() string
GetPK returns the primary partition key
func (*ModelTrainingJob) GetSK ¶
func (m *ModelTrainingJob) GetSK() string
GetSK returns the primary sort key
func (ModelTrainingJob) TableName ¶
func (ModelTrainingJob) TableName() string
TableName returns the DynamoDB table name
func (*ModelTrainingJob) UpdateKeys ¶
func (m *ModelTrainingJob) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type Moderation ¶
type Moderation struct {
ModerationID string `json:"moderation_id"`
ContentID string `json:"content_id"`
ContentType ModerationContentType `json:"content_type"`
UserID string `json:"user_id"`
Status ModerationStatus `json:"status"`
Action ModerationAction `json:"action"`
Reason ModerationReason `json:"reason"`
Evidence ModerationEvidence `json:"evidence"`
ModeratorID string `json:"moderator_id"`
ModeratorType string `json:"moderator_type"` // "user", "automated", "admin"
Metadata map[string]interface{} `json:"metadata,omitempty"`
History []ModerationHistoryEntry `json:"history,omitempty"`
CreatedAt time.Time `json:"created_at"`
ActionedAt *time.Time `json:"actioned_at,omitempty"`
ResolvedAt *time.Time `json:"resolved_at,omitempty"`
}
Moderation represents an active moderation case being processed
func (*Moderation) AddHistoryEntry ¶
func (m *Moderation) AddHistoryEntry(actorID, actorType string, action ModerationAction, fromStatus, toStatus ModerationStatus, note string)
AddHistoryEntry adds a new entry to the moderation history
func (*Moderation) GetPrimaryProhibitedWord ¶
func (m *Moderation) GetPrimaryProhibitedWord() string
GetPrimaryProhibitedWord returns the first prohibited word found, or empty string
func (*Moderation) GetRateLimitViolationSeverity ¶
func (m *Moderation) GetRateLimitViolationSeverity() string
GetRateLimitViolationSeverity determines the severity of rate limit violations
func (Moderation) TableName ¶
func (Moderation) TableName() string
TableName returns the DynamoDB table backing Moderation.
type ModerationAction ¶
type ModerationAction string
ModerationAction represents the type of moderation action taken
const ( // ModerationActionRemove represents a remove moderation action ModerationActionRemove ModerationAction = "remove" // ModerationActionSuspend represents a suspend moderation action ModerationActionSuspend ModerationAction = "suspend" // ModerationActionSilence represents a silence moderation action ModerationActionSilence ModerationAction = "silence" // ModerationActionWarning represents a warning moderation action ModerationActionWarning ModerationAction = "warning" // ModerationActionRestore represents a restore moderation action ModerationActionRestore ModerationAction = "restore" // ModerationActionDismiss represents a dismiss moderation action ModerationActionDismiss ModerationAction = "dismiss" )
type ModerationAnalysisResult ¶
type ModerationAnalysisResult struct {
// Primary key - analysis results by content
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "ANALYSIS#{content_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "RESULT#{timestamp}#{analysis_id}"
// GSI1 - Author queries (find analyses by content author)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "AUTHOR#{author_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Analysis type queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "ANALYSIS_TYPE#{type}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "CONFIDENCE#{confidence}#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ANALYSIS_RESULT"
// Analysis result data
ID string `theorydb:"attr:id" json:"id"`
ContentID string `theorydb:"attr:contentID" json:"content_id"`
ContentType string `theorydb:"attr:contentType" json:"content_type"` // text, image, video
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
AnalysisType string `theorydb:"attr:analysisType" json:"analysis_type"` // text, image, video, combined
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
Results map[string]interface{} `theorydb:"attr:results" json:"results"` // Full analysis results
PatternMatches []interface{} `theorydb:"attr:patternMatches" json:"pattern_matches,omitempty"`
ThreatMatches []interface{} `theorydb:"attr:threatMatches" json:"threat_matches,omitempty"`
ReputationScore interface{} `theorydb:"attr:reputationScore" json:"reputation_score,omitempty"`
ProcessingTime int64 `theorydb:"attr:processingTime" json:"processing_time"` // milliseconds
AnalyzedAt time.Time `theorydb:"attr:analyzedAt" json:"analyzed_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// DynamoDB TTL (90 days for analysis results)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationAnalysisResult stores detailed analysis results for audit/appeals
func (ModerationAnalysisResult) TableName ¶
func (ModerationAnalysisResult) TableName() string
TableName returns the DynamoDB table name
func (*ModerationAnalysisResult) UpdateKeys ¶
func (m *ModerationAnalysisResult) UpdateKeys()
UpdateKeys updates the GSI keys based on current field values
type ModerationAnalytics ¶
type ModerationAnalytics struct {
// Key fields - Pattern from legacy: PK=`MOD_ANALYTICS#date`, SK=`type#count`
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI fields for querying by type
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
// Business fields from legacy
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD format
ReportType string `theorydb:"attr:reportType" json:"report_type"`
Count int64 `theorydb:"attr:count" json:"count"`
ResolvedCount int64 `theorydb:"attr:resolvedCount" json:"resolved_count"`
AverageResolutionTime float64 `theorydb:"attr:averageResolutionTime" json:"average_resolution_time"` // in hours
ModeratorActions map[string]int64 `theorydb:"attr:moderatorActions" json:"moderator_actions"` // moderator -> action count
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Additional fields for pattern analytics (keeping compatibility)
PatternID string `theorydb:"attr:patternID" json:"pattern_id,omitempty"`
Matched bool `theorydb:"attr:matched" json:"matched,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL field - 90 days as per legacy
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationAnalytics tracks moderation actions and statistics
func (*ModerationAnalytics) GetPK ¶
func (m *ModerationAnalytics) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*ModerationAnalytics) GetSK ¶
func (m *ModerationAnalytics) GetSK() string
GetSK returns the sort key for BaseModel interface
func (ModerationAnalytics) TableName ¶
func (ModerationAnalytics) TableName() string
TableName returns the DynamoDB table backing ModerationAnalytics.
func (*ModerationAnalytics) UpdateKeys ¶
func (m *ModerationAnalytics) UpdateKeys() error
UpdateKeys updates the primary and sort keys for DynamoDB
type ModerationContentType ¶
type ModerationContentType string
ModerationContentType represents the type of content being moderated
const ( // ModerationContentTypeStatus represents status content type ModerationContentTypeStatus ModerationContentType = "status" // ModerationContentTypeUser represents user content type ModerationContentTypeUser ModerationContentType = "user" // ModerationContentTypeMedia represents media content type ModerationContentTypeMedia ModerationContentType = "media" // ModerationContentTypeReport represents report content type ModerationContentTypeReport ModerationContentType = "report" )
type ModerationDecision ¶
type ModerationDecision struct {
// Primary key - decisions by object
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "DECISION#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{RFC3339}"
// GSI1 - Active decisions lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "ACTIVE_DECISIONS"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // "OBJECT#{object_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "DECISION"
// ModerationDecision fields (copied to avoid circular import)
ID string `theorydb:"attr:id" json:"id"`
EventID string `theorydb:"attr:eventID" json:"event_id"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
Action string `theorydb:"attr:action" json:"action"` // none, remove, silence, suspend, warning
ConsensusScore float64 `theorydb:"attr:consensusScore" json:"consensus_score"` // 0.0-1.0
ReviewerCount int `theorydb:"attr:reviewerCount" json:"reviewer_count"`
TrustWeightTotal float64 `theorydb:"attr:trustWeightTotal" json:"trust_weight_total"`
Reviews []interface{} `theorydb:"attr:reviews" json:"reviews,omitempty"` // Array of Review objects
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
Decided time.Time `theorydb:"attr:decided" json:"decided"`
Expires *time.Time `theorydb:"attr:expires" json:"expires,omitempty"`
// DynamoDB TTL
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
ModerationDecision represents a consensus decision
func (ModerationDecision) TableName ¶
func (ModerationDecision) TableName() string
TableName returns the DynamoDB table name
func (*ModerationDecision) UpdateKeys ¶
func (d *ModerationDecision) UpdateKeys()
UpdateKeys updates the keys based on current field values
type ModerationDecisionResult ¶
type ModerationDecisionResult struct {
// Primary key - decisions by content
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "DECISION_RESULT#{content_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{RFC3339}#{decision_id}"
// GSI1 - Active decisions lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "ACTIVE_DECISIONS"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // "CONTENT#{content_id}"
// GSI2 - Action type queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "ACTION#{action}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "CONFIDENCE#{confidence}#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "DECISION_RESULT"
// Decision data
ID string `theorydb:"attr:id" json:"id"`
ContentID string `theorydb:"attr:contentID" json:"content_id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Action string `theorydb:"attr:action" json:"action"` // allow, flag, quarantine, remove, shadow_ban
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
Reasons []interface{} `theorydb:"attr:reasons" json:"reasons"`
RequiresReview bool `theorydb:"attr:requiresReview" json:"requires_review"`
ReviewPriority int `theorydb:"attr:reviewPriority" json:"review_priority"`
Recommendations []string `theorydb:"attr:recommendations" json:"recommendations,omitempty"`
ExpiresAt *time.Time `theorydb:"attr:expiresAt" json:"expires_at,omitempty"`
DecidedAt time.Time `theorydb:"attr:decidedAt" json:"decided_at"`
EnforcementStatus string `theorydb:"attr:enforcementStatus" json:"enforcement_status"` // pending, applied, failed, expired
EnforcedAt *time.Time `theorydb:"attr:enforcedAt" json:"enforced_at,omitempty"`
EnforcementError string `theorydb:"attr:enforcementError" json:"enforcement_error,omitempty"`
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// DynamoDB TTL (90 days for decisions)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationDecisionResult stores enhanced decision results with enforcement tracking
func (ModerationDecisionResult) TableName ¶
func (ModerationDecisionResult) TableName() string
TableName returns the DynamoDB table name
func (*ModerationDecisionResult) UpdateKeys ¶
func (m *ModerationDecisionResult) UpdateKeys()
UpdateKeys updates the GSI keys based on current field values
type ModerationDecisionSample ¶
type ModerationDecisionSample struct {
// Primary key - samples by date
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "SAMPLES#{YYYY-MM-DD}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "{unix_nano}#{content_id}"
// GSI1 - Decision type queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "DECISION#{decision}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "DATE#{YYYY-MM-DD}#{timestamp}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "DECISION_SAMPLE"
// Sample data
ContentID string `theorydb:"attr:contentID" json:"content_id"`
Decision string `theorydb:"attr:decision" json:"decision"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
ProcessingTime int64 `theorydb:"attr:processingTime" json:"processing_time"` // milliseconds
ReasonCount int `theorydb:"attr:reasonCount" json:"reason_count"`
RequiresReview bool `theorydb:"attr:requiresReview" json:"requires_review"`
Date string `theorydb:"attr:date" json:"date"`
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationDecisionSample represents a decision sample for analysis
func (*ModerationDecisionSample) GetPK ¶
func (m *ModerationDecisionSample) GetPK() string
GetPK returns the partition key
func (*ModerationDecisionSample) GetSK ¶
func (m *ModerationDecisionSample) GetSK() string
GetSK returns the sort key
func (ModerationDecisionSample) TableName ¶
func (ModerationDecisionSample) TableName() string
TableName returns the DynamoDB table name
func (*ModerationDecisionSample) UpdateKeys ¶
func (m *ModerationDecisionSample) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationEffectivenessMetric ¶
type ModerationEffectivenessMetric struct {
// Primary key - Metrics by pattern/model
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLMETRICS#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PERIOD#{period}#{start_time}"
// GSI1 - Timeframe queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "METRICS#{period}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "F1SCORE#{f1}#{pattern_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_METRICS"
// Metric fields
PatternID string `theorydb:"attr:patternID" json:"pattern_id"` // Pattern or model ID
Period string `theorydb:"attr:period" json:"period"` // hourly, daily, weekly, monthly
StartTime time.Time `theorydb:"attr:startTime" json:"start_time"` // Start of measurement period
EndTime time.Time `theorydb:"attr:endTime" json:"end_time"` // End of measurement period
TruePositives int `theorydb:"attr:truePositives" json:"true_positives"` // Correctly flagged content
FalsePositives int `theorydb:"attr:falsePositives" json:"false_positives"` // Incorrectly flagged content
TrueNegatives int `theorydb:"attr:trueNegatives" json:"true_negatives"` // Correctly passed content
FalseNegatives int `theorydb:"attr:falseNegatives" json:"false_negatives"` // Missed problematic content
Precision float64 `theorydb:"attr:precision" json:"precision"` // TP / (TP + FP)
Recall float64 `theorydb:"attr:recall" json:"recall"` // TP / (TP + FN)
F1Score float64 `theorydb:"attr:f1Score" json:"f1_score"` // 2 * (precision * recall) / (precision + recall)
TotalReviewed int `theorydb:"attr:totalReviewed" json:"total_reviewed"` // Total items reviewed
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ModerationEffectivenessMetric represents effectiveness metrics for a moderation pattern or model
func (*ModerationEffectivenessMetric) CalculateMetrics ¶
func (m *ModerationEffectivenessMetric) CalculateMetrics()
CalculateMetrics computes precision, recall, and F1 score from counts
func (*ModerationEffectivenessMetric) GetPK ¶
func (m *ModerationEffectivenessMetric) GetPK() string
GetPK returns the primary partition key
func (*ModerationEffectivenessMetric) GetSK ¶
func (m *ModerationEffectivenessMetric) GetSK() string
GetSK returns the primary sort key
func (ModerationEffectivenessMetric) TableName ¶
func (ModerationEffectivenessMetric) TableName() string
TableName returns the DynamoDB table name
func (*ModerationEffectivenessMetric) UpdateKeys ¶
func (m *ModerationEffectivenessMetric) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationEvent ¶
type ModerationEvent struct {
// Primary key - Events are stored by object being moderated
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "EVENT#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{RFC3339}#{event_id}"
// GSI1 - Actor queries (find events by who created the content)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "ACTOR#{actor_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Type/Category/Severity queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "TYPE#{event_type}#{category}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "SEVERITY#{severity}#{RFC3339}"
// GSI3 - Event ID lookups
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk,omitempty"` // Format: "EVENTID#{event_id}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk,omitempty"` // Format: "EVENTID#{event_id}"
// GSI4 - Global event listing (admin/debug)
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk,omitempty"` // Format: "MODERATION_EVENTS"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk,omitempty"` // Format: "TIME#{RFC3339}#{event_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "EVENT"
// ModerationEvent fields (copied to avoid circular import)
ID string `theorydb:"attr:id" json:"id"`
EventType string `theorydb:"attr:eventType" json:"event_type"`
ObjectID string `theorydb:"attr:objectID" json:"object_id"` // ID of content being moderated
ObjectType string `theorydb:"attr:objectType" json:"object_type"` // status, account, media
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // Who triggered this event
Category string `theorydb:"attr:category" json:"category"`
Severity string `theorydb:"attr:severity" json:"severity"`
ConfidenceScore float64 `theorydb:"attr:confidenceScore" json:"confidence_score"` // 0.0-1.0
Evidence []any `theorydb:"attr:evidence" json:"evidence"`
Reason string `theorydb:"attr:reason" json:"reason,omitempty"` // Human-provided reason
Created time.Time `theorydb:"attr:created" json:"created"`
Updated time.Time `theorydb:"attr:updated" json:"updated"`
// DynamoDB TTL
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
ModerationEvent represents a moderation event stored in DynamoDB
func (*ModerationEvent) GetPK ¶
func (m *ModerationEvent) GetPK() string
GetPK returns the primary partition key
func (*ModerationEvent) GetSK ¶
func (m *ModerationEvent) GetSK() string
GetSK returns the primary sort key
func (ModerationEvent) TableName ¶
func (ModerationEvent) TableName() string
TableName returns the DynamoDB table name
func (*ModerationEvent) UpdateKeys ¶
func (m *ModerationEvent) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationEvidence ¶
type ModerationEvidence struct {
// Spam detection
SpamScore float64 `json:"spam_score,omitempty"`
SpamIndicators []string `json:"spam_indicators,omitempty"`
DuplicateCount int `json:"duplicate_count,omitempty"`
LinkCount int `json:"link_count,omitempty"`
MentionCount int `json:"mention_count,omitempty"`
HashtagCount int `json:"hashtag_count,omitempty"`
SuspiciousLinks []string `json:"suspicious_links,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
RegistrationAge string `json:"registration_age,omitempty"`
PostFrequency float64 `json:"post_frequency,omitempty"` // posts per hour
FollowerRatio float64 `json:"follower_ratio,omitempty"` // followers/following
NewAccountPosts int `json:"new_account_posts,omitempty"` // posts in first 24h
// Content analysis
ProhibitedWords []string `json:"prohibited_words,omitempty"`
MatchedPatterns []string `json:"matched_patterns,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
MediaFingerprint string `json:"media_fingerprint,omitempty"`
TextContent string `json:"text_content,omitempty"` // Original content for review
ContentLength int `json:"content_length,omitempty"`
Language string `json:"language,omitempty"`
Sentiment float64 `json:"sentiment,omitempty"` // -1.0 to 1.0
Toxicity float64 `json:"toxicity,omitempty"` // 0.0 to 1.0
// Rate limiting
RequestCount int `json:"request_count,omitempty"`
RequestPeriod string `json:"request_period,omitempty"`
BurstSize int `json:"burst_size,omitempty"`
AverageInterval float64 `json:"average_interval,omitempty"` // seconds between actions
LastViolationAt string `json:"last_violation_at,omitempty"`
ViolationCount int `json:"violation_count,omitempty"`
// External signals
ReportCount int `json:"report_count,omitempty"`
ReporterIDs []string `json:"reporter_ids,omitempty"`
ExternalScore float64 `json:"external_score,omitempty"`
ExternalProvider string `json:"external_provider,omitempty"`
// Confidence metrics
ConfidenceScore float64 `json:"confidence_score,omitempty"` // 0.0 to 1.0
FalsePositiveRisk float64 `json:"false_positive_risk,omitempty"`
RequiresReview bool `json:"requires_review,omitempty"`
}
ModerationEvidence contains detailed evidence for the moderation decision
func (ModerationEvidence) TableName ¶
func (ModerationEvidence) TableName() string
TableName returns the DynamoDB table backing ModerationEvidence.
type ModerationFalsePositive ¶
type ModerationFalsePositive struct {
// Primary key - false positives by date
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "METRICS#{YYYY-MM-DD}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "FP#{content_id}"
// GSI1 - False positive queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "FALSE_POSITIVES"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "DATE#{YYYY-MM-DD}#{timestamp}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "FALSE_POSITIVE"
// False positive data
ContentID string `theorydb:"attr:contentID" json:"content_id"`
OriginalDecision string `theorydb:"attr:originalDecision" json:"original_decision"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
Date string `theorydb:"attr:date" json:"date"`
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationFalsePositive represents a false positive record
func (*ModerationFalsePositive) GetPK ¶
func (m *ModerationFalsePositive) GetPK() string
GetPK returns the partition key
func (*ModerationFalsePositive) GetSK ¶
func (m *ModerationFalsePositive) GetSK() string
GetSK returns the sort key
func (ModerationFalsePositive) TableName ¶
func (ModerationFalsePositive) TableName() string
TableName returns the DynamoDB table name
func (*ModerationFalsePositive) UpdateKeys ¶
func (m *ModerationFalsePositive) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationHistoryEntry ¶
type ModerationHistoryEntry struct {
Timestamp time.Time `json:"timestamp"`
ActorID string `json:"actor_id"`
ActorType string `json:"actor_type"` // "user", "moderator", "system"
Action ModerationAction `json:"action"`
FromStatus ModerationStatus `json:"from_status"`
ToStatus ModerationStatus `json:"to_status"`
Note string `json:"note,omitempty"`
ChangedData map[string]interface{} `json:"changed_data,omitempty"`
}
ModerationHistoryEntry represents a single entry in the moderation audit trail
func (ModerationHistoryEntry) TableName ¶
func (ModerationHistoryEntry) TableName() string
TableName returns the DynamoDB table backing ModerationHistoryEntry.
type ModerationMetricsEntry ¶
type ModerationMetricsEntry struct {
// Primary key - metrics by date
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "METRICS#{YYYY-MM-DD}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "STATS#{hour}#{metric_type}"
// GSI1 - Metric type queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "METRIC_TYPE#{metric_type}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "DATE#{YYYY-MM-DD}#{hour}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "METRIC_STATS"
// Metric data
MetricType string `theorydb:"attr:metricType" json:"metric_type"` // e.g., "content_type:text", "decision:allow"
Count int64 `theorydb:"attr:count" json:"count"`
Hour string `theorydb:"attr:hour" json:"hour"`
Date string `theorydb:"attr:date" json:"date"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationMetricsEntry represents a single metrics entry in DynamoDB
func (*ModerationMetricsEntry) GetPK ¶
func (m *ModerationMetricsEntry) GetPK() string
GetPK returns the partition key
func (*ModerationMetricsEntry) GetSK ¶
func (m *ModerationMetricsEntry) GetSK() string
GetSK returns the sort key
func (ModerationMetricsEntry) TableName ¶
func (ModerationMetricsEntry) TableName() string
TableName returns the DynamoDB table name
func (*ModerationMetricsEntry) UpdateKeys ¶
func (m *ModerationMetricsEntry) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationMetricsStats ¶
type ModerationMetricsStats struct {
TimeRange ModerationMetricsTimeRange
TotalAnalyzed int64
ActionCounts map[AdvancedModerationAction]int64
CategoryCounts map[string]int64
SeverityCounts map[AdvancedSeverity]int64
AverageConfidence float64
FalsePositives int64
TruePositives int64
ResponseTime time.Duration
}
ModerationMetricsStats represents aggregated moderation statistics
func (ModerationMetricsStats) TableName ¶
func (ModerationMetricsStats) TableName() string
TableName returns the DynamoDB table backing ModerationMetricsStats.
type ModerationMetricsTimeRange ¶
ModerationMetricsTimeRange represents a time range for metrics queries
func (ModerationMetricsTimeRange) TableName ¶
func (ModerationMetricsTimeRange) TableName() string
TableName returns the DynamoDB table backing ModerationMetricsTimeRange.
type ModerationModelVersion ¶
type ModerationModelVersion struct {
// Primary key - Model versions
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLMODEL#bedrock"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "VERSION#{version_id}"
// GSI1 - Active model queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "MLMODEL#ACTIVE"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "ACCURACY#{accuracy}#VERSION#{version_id}"
// GSI2 - Training job queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "TRAININGJOB#{job_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "TRAININGJOB#{job_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_MODEL_VERSION"
// Model version fields
VersionID string `theorydb:"attr:versionID" json:"version_id"` // Model version identifier
DatasetHash string `theorydb:"attr:datasetHash" json:"dataset_hash"` // Hash of training dataset
Accuracy float64 `theorydb:"attr:accuracy" json:"accuracy"` // Model accuracy
Precision float64 `theorydb:"attr:precision" json:"precision"` // Model precision
Recall float64 `theorydb:"attr:recall" json:"recall"` // Model recall
F1Score float64 `theorydb:"attr:f1Score" json:"f1_score"` // F1 score
SamplesUsed int `theorydb:"attr:samplesUsed" json:"samples_used"` // Number of training samples
TrainingJobID string `theorydb:"attr:trainingJobID" json:"training_job_id"` // Bedrock training job ID
TrainingStatus string `theorydb:"attr:trainingStatus" json:"training_status"` // pending, in_progress, completed, failed
TrainingTime int `theorydb:"attr:trainingTime" json:"training_time"` // Training duration in seconds
IsActive bool `theorydb:"attr:isActive" json:"is_active"` // Whether this is the active model
ModelARN string `theorydb:"attr:modelARN" json:"model_arn"` // Bedrock model ARN
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"` // Training config, hyperparams, etc.
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ModerationModelVersion represents metadata about a trained ML model version
func (*ModerationModelVersion) GetPK ¶
func (m *ModerationModelVersion) GetPK() string
GetPK returns the primary partition key
func (*ModerationModelVersion) GetSK ¶
func (m *ModerationModelVersion) GetSK() string
GetSK returns the primary sort key
func (ModerationModelVersion) TableName ¶
func (ModerationModelVersion) TableName() string
TableName returns the DynamoDB table name
func (*ModerationModelVersion) UpdateKeys ¶
func (m *ModerationModelVersion) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationPattern ¶
type ModerationPattern struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "PATTERN#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // "METADATA"
// GSI1 - Active pattern queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "MODERATION_PATTERNS#ACTIVE" (when active)
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // "{severity}#{type}#{pattern_id}"
// GSI2 - Severity-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // "MODERATION_PATTERNS#{severity}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // "{updated_at}#{pattern_id}"
// Pattern data
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
Name string `theorydb:"attr:name" json:"name"`
Description string `theorydb:"attr:description" json:"description"`
Type string `theorydb:"attr:type" json:"type"` // "regex", "keyword", "phrase"
Pattern string `theorydb:"attr:pattern" json:"pattern"`
Category string `theorydb:"attr:category" json:"category"` // "toxicity", "spam", "violence", etc.
Severity float64 `theorydb:"attr:severity" json:"severity"` // 0.0 to 1.0
Active bool `theorydb:"attr:active" json:"active"`
Flags []string `theorydb:"attr:flags" json:"flags,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
HitCount int64 `theorydb:"attr:hitCount" json:"hit_count"`
LastHit time.Time `theorydb:"attr:lastHit" json:"last_hit,omitempty"`
// TTL for auto-cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationPattern represents a moderation pattern
func (*ModerationPattern) GetPK ¶
func (p *ModerationPattern) GetPK() string
GetPK returns the primary partition key
func (*ModerationPattern) GetSK ¶
func (p *ModerationPattern) GetSK() string
GetSK returns the primary sort key
func (ModerationPattern) TableName ¶
func (ModerationPattern) TableName() string
TableName returns the DynamoDB table name
func (*ModerationPattern) UpdateKeys ¶
func (p *ModerationPattern) UpdateKeys() error
UpdateKeys updates the keys based on current field values
type ModerationPatternStats ¶
type ModerationPatternStats struct {
// Primary key - pattern stats by ID
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "PATTERN_STATS#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "STATS"
// GSI1 - Hit count ranking
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "PATTERN_HITS"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "{hit_count_padded}#{pattern_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "PATTERN_STATS"
// Pattern stats data
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
PatternName string `theorydb:"attr:patternName" json:"pattern_name"`
HitCount int64 `theorydb:"attr:hitCount" json:"hit_count"`
LastHit time.Time `theorydb:"attr:lastHit" json:"last_hit"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationPatternStats represents pattern matching statistics
func (*ModerationPatternStats) GetPK ¶
func (m *ModerationPatternStats) GetPK() string
GetPK returns the partition key
func (*ModerationPatternStats) GetSK ¶
func (m *ModerationPatternStats) GetSK() string
GetSK returns the sort key
func (ModerationPatternStats) TableName ¶
func (ModerationPatternStats) TableName() string
TableName returns the DynamoDB table name
func (*ModerationPatternStats) UpdateKeys ¶
func (m *ModerationPatternStats) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationReason ¶
type ModerationReason string
ModerationReason represents why moderation was triggered
const ( // ModerationReasonSpam represents spam moderation reason ModerationReasonSpam ModerationReason = "spam" // ModerationReasonHateSpeech represents hate speech moderation reason ModerationReasonHateSpeech ModerationReason = "hate_speech" // ModerationReasonHarassment represents harassment moderation reason ModerationReasonHarassment ModerationReason = "harassment" // ModerationReasonMisinformation represents misinformation moderation reason ModerationReasonMisinformation ModerationReason = "misinformation" // ModerationReasonProhibitedWords represents prohibited words moderation reason ModerationReasonProhibitedWords ModerationReason = "prohibited_words" // ModerationReasonRateLimiting represents rate limiting moderation reason ModerationReasonRateLimiting ModerationReason = "rate_limiting" // ModerationReasonCopyright represents copyright moderation reason ModerationReasonCopyright ModerationReason = "copyright" // ModerationReasonOther represents other/miscellaneous moderation reason ModerationReasonOther ModerationReason = "other" )
type ModerationReview ¶
type ModerationReview struct {
// Primary key - reviews by event
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "REVIEW#{event_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "REVIEWER#{reviewer_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "REVIEW"
// Review fields (copied to avoid circular import)
ID string `theorydb:"attr:id" json:"id"`
EventID string `theorydb:"attr:eventID" json:"event_id"`
ReviewerID string `theorydb:"attr:reviewerID" json:"reviewer_id"`
ReviewerRep float64 `theorydb:"attr:reviewerRep" json:"reviewer_rep,omitempty"`
Action string `theorydb:"attr:action" json:"action"` // none, remove, silence, suspend, warning
Severity string `theorydb:"attr:severity" json:"severity"` // low, medium, high, critical
Note string `theorydb:"attr:note" json:"note,omitempty"`
Tags []string `theorydb:"attr:tags" json:"tags,omitempty"`
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"` // 0.0-1.0
Created time.Time `theorydb:"attr:created" json:"created"`
// DynamoDB TTL
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
ModerationReview represents a review by a moderator
func (ModerationReview) TableName ¶
func (ModerationReview) TableName() string
TableName returns the DynamoDB table name
func (*ModerationReview) UpdateKeys ¶
func (r *ModerationReview) UpdateKeys()
UpdateKeys updates the keys based on current field values
type ModerationReviewQueue ¶
type ModerationReviewQueue struct {
// Primary key - queue items by status and priority
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "REVIEW_QUEUE#{status}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PRIORITY#{priority}#{RFC3339}#{item_id}"
// GSI1 - Content lookups
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "QUEUE_CONTENT#{content_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "STATUS#{status}"
// GSI2 - Assignee queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "ASSIGNEE#{assignee_id}" (when assigned)
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "PRIORITY#{priority}#{RFC3339}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "REVIEW_QUEUE"
// Queue item data
ID string `theorydb:"attr:id" json:"id"`
ContentID string `theorydb:"attr:contentID" json:"content_id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Status string `theorydb:"attr:status" json:"status"` // pending, assigned, reviewing, completed, dismissed
Priority int `theorydb:"attr:priority" json:"priority"` // 1-10, higher is more urgent
AssignedTo string `theorydb:"attr:assignedTo" json:"assigned_to,omitempty"`
AssignedAt *time.Time `theorydb:"attr:assignedAt" json:"assigned_at,omitempty"`
Category string `theorydb:"attr:category" json:"category"`
Severity string `theorydb:"attr:severity" json:"severity"`
Reason string `theorydb:"attr:reason" json:"reason"`
Evidence map[string]interface{} `theorydb:"attr:evidence" json:"evidence,omitempty"`
Deadline *time.Time `theorydb:"attr:deadline" json:"deadline,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
ReviewCount int `theorydb:"attr:reviewCount" json:"review_count"`
LastReviewedAt *time.Time `theorydb:"attr:lastReviewedAt" json:"last_reviewed_at,omitempty"`
// DynamoDB TTL (30 days for queue items)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ModerationReviewQueue represents items in the review queue
func (ModerationReviewQueue) TableName ¶
func (ModerationReviewQueue) TableName() string
TableName returns the DynamoDB table name
func (*ModerationReviewQueue) UpdateKeys ¶
func (m *ModerationReviewQueue) UpdateKeys()
UpdateKeys updates the GSI keys based on current field values
type ModerationSample ¶
type ModerationSample struct {
// Primary key - Samples by object
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "MLSAMPLE#{object_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "VERSION#{version}#{sample_id}"
// GSI1 - Reviewer queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "REVIEWER#{reviewer_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "TIME#{RFC3339}"
// GSI2 - Label/Severity queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "LABEL#{label}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "CONFIDENCE#{confidence}#{RFC3339}"
// GSI3 - Sample ID lookups
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk,omitempty"` // Format: "SAMPLEID#{sample_id}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk,omitempty"` // Format: "SAMPLEID#{sample_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "ML_SAMPLE"
// Sample fields
ID string `theorydb:"attr:id" json:"id"` // Unique sample ID
ObjectID string `theorydb:"attr:objectID" json:"object_id"` // Object being labeled
ObjectType string `theorydb:"attr:objectType" json:"object_type"` // status, account, media
Label string `theorydb:"attr:label" json:"label"` // The moderation label (spam, hate_speech, etc.)
ReviewerID string `theorydb:"attr:reviewerID" json:"reviewer_id"` // Who labeled this sample
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When sample was created
Confidence float64 `theorydb:"attr:confidence" json:"confidence"` // Reviewer confidence (0.0-1.0)
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"` // Additional context
// DynamoDB TTL (samples can expire after use)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ModerationSample represents a labeled training sample for ML moderation
func (*ModerationSample) GetPK ¶
func (m *ModerationSample) GetPK() string
GetPK returns the primary partition key
func (*ModerationSample) GetSK ¶
func (m *ModerationSample) GetSK() string
GetSK returns the primary sort key
func (ModerationSample) TableName ¶
func (ModerationSample) TableName() string
TableName returns the DynamoDB table name
func (*ModerationSample) UpdateKeys ¶
func (m *ModerationSample) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type ModerationStatus ¶
type ModerationStatus string
ModerationStatus represents the current status of a moderation case
const ( // ModerationStatusPending represents a pending moderation status ModerationStatusPending ModerationStatus = "pending" // ModerationStatusReviewing represents a reviewing moderation status ModerationStatusReviewing ModerationStatus = "reviewing" // ModerationStatusActioned represents an actioned moderation status ModerationStatusActioned ModerationStatus = "actioned" // ModerationStatusAppealed represents an appealed moderation status ModerationStatusAppealed ModerationStatus = "appealed" // ModerationStatusResolved represents a resolved moderation status ModerationStatusResolved ModerationStatus = "resolved" // ModerationStatusDismissed represents a dismissed moderation status ModerationStatusDismissed ModerationStatus = "dismissed" )
type Move ¶
type Move struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // MOVE#ACTOR#{actor}
SK string `theorydb:"sk,attr:SK" json:"SK"` // TARGET#{target}
// GSI1 for reverse lookups (moves to a target)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // MOVE#TARGET#{target}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // ACTOR#{actor}
// Move data (nested in legacy)
ID string `theorydb:"attr:id" json:"ID"` // The move activity ID
Actor string `theorydb:"attr:actor" json:"Actor"` // The old account moving
Target string `theorydb:"attr:target" json:"Target"` // The new account location
Published time.Time `theorydb:"attr:published" json:"Published"` // When the move was announced
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"` // Database timestamp
// Optional TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"TTL,omitempty"`
// contains filtered or unexported fields
}
Move represents an account move/migration activity
func (*Move) BeforeCreate ¶
BeforeCreate sets up the record before creation
func (*Move) ExtractActor ¶
ExtractActor extracts the actor from PK
func (*Move) ExtractTarget ¶
ExtractTarget extracts the target from SK
func (*Move) UpdateKeys ¶
func (m *Move) UpdateKeys()
UpdateKeys updates GSI keys based on actor and target
type Mute ¶
type Mute struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // MUTE#{username}
SK string `theorydb:"sk,attr:SK" json:"SK"` // MUTED#{muted_username}
// GSI1 for reverse lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // MUTED#{muted_username}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // MUTER#{username}
// Core fields from legacy
Type string `theorydb:"attr:type" json:"Type"` // Always "Mute"
Actor string `theorydb:"attr:actor" json:"Actor"` // Full actor ID who is muting
Object string `theorydb:"attr:object" json:"Object"` // Full actor ID being muted
ID string `theorydb:"attr:id" json:"ID"` // Mute activity ID
HideNotifications bool `theorydb:"attr:hideNotifications" json:"HideNotifications"` // Whether to hide notifications from this user
Published time.Time `theorydb:"attr:published" json:"Published"` // When the mute was published
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"` // When stored in DB
// contains filtered or unexported fields
}
Mute represents a mute relationship between actors
func (*Mute) BeforeCreate ¶
BeforeCreate prepares the Mute for creation
func (*Mute) UpdateKeys ¶
UpdateKeys sets the primary and GSI keys based on the actor usernames This implements the BaseModel interface requirement
type Notification ¶
type Notification struct {
// Primary key - using user ID as partition key with notification sort key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "user#{userID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "notif#{timestamp}#{notificationID}"
// GSI1 - Notification type queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "NOTIF_TYPE#{type}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{created_at}#{userID}#{id}"
// GSI2 - Actor notifications (who triggered notifications)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "NOTIF_ACTOR#{actorID}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{created_at}#{userID}#{id}"
// GSI3 - Group key for notification consolidation
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "NOTIF_GROUP#{groupKey}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{created_at}#{id}"
// GSI4 - Direct notification ID lookup, scoped by recipient
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk"` // Format: "NOTIF_ID#{notificationID}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk"` // Format: "USER#{userID}"
// Core notification data
ID string `theorydb:"attr:id" json:"id"`
UserID string `theorydb:"attr:userID" json:"user_id"` // User receiving the notification
Type string `theorydb:"attr:type" json:"type"` // "mention", "reblog", "favourite", "follow", "follow_request", etc.
// Actor information (who triggered the notification)
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
ActorType string `theorydb:"attr:actorType" json:"actor_type,omitempty"` // "user", "remote_actor"
// Target information (what the notification is about)
TargetID string `theorydb:"attr:targetID" json:"target_id,omitempty"`
TargetType string `theorydb:"attr:targetType" json:"target_type,omitempty"` // "status", "user", "account"
// Notification content
Title string `theorydb:"attr:title" json:"title,omitempty"`
Body string `theorydb:"attr:body" json:"body,omitempty"`
// Additional data payload
Data map[string]interface{} `theorydb:"attr:data" json:"data,omitempty"`
// Status tracking
IsRead bool `theorydb:"attr:isRead" json:"is_read"`
ReadAt *time.Time `theorydb:"attr:readAt" json:"read_at,omitempty"`
// Push notification status
PushSent bool `theorydb:"attr:pushSent" json:"push_sent"`
PushSentAt *time.Time `theorydb:"attr:pushSentAt" json:"push_sent_at,omitempty"`
PushError string `theorydb:"attr:pushError" json:"push_error,omitempty"`
// Grouping for similar notifications
GroupKey string `theorydb:"attr:groupKey" json:"group_key"` // Key for grouping similar notifications
GroupCount int `theorydb:"attr:groupCount" json:"group_count"` // Number of notifications in this group
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (30 days)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Notification represents a user notification
func NewFavouriteNotification ¶
func NewFavouriteNotification(userID, likerID, statusID string) *Notification
NewFavouriteNotification creates a favourite notification
func NewFollowNotification ¶
func NewFollowNotification(userID, followerID string) *Notification
NewFollowNotification creates a follow notification
func NewFollowRequestNotification ¶
func NewFollowRequestNotification(userID, requesterID string) *Notification
NewFollowRequestNotification creates a follow request notification
func NewMentionNotification ¶
func NewMentionNotification(userID, actorID, statusID string) *Notification
NewMentionNotification creates a mention notification
func NewReblogNotification ¶
func NewReblogNotification(userID, rebloggerID, statusID string) *Notification
NewReblogNotification creates a reblog notification
func NewReplyNotification ¶ added in v1.1.50
func NewReplyNotification(userID, actorID, statusID string) *Notification
NewReplyNotification creates a reply notification
func (*Notification) BeforeCreate ¶
func (n *Notification) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*Notification) BeforeUpdate ¶
func (n *Notification) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*Notification) GetData ¶
func (n *Notification) GetData(key string) (interface{}, bool)
GetData gets a data field
func (*Notification) GetPK ¶
func (n *Notification) GetPK() string
GetPK returns the primary key for BaseRepository interface
func (*Notification) GetSK ¶
func (n *Notification) GetSK() string
GetSK returns the sort key for BaseRepository interface
func (*Notification) IncrementGroupCount ¶
func (n *Notification) IncrementGroupCount()
IncrementGroupCount increments the group count for consolidated notifications
func (*Notification) MarkPushFailed ¶
func (n *Notification) MarkPushFailed(errorMsg string)
MarkPushFailed marks the push notification as failed
func (*Notification) MarkPushSent ¶
func (n *Notification) MarkPushSent()
MarkPushSent marks the push notification as sent
func (*Notification) MarkRead ¶
func (n *Notification) MarkRead()
MarkRead marks the notification as read
func (*Notification) MarkUnread ¶
func (n *Notification) MarkUnread()
MarkUnread marks the notification as unread
func (*Notification) SetData ¶
func (n *Notification) SetData(key string, value interface{})
SetData sets a data field
func (*Notification) ShouldSendPush ¶
func (n *Notification) ShouldSendPush() bool
ShouldSendPush determines if a push notification should be sent
func (Notification) TableName ¶
func (Notification) TableName() string
TableName returns the DynamoDB table name for the Notification model
func (*Notification) UpdateKeys ¶
func (n *Notification) UpdateKeys() error
UpdateKeys updates the GSI keys for this notification (required by DynamORM)
func (*Notification) Validate ¶
func (n *Notification) Validate() error
Validate performs validation on the Notification
type NotificationBudget ¶
type NotificationBudget struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "NOTIF_BUDGET#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PERIOD#{period}"
// Budget details
Username string `theorydb:"attr:username" json:"username"`
Period string `theorydb:"attr:period" json:"period"` // daily, weekly, monthly
LimitMicroCents int64 `theorydb:"attr:limitMicroCents" json:"limit_micro_cents"` // Budget limit in micro-cents
LimitDollars float64 `theorydb:"attr:limitDollars" json:"limit_dollars"` // Budget limit in dollars
SpentMicroCents int64 `theorydb:"attr:spentMicroCents" json:"spent_micro_cents"` // Amount spent in current period
SpentDollars float64 `theorydb:"attr:spentDollars" json:"spent_dollars"` // Amount spent in dollars
RemainingMicroCents int64 `theorydb:"attr:remainingMicroCents" json:"remaining_micro_cents"` // Remaining budget
RemainingDollars float64 `theorydb:"attr:remainingDollars" json:"remaining_dollars"` // Remaining budget in dollars
// Period tracking
PeriodStart time.Time `theorydb:"attr:periodStart" json:"period_start"`
PeriodEnd time.Time `theorydb:"attr:periodEnd" json:"period_end"`
NextResetTime time.Time `theorydb:"attr:nextResetTime" json:"next_reset_time"`
// Notification limits
MaxNotificationsPerPeriod int64 `theorydb:"attr:maxNotificationsPerPeriod" json:"max_notifications_per_period,omitempty"`
NotificationsSentThisPeriod int64 `theorydb:"attr:notificationsSentThisPeriod" json:"notifications_sent_this_period"`
// Enforcement settings
Enabled bool `theorydb:"attr:enabled" json:"enabled"` // Whether budget is actively enforced
SendWarningAt float64 `theorydb:"attr:sendWarningAt" json:"send_warning_at"` // Send warning at X% of budget
BlockDeliveryAt float64 `theorydb:"attr:blockDeliveryAt" json:"block_delivery_at"` // Block delivery at X% of budget
AllowedDeliveryMethods []string `theorydb:"attr:allowedDeliveryMethods" json:"allowed_delivery_methods,omitempty"` // Restrict to specific methods
// Status
BudgetExceeded bool `theorydb:"attr:budgetExceeded" json:"budget_exceeded"`
WarningsSent int `theorydb:"attr:warningsSent" json:"warnings_sent"`
LastWarningTime time.Time `theorydb:"attr:lastWarningTime" json:"last_warning_time,omitempty"`
LastExceededTime time.Time `theorydb:"attr:lastExceededTime" json:"last_exceeded_time,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
NotificationBudget represents a budget limit for notification sending per user
func (*NotificationBudget) AddSpending ¶
func (n *NotificationBudget) AddSpending(costMicroCents int64) bool
AddSpending adds spending to the budget and checks limits
func (*NotificationBudget) BeforeCreate ¶
func (n *NotificationBudget) BeforeCreate() error
BeforeCreate sets up the budget before creation
func (*NotificationBudget) BeforeUpdate ¶
func (n *NotificationBudget) BeforeUpdate() error
BeforeUpdate sets up the budget before update
func (*NotificationBudget) CalculateDollarAmounts ¶
func (n *NotificationBudget) CalculateDollarAmounts()
CalculateDollarAmounts calculates dollar amounts from micro-cents
func (*NotificationBudget) CalculateRemaining ¶
func (n *NotificationBudget) CalculateRemaining()
CalculateRemaining calculates remaining budget
func (*NotificationBudget) GetPK ¶
func (n *NotificationBudget) GetPK() string
GetPK returns the partition key
func (*NotificationBudget) GetSK ¶
func (n *NotificationBudget) GetSK() string
GetSK returns the sort key
func (*NotificationBudget) IsMethodAllowed ¶
func (n *NotificationBudget) IsMethodAllowed(method string) bool
IsMethodAllowed checks if a delivery method is allowed
func (*NotificationBudget) ResetPeriod ¶
func (n *NotificationBudget) ResetPeriod(newPeriodStart, newPeriodEnd time.Time)
ResetPeriod resets the budget for a new period
func (*NotificationBudget) ShouldBlockDelivery ¶
func (n *NotificationBudget) ShouldBlockDelivery() bool
ShouldBlockDelivery checks if delivery should be blocked
func (*NotificationBudget) ShouldSendWarning ¶
func (n *NotificationBudget) ShouldSendWarning() bool
ShouldSendWarning checks if a warning should be sent
func (NotificationBudget) TableName ¶
func (NotificationBudget) TableName() string
TableName returns the DynamoDB table backing NotificationBudget.
func (*NotificationBudget) UpdateKeys ¶
func (n *NotificationBudget) UpdateKeys() error
UpdateKeys updates the primary and sort keys
type NotificationBuilder ¶
type NotificationBuilder struct {
// contains filtered or unexported fields
}
NotificationBuilder helps create notifications with proper defaults
func NewNotificationBuilder ¶
func NewNotificationBuilder() *NotificationBuilder
NewNotificationBuilder creates a new notification builder
func (*NotificationBuilder) AboutTarget ¶
func (nb *NotificationBuilder) AboutTarget(targetID, targetType string) *NotificationBuilder
AboutTarget sets the target of the notification
func (*NotificationBuilder) Build ¶
func (nb *NotificationBuilder) Build() *Notification
Build creates the notification
func (*NotificationBuilder) ForUser ¶
func (nb *NotificationBuilder) ForUser(userID string) *NotificationBuilder
ForUser sets the user ID for the notification
func (*NotificationBuilder) FromActor ¶
func (nb *NotificationBuilder) FromActor(actorID, actorType string) *NotificationBuilder
FromActor sets the actor who triggered the notification
func (*NotificationBuilder) OfType ¶
func (nb *NotificationBuilder) OfType(notifType string) *NotificationBuilder
OfType sets the notification type
func (NotificationBuilder) TableName ¶
func (NotificationBuilder) TableName() string
TableName returns the DynamoDB table backing NotificationBuilder.
func (*NotificationBuilder) WithContent ¶
func (nb *NotificationBuilder) WithContent(title, body string) *NotificationBuilder
WithContent sets the notification content
func (*NotificationBuilder) WithData ¶
func (nb *NotificationBuilder) WithData(key string, value interface{}) *NotificationBuilder
WithData adds data to the notification
func (*NotificationBuilder) WithGroupKey ¶
func (nb *NotificationBuilder) WithGroupKey(groupKey string) *NotificationBuilder
WithGroupKey sets a custom group key
type NotificationChannelCostStats ¶
type NotificationChannelCostStats struct {
Channel string `json:"channel"`
Count int64 `json:"count"`
SuccessfulDeliveries int64 `json:"successful_deliveries"`
FailedDeliveries int64 `json:"failed_deliveries"`
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
TotalCostDollars float64 `json:"total_cost_dollars"`
AverageCostMicroCents int64 `json:"average_cost_micro_cents"`
AverageCostDollars float64 `json:"average_cost_dollars"`
SuccessRate float64 `json:"success_rate"`
AverageDeliveryTimeMs float64 `json:"average_delivery_time_ms"`
}
NotificationChannelCostStats represents cost statistics for a specific delivery channel
func (NotificationChannelCostStats) TableName ¶
func (NotificationChannelCostStats) TableName() string
TableName returns the DynamoDB table backing NotificationChannelCostStats.
type NotificationCostAggregation ¶
type NotificationCostAggregation struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "NOTIF_AGG#{period}#{delivery_method}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "WINDOW#{windowStart}"
// Aggregation details
Period string `theorydb:"attr:period" json:"period"` // daily, hourly, weekly, monthly
DeliveryMethod string `theorydb:"attr:deliveryMethod" json:"delivery_method"` // push, websocket, all
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"`
// Aggregate statistics
TotalNotifications int64 `theorydb:"attr:totalNotifications" json:"total_notifications"`
SuccessfulDeliveries int64 `theorydb:"attr:successfulDeliveries" json:"successful_deliveries"`
FailedDeliveries int64 `theorydb:"attr:failedDeliveries" json:"failed_deliveries"`
TotalRetries int64 `theorydb:"attr:totalRetries" json:"total_retries"`
// Cost aggregations (micro-cents)
TotalPushCostMicroCents int64 `theorydb:"attr:totalPushCostMicroCents" json:"total_push_cost_micro_cents"`
TotalWebSocketCostMicroCents int64 `theorydb:"attr:totalWebSocketCostMicroCents" json:"total_websocket_cost_micro_cents"`
TotalLambdaCostMicroCents int64 `theorydb:"attr:totalLambdaCostMicroCents" json:"total_lambda_cost_micro_cents"`
TotalDynamoDBCostMicroCents int64 `theorydb:"attr:totalDynamoDBCostMicroCents" json:"total_dynamodb_cost_micro_cents"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
// Cost aggregations (dollars)
TotalPushCostDollars float64 `theorydb:"attr:totalPushCostDollars" json:"total_push_cost_dollars"`
TotalWebSocketCostDollars float64 `theorydb:"attr:totalWebSocketCostDollars" json:"total_websocket_cost_dollars"`
TotalLambdaCostDollars float64 `theorydb:"attr:totalLambdaCostDollars" json:"total_lambda_cost_dollars"`
TotalDynamoDBCostDollars float64 `theorydb:"attr:totalDynamoDBCostDollars" json:"total_dynamodb_cost_dollars"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
// Performance metrics
AverageProcessingTimeMs float64 `theorydb:"attr:averageProcessingTimeMs" json:"average_processing_time_ms"`
AverageDeliveryTimeMs float64 `theorydb:"attr:averageDeliveryTimeMs" json:"average_delivery_time_ms"`
AverageTotalTimeMs float64 `theorydb:"attr:averageTotalTimeMs" json:"average_total_time_ms"`
// Rate calculations
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"` // Percentage of successful deliveries
RetryRate float64 `theorydb:"attr:retryRate" json:"retry_rate"` // Percentage requiring retries
CostPerDelivery float64 `theorydb:"attr:costPerDelivery" json:"cost_per_delivery"` // Average cost per delivery attempt
// Breakdown by notification type
TypeBreakdown map[string]*NotificationTypeCostStats `theorydb:"attr:typeBreakdown" json:"type_breakdown,omitempty"`
ChannelBreakdown map[string]*NotificationChannelCostStats `theorydb:"attr:channelBreakdown" json:"channel_breakdown,omitempty"`
UserBreakdown map[string]*NotificationUserCostStats `theorydb:"attr:userBreakdown" json:"user_breakdown,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
NotificationCostAggregation aggregates notification costs by period
func (*NotificationCostAggregation) BeforeCreate ¶
func (n *NotificationCostAggregation) BeforeCreate() error
BeforeCreate sets up the aggregation before creation
func (*NotificationCostAggregation) BeforeUpdate ¶
func (n *NotificationCostAggregation) BeforeUpdate() error
BeforeUpdate sets up the aggregation before update
func (*NotificationCostAggregation) CalculateDollarAmounts ¶
func (n *NotificationCostAggregation) CalculateDollarAmounts()
CalculateDollarAmounts calculates dollar amounts from micro-cents
func (*NotificationCostAggregation) CalculateRates ¶
func (n *NotificationCostAggregation) CalculateRates()
CalculateRates calculates success rate, retry rate, and cost per delivery
func (*NotificationCostAggregation) GetPK ¶
func (n *NotificationCostAggregation) GetPK() string
GetPK returns the partition key
func (*NotificationCostAggregation) GetSK ¶
func (n *NotificationCostAggregation) GetSK() string
GetSK returns the sort key
func (NotificationCostAggregation) TableName ¶
func (NotificationCostAggregation) TableName() string
TableName returns the DynamoDB table backing NotificationCostAggregation.
func (*NotificationCostAggregation) UpdateKeys ¶
func (n *NotificationCostAggregation) UpdateKeys() error
UpdateKeys updates the primary and sort keys
type NotificationCostTracking ¶
type NotificationCostTracking struct {
// Primary keys - notification cost tracking uses NOTIF_COST#{notification_id}#{timestamp} pattern
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1 for user queries - USER#{username}, COST#{timestamp}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2 for delivery method queries - METHOD#{delivery_method}, TIMESTAMP#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// GSI3 for daily aggregation - DAILY#{date}, COST#{timestamp}
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"`
// Core tracking fields
ID string `theorydb:"attr:id" json:"id"`
NotificationID string `theorydb:"attr:notificationID" json:"notification_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
DeliveryMethod string `theorydb:"attr:deliveryMethod" json:"delivery_method"` // push, websocket
NotificationType string `theorydb:"attr:notificationType" json:"notification_type"` // mention, follow, favourite, etc.
Channel string `theorydb:"attr:channel" json:"channel"` // specific channel within method
Success bool `theorydb:"attr:success" json:"success"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"`
// Cost breakdown (all in micro-cents for precision)
PushCostMicroCents int64 `theorydb:"attr:pushCostMicroCents" json:"push_cost_micro_cents"`
WebSocketCostMicroCents int64 `theorydb:"attr:webSocketCostMicroCents" json:"websocket_cost_micro_cents"`
LambdaCostMicroCents int64 `theorydb:"attr:lambdaCostMicroCents" json:"lambda_cost_micro_cents"`
DynamoDBCostMicroCents int64 `theorydb:"attr:dynamoDBCostMicroCents" json:"dynamodb_cost_micro_cents"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
// Cost breakdown in dollars (calculated from micro-cents)
PushCostDollars float64 `theorydb:"attr:pushCostDollars" json:"push_cost_dollars"`
WebSocketCostDollars float64 `theorydb:"attr:webSocketCostDollars" json:"websocket_cost_dollars"`
LambdaCostDollars float64 `theorydb:"attr:lambdaCostDollars" json:"lambda_cost_dollars"`
DynamoDBCostDollars float64 `theorydb:"attr:dynamoDBCostDollars" json:"dynamodb_cost_dollars"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
// Performance metrics
ProcessingTimeMs int64 `theorydb:"attr:processingTimeMs" json:"processing_time_ms"`
DeliveryTimeMs int64 `theorydb:"attr:deliveryTimeMs" json:"delivery_time_ms"`
TotalTimeMs int64 `theorydb:"attr:totalTimeMs" json:"total_time_ms"`
ResponseCode int `theorydb:"attr:responseCode" json:"response_code,omitempty"`
ResponseSize int64 `theorydb:"attr:responseSize" json:"response_size,omitempty"`
// Context and metadata
RequestID string `theorydb:"attr:requestID" json:"request_id"`
ServiceName string `theorydb:"attr:serviceName" json:"service_name"` // notification-processor
LambdaFunctionName string `theorydb:"attr:lambdaFunctionName" json:"lambda_function_name"`
LambdaRequestID string `theorydb:"attr:lambdaRequestID" json:"lambda_request_id"`
Properties map[string]interface{} `theorydb:"attr:properties" json:"properties,omitempty"` // Additional metadata
Tags map[string]string `theorydb:"attr:tags" json:"tags,omitempty"` // User-defined tags
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
NotificationCostTracking tracks costs for notification delivery operations
func (*NotificationCostTracking) AddCost ¶
func (n *NotificationCostTracking) AddCost(method string, costMicroCents int64)
AddCost adds cost for a specific delivery method
func (*NotificationCostTracking) BeforeCreate ¶
func (n *NotificationCostTracking) BeforeCreate() error
BeforeCreate sets up the notification cost tracking before creation
func (*NotificationCostTracking) BeforeUpdate ¶
func (n *NotificationCostTracking) BeforeUpdate() error
BeforeUpdate sets up the notification cost tracking before update
func (*NotificationCostTracking) CalculateDollarAmounts ¶
func (n *NotificationCostTracking) CalculateDollarAmounts()
CalculateDollarAmounts calculates dollar amounts from micro-cents
func (*NotificationCostTracking) GetPK ¶
func (n *NotificationCostTracking) GetPK() string
GetPK returns the partition key
func (*NotificationCostTracking) GetSK ¶
func (n *NotificationCostTracking) GetSK() string
GetSK returns the sort key
func (*NotificationCostTracking) SetError ¶
func (n *NotificationCostTracking) SetError(errorMsg string)
SetError marks the tracking as failed with an error
func (*NotificationCostTracking) SetSuccess ¶
func (n *NotificationCostTracking) SetSuccess()
SetSuccess marks the tracking as successful
func (NotificationCostTracking) TableName ¶
func (NotificationCostTracking) TableName() string
TableName returns the DynamoDB table backing NotificationCostTracking.
func (*NotificationCostTracking) UpdateKeys ¶
func (n *NotificationCostTracking) UpdateKeys() error
UpdateKeys updates all the key fields for DynamoDB
type NotificationCostTrackingBuilder ¶
type NotificationCostTrackingBuilder struct {
// contains filtered or unexported fields
}
NotificationCostTrackingBuilder helps build notification cost tracking records
func NewNotificationCostTrackingBuilder ¶
func NewNotificationCostTrackingBuilder() *NotificationCostTrackingBuilder
NewNotificationCostTrackingBuilder creates a new builder
func (*NotificationCostTrackingBuilder) Build ¶
func (b *NotificationCostTrackingBuilder) Build() *NotificationCostTracking
Build returns the completed notification cost tracking record
func (NotificationCostTrackingBuilder) TableName ¶
func (NotificationCostTrackingBuilder) TableName() string
TableName returns the DynamoDB table backing NotificationCostTrackingBuilder.
func (*NotificationCostTrackingBuilder) WithContext ¶
func (b *NotificationCostTrackingBuilder) WithContext(requestID, serviceName, functionName, lambdaRequestID string) *NotificationCostTrackingBuilder
WithContext sets context information
func (*NotificationCostTrackingBuilder) WithCosts ¶
func (b *NotificationCostTrackingBuilder) WithCosts(pushCost, websocketCost, lambdaCost, dynamodbCost int64) *NotificationCostTrackingBuilder
WithCosts sets cost details
func (*NotificationCostTrackingBuilder) WithDelivery ¶
func (b *NotificationCostTrackingBuilder) WithDelivery(method, channel string, success bool, retryCount int) *NotificationCostTrackingBuilder
WithDelivery sets delivery details
func (*NotificationCostTrackingBuilder) WithError ¶
func (b *NotificationCostTrackingBuilder) WithError(errorMsg string) *NotificationCostTrackingBuilder
WithError sets error information
func (*NotificationCostTrackingBuilder) WithNotification ¶
func (b *NotificationCostTrackingBuilder) WithNotification(notificationID, userID, username, notificationType string) *NotificationCostTrackingBuilder
WithNotification sets notification details
func (*NotificationCostTrackingBuilder) WithPerformance ¶
func (b *NotificationCostTrackingBuilder) WithPerformance(processingTimeMs, deliveryTimeMs int64, responseCode int, responseSize int64) *NotificationCostTrackingBuilder
WithPerformance sets performance metrics
func (*NotificationCostTrackingBuilder) WithProperty ¶
func (b *NotificationCostTrackingBuilder) WithProperty(key string, value interface{}) *NotificationCostTrackingBuilder
WithProperty adds a custom property
func (*NotificationCostTrackingBuilder) WithTag ¶
func (b *NotificationCostTrackingBuilder) WithTag(key, value string) *NotificationCostTrackingBuilder
WithTag adds a custom tag
func (*NotificationCostTrackingBuilder) WithTimestamp ¶
func (b *NotificationCostTrackingBuilder) WithTimestamp(timestamp time.Time) *NotificationCostTrackingBuilder
WithTimestamp sets the timestamp
type NotificationDelivery ¶
type NotificationDelivery struct {
// Primary keys - using notification ID and delivery method
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "NOTIFICATION#{notificationID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "DELIVERY#{method}"
// Core fields
NotificationID string `theorydb:"attr:notificationID" json:"notification_id"`
DeliveryMethod string `theorydb:"attr:deliveryMethod" json:"delivery_method"` // "push", "websocket", "web"
Status string `theorydb:"attr:status" json:"status"` // "pending", "sent", "failed"
AttemptCount int `theorydb:"attr:attemptCount" json:"attempt_count"`
LastAttempt time.Time `theorydb:"attr:lastAttempt" json:"last_attempt"`
Error string `theorydb:"attr:error" json:"error,omitempty"` // Error message if failed
SentAt time.Time `theorydb:"attr:sentAt" json:"sent_at,omitempty"`
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for cleanup (7 days after creation)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
NotificationDelivery tracks delivery attempts for notifications
func NewNotificationDelivery ¶
func NewNotificationDelivery(notificationID, method string) *NotificationDelivery
NewNotificationDelivery creates a new delivery tracking record
func (*NotificationDelivery) BeforeCreate ¶
func (n *NotificationDelivery) BeforeCreate() error
BeforeCreate is called before creating a new delivery record
func (*NotificationDelivery) BeforeUpdate ¶
func (n *NotificationDelivery) BeforeUpdate() error
BeforeUpdate is called before updating a delivery record
func (*NotificationDelivery) CanRetry ¶
func (n *NotificationDelivery) CanRetry() bool
CanRetry determines if this delivery can be retried
func (*NotificationDelivery) IncrementAttempt ¶
func (n *NotificationDelivery) IncrementAttempt()
IncrementAttempt increments the attempt counter
func (*NotificationDelivery) MarkFailed ¶
func (n *NotificationDelivery) MarkFailed(errorMsg string)
MarkFailed marks the delivery as failed
func (*NotificationDelivery) MarkPending ¶
func (n *NotificationDelivery) MarkPending()
MarkPending marks the delivery as pending
func (*NotificationDelivery) MarkSent ¶
func (n *NotificationDelivery) MarkSent()
MarkSent marks the delivery as sent
func (NotificationDelivery) TableName ¶
func (NotificationDelivery) TableName() string
TableName returns the DynamoDB table name
func (*NotificationDelivery) UpdateKeys ¶
func (n *NotificationDelivery) UpdateKeys()
UpdateKeys updates the primary keys based on the model's fields
func (*NotificationDelivery) Validate ¶
func (n *NotificationDelivery) Validate() error
Validate performs validation on the NotificationDelivery
type NotificationFilter ¶
type NotificationFilter struct {
Types []string `json:"types,omitempty"`
AccountID string `json:"account_id,omitempty"`
MinID string `json:"min_id,omitempty"`
MaxID string `json:"max_id,omitempty"`
SinceID string `json:"since_id,omitempty"`
Limit int `json:"limit,omitempty"`
ExcludeTypes []string `json:"exclude_types,omitempty"`
}
NotificationFilter represents a lightweight filter configuration for hashtag notifications.
func (NotificationFilter) TableName ¶
func (NotificationFilter) TableName() string
TableName returns the DynamoDB table backing NotificationFilter.
type NotificationLegacy ¶
type NotificationLegacy struct {
PK string `theorydb:"pk,attr:PK" json:"PK"` // NOTIFICATIONS#username
SK string `theorydb:"sk,attr:SK" json:"SK"` // timestamp#notificationID
ID string `theorydb:"attr:id" json:"ID"`
Type string `theorydb:"attr:type" json:"Type"`
Username string `theorydb:"attr:username" json:"Username"`
AccountID string `theorydb:"attr:accountID" json:"AccountID"`
StatusID string `theorydb:"attr:statusID" json:"StatusID,omitempty"`
Read bool `theorydb:"attr:read" json:"Read"`
CreatedAt int64 `theorydb:"attr:createdAt" json:"CreatedAt"` // Unix timestamp for sorting
TTL int64 `theorydb:"ttl,attr:ttl" json:"TTL"` // 30 days auto-deletion
// contains filtered or unexported fields
}
NotificationLegacy represents a notification with legacy key patterns Used for compatibility with existing notification data
func NewNotificationLegacy ¶
func NewNotificationLegacy(username, notificationType, accountID string) *NotificationLegacy
NewNotificationLegacy creates a new legacy notification with proper initialization
func (*NotificationLegacy) SetPrimaryKey ¶
func (n *NotificationLegacy) SetPrimaryKey(username string)
SetPrimaryKey sets the primary key for the notification
func (*NotificationLegacy) SetSortKey ¶
func (n *NotificationLegacy) SetSortKey(timestamp int64, id string)
SetSortKey sets the sort key for the notification
func (NotificationLegacy) TableName ¶
func (NotificationLegacy) TableName() string
TableName returns the DynamoDB table name
func (*NotificationLegacy) UpdateKeys ¶
func (n *NotificationLegacy) UpdateKeys() error
UpdateKeys updates the notification keys
type NotificationPreferences ¶
type NotificationPreferences struct {
// Keys - using legacy pattern
PK string `theorydb:"pk,attr:PK" json:"-"` // USER#username
SK string `theorydb:"sk,attr:SK" json:"-"` // NOTIFICATION_PREFS
// Fields matching legacy storage.NotificationPreferences
Username string `theorydb:"attr:username" json:"username"`
EmailEnabled bool `theorydb:"attr:emailEnabled" json:"email_enabled"`
PushEnabled bool `theorydb:"attr:pushEnabled" json:"push_enabled"`
FollowEnabled bool `theorydb:"attr:followEnabled" json:"follow_enabled"`
MentionEnabled bool `theorydb:"attr:mentionEnabled" json:"mention_enabled"`
ReblogEnabled bool `theorydb:"attr:reblogEnabled" json:"reblog_enabled"`
FavoriteEnabled bool `theorydb:"attr:favoriteEnabled" json:"favorite_enabled"`
PollEnabled bool `theorydb:"attr:pollEnabled" json:"poll_enabled"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Additional notification preferences
FollowNotifications bool `theorydb:"attr:followNotifications" json:"follow_notifications"`
MentionNotifications bool `theorydb:"attr:mentionNotifications" json:"mention_notifications"`
ReblogNotifications bool `theorydb:"attr:reblogNotifications" json:"reblog_notifications"`
FavoriteNotifications bool `theorydb:"attr:favoriteNotifications" json:"favorite_notifications"`
PollNotifications bool `theorydb:"attr:pollNotifications" json:"poll_notifications"`
NewFollowerNotifications bool `theorydb:"attr:newFollowerNotifications" json:"new_follower_notifications"`
DigestEmail bool `theorydb:"attr:digestEmail" json:"digest_email"`
// contains filtered or unexported fields
}
NotificationPreferences represents user notification preferences in DynamoDB
func (*NotificationPreferences) BeforeCreate ¶
func (n *NotificationPreferences) BeforeCreate() error
BeforeCreate is called before creating a new notification preferences record
func (*NotificationPreferences) BeforeUpdate ¶
func (n *NotificationPreferences) BeforeUpdate() error
BeforeUpdate is called before updating notification preferences
func (NotificationPreferences) TableName ¶
func (NotificationPreferences) TableName() string
TableName returns the DynamoDB table backing NotificationPreferences.
func (*NotificationPreferences) UpdateKeys ¶
func (n *NotificationPreferences) UpdateKeys()
UpdateKeys updates the primary and GSI keys based on the model's fields
type NotificationTypeCostStats ¶
type NotificationTypeCostStats struct {
Type string `json:"type"`
Count int64 `json:"count"`
SuccessfulDeliveries int64 `json:"successful_deliveries"`
FailedDeliveries int64 `json:"failed_deliveries"`
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
TotalCostDollars float64 `json:"total_cost_dollars"`
AverageCostMicroCents int64 `json:"average_cost_micro_cents"`
AverageCostDollars float64 `json:"average_cost_dollars"`
SuccessRate float64 `json:"success_rate"`
}
NotificationTypeCostStats represents cost statistics for a specific notification type
func (NotificationTypeCostStats) TableName ¶
func (NotificationTypeCostStats) TableName() string
TableName returns the DynamoDB table backing NotificationTypeCostStats.
type NotificationUserCostStats ¶
type NotificationUserCostStats struct {
Username string `json:"username"`
Count int64 `json:"count"`
SuccessfulDeliveries int64 `json:"successful_deliveries"`
FailedDeliveries int64 `json:"failed_deliveries"`
TotalCostMicroCents int64 `json:"total_cost_micro_cents"`
TotalCostDollars float64 `json:"total_cost_dollars"`
AverageCostMicroCents int64 `json:"average_cost_micro_cents"`
AverageCostDollars float64 `json:"average_cost_dollars"`
SuccessRate float64 `json:"success_rate"`
}
NotificationUserCostStats represents cost statistics for a specific user
func (NotificationUserCostStats) TableName ¶
func (NotificationUserCostStats) TableName() string
TableName returns the DynamoDB table backing NotificationUserCostStats.
type NumericIDMapping ¶
type NumericIDMapping struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "NUMERIC_ID#{numeric_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "METADATA"
// Mapping data
NumericID string `theorydb:"attr:numericID" json:"numeric_id"`
Username string `theorydb:"attr:username" json:"username"`
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
Type string `theorydb:"attr:type" json:"type"` // "NumericIDMapping"
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
NumericIDMapping represents a mapping from numeric ID to username for Mastodon API compatibility
func (*NumericIDMapping) BeforeCreate ¶
func (n *NumericIDMapping) BeforeCreate() error
BeforeCreate sets up the model before creation
func (NumericIDMapping) TableName ¶
func (NumericIDMapping) TableName() string
TableName returns the DynamoDB table name for the NumericIDMapping model
type OAuthApp ¶
type OAuthApp struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // OAUTH_APP#{clientID}
SK string `theorydb:"sk,attr:SK" json:"-"` // METADATA
// GSI for querying by name
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // OAUTH_APPS
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // {name}#{clientID}
// OAuth app data
ClientID string `theorydb:"attr:clientID" json:"client_id"`
ClientSecret string `theorydb:"attr:clientSecret" json:"client_secret"`
Name string `theorydb:"attr:name" json:"name"`
RedirectURIs []string `theorydb:"attr:redirectURIs" json:"redirect_uris"`
Scopes []string `theorydb:"attr:scopes" json:"scopes"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CreatedBy string `theorydb:"attr:createdBy" json:"created_by"` // User who created the app
Website string `theorydb:"attr:website" json:"website,omitempty"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Active bool `theorydb:"attr:active" json:"active"`
// contains filtered or unexported fields
}
OAuthApp represents an OAuth application stored in DynamoDB
func (*OAuthApp) IsValidRedirectURI ¶
IsValidRedirectURI checks if a redirect URI is valid for this app
func (*OAuthApp) UpdateKeys ¶
func (o *OAuthApp) UpdateKeys()
UpdateKeys updates the GSI keys based on the OAuth app data
type OAuthAuthSession ¶
type OAuthAuthSession struct {
// DynamoDB keys for authorization sessions
PK string `theorydb:"pk,attr:PK" json:"-"` // OAUTH_AUTH#sessionID
SK string `theorydb:"sk,attr:SK" json:"-"` // SESSION#sessionID
// GSI1 - User sessions lookup (optional - for authenticated users)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // USER_OAUTH#username
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // created_at#sessionID
// GSI2 - State lookup for OAuth flow
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // OAUTH_STATE#state
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // sessionID
// Core session data
SessionID string `theorydb:"attr:sessionID" json:"session_id"`
State string `theorydb:"attr:state" json:"state,omitempty"` // OAuth state parameter
// OAuth flow data
ClientID string `theorydb:"attr:clientID" json:"client_id"`
RedirectURI string `theorydb:"attr:redirectURI" json:"redirect_uri"`
Scopes []string `theorydb:"attr:scopes" json:"scopes,omitempty"`
CodeChallenge string `theorydb:"attr:codeChallenge" json:"code_challenge,omitempty"` // PKCE
CodeChallengeMethod string `theorydb:"attr:codeChallengeMethod" json:"code_challenge_method,omitempty"` // PKCE method
// User data (populated after login)
Username string `theorydb:"attr:username" json:"username,omitempty"` // Set after user authenticates
IsAuthorized bool `theorydb:"attr:isAuthorized" json:"is_authorized"` // User has authorized the app
AuthorizedAt *time.Time `theorydb:"attr:authorizedAt" json:"authorized_at,omitempty"` // When user authorized
// Security and tracking
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
DeviceID string `theorydb:"attr:deviceID" json:"device_id,omitempty"`
// Session flow tracking
FlowStep string `theorydb:"attr:flowStep" json:"flow_step"` // login, consent, authorized, error
FlowData map[string]interface{} `theorydb:"attr:flowData" json:"flow_data,omitempty"` // Additional flow context
ReturnURL string `theorydb:"attr:returnURL" json:"return_url,omitempty"` // URL to return to after login
// Security measures
CSRFToken string `theorydb:"attr:csrfToken" json:"csrf_token"` // CSRF protection
SessionNonce string `theorydb:"attr:sessionNonce" json:"session_nonce,omitempty"` // Additional entropy
IsSecure bool `theorydb:"attr:isSecure" json:"is_secure"` // Created over HTTPS
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastUsedAt time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at"`
// TTL for automatic cleanup (OAuth sessions are short-lived)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp for DynamoDB TTL
// Session validation
Version int `theorydb:"attr:version" json:"version"` // For optimistic locking
// contains filtered or unexported fields
}
OAuthAuthSession represents an OAuth authorization session during the auth flow
func (*OAuthAuthSession) Authorize ¶
func (o *OAuthAuthSession) Authorize()
Authorize marks the session as authorized by the user
func (*OAuthAuthSession) BeforeCreate ¶
func (o *OAuthAuthSession) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*OAuthAuthSession) BeforeUpdate ¶
func (o *OAuthAuthSession) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*OAuthAuthSession) CanAuthorize ¶
func (o *OAuthAuthSession) CanAuthorize() bool
CanAuthorize returns true if the session is ready for authorization
func (*OAuthAuthSession) GetContext ¶
func (o *OAuthAuthSession) GetContext(key string) (interface{}, bool)
GetContext gets a context value from flow data
func (*OAuthAuthSession) GetPK ¶
func (o *OAuthAuthSession) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*OAuthAuthSession) GetSK ¶
func (o *OAuthAuthSession) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*OAuthAuthSession) IsExpired ¶
func (o *OAuthAuthSession) IsExpired() bool
IsExpired returns true if the session has expired
func (*OAuthAuthSession) IsValid ¶
func (o *OAuthAuthSession) IsValid() bool
IsValid returns true if the session is valid (not expired)
func (*OAuthAuthSession) RemainingTime ¶
func (o *OAuthAuthSession) RemainingTime() time.Duration
RemainingTime returns the time until the session expires
func (*OAuthAuthSession) SetContext ¶
func (o *OAuthAuthSession) SetContext(key string, value interface{})
SetContext sets a context value in flow data
func (*OAuthAuthSession) SetFlowStep ¶
func (o *OAuthAuthSession) SetFlowStep(step string, data map[string]interface{})
SetFlowStep updates the current flow step and optional data
func (*OAuthAuthSession) SetUser ¶
func (o *OAuthAuthSession) SetUser(username string)
SetUser sets the username and updates GSI keys
func (OAuthAuthSession) TableName ¶
func (OAuthAuthSession) TableName() string
TableName returns the DynamoDB table name
func (*OAuthAuthSession) Touch ¶
func (o *OAuthAuthSession) Touch()
Touch updates the last used timestamp
func (*OAuthAuthSession) UpdateKeys ¶
func (o *OAuthAuthSession) UpdateKeys() error
UpdateKeys implements BaseModel interface - updates the GSI keys
func (*OAuthAuthSession) Validate ¶
func (o *OAuthAuthSession) Validate() error
Validate performs validation on the OAuth session
type OAuthClient ¶
type OAuthClient struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"-"` // OAUTH_CLIENT#clientID
SK string `theorydb:"sk,attr:SK" json:"-"` // CLIENT
GSI1PK *string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // OWNER#ownerID (for owner index)
GSI1SK *string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // CLIENT#clientID
OAuthClientsPK string `theorydb:"index:oauth-clients-index,pk,attr:oauthClientsPK" json:"-"` // OAUTH_CLIENTS
OAuthClientsSK string `theorydb:"index:oauth-clients-index,sk,attr:oauthClientsSK" json:"-"` // CREATED_AT#{ts_desc}#CLIENT#{clientID}
// Core fields
ID string `theorydb:"attr:id" json:"id,omitempty"`
ClientID string `theorydb:"attr:clientID" json:"client_id"`
ClientSecret string `theorydb:"attr:clientSecret" json:"client_secret"`
PreviousClientSecret string `theorydb:"attr:previousClientSecret,omitempty" json:"-"`
PreviousClientSecretGraceExpiresAt time.Time `theorydb:"attr:previousClientSecretGraceExpiresAt,omitempty" json:"-"`
SecretRotatedAt time.Time `theorydb:"attr:secretRotatedAt,omitempty" json:"-"`
SecretRotatedBy string `theorydb:"attr:secretRotatedBy,omitempty" json:"-"`
Name string `theorydb:"attr:name" json:"name"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Website string `theorydb:"attr:website" json:"website,omitempty"`
ClientURI string `theorydb:"attr:clientURI" json:"client_uri,omitempty"`
LogoURI string `theorydb:"attr:logoURI,omitempty" json:"logo_uri,omitempty"`
Contacts []string `theorydb:"attr:contacts,omitempty" json:"contacts,omitempty"`
TosURI string `theorydb:"attr:tosURI,omitempty" json:"tos_uri,omitempty"`
PolicyURI string `theorydb:"attr:policyURI,omitempty" json:"policy_uri,omitempty"`
SoftwareID string `theorydb:"attr:softwareID" json:"software_id,omitempty"`
SoftwareVersion string `theorydb:"attr:softwareVersion" json:"software_version,omitempty"`
RedirectURIs []string `theorydb:"attr:redirectURIs" json:"redirect_uris"`
GrantTypes []string `theorydb:"attr:grantTypes" json:"grant_types,omitempty"`
ResponseTypes []string `theorydb:"attr:responseTypes" json:"response_types,omitempty"`
Scopes []string `theorydb:"attr:scopes" json:"scopes,omitempty"`
ClientClass string `theorydb:"attr:clientClass,omitempty" json:"client_class,omitempty"`
AgentUsername string `theorydb:"attr:agentUsername,omitempty" json:"agent_username,omitempty"`
OwnerID string `theorydb:"attr:ownerID,omitempty" json:"owner_id,omitempty"`
RegistrationSource string `theorydb:"attr:registrationSource,omitempty" json:"registration_source,omitempty"`
Confidential bool `theorydb:"attr:confidential" json:"confidential"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at,omitempty"`
// contains filtered or unexported fields
}
OAuthClient represents an OAuth 2.0 client application
func (*OAuthClient) BeforeCreate ¶
func (o *OAuthClient) BeforeCreate() error
BeforeCreate sets up the keys before creating
func (*OAuthClient) BeforeUpdate ¶
func (o *OAuthClient) BeforeUpdate() error
BeforeUpdate sets the updated timestamp
func (*OAuthClient) GetPK ¶
func (o *OAuthClient) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*OAuthClient) GetSK ¶
func (o *OAuthClient) GetSK() string
GetSK returns the sort key for BaseModel interface
func (OAuthClient) TableName ¶
func (OAuthClient) TableName() string
TableName returns the DynamoDB table name
func (*OAuthClient) UpdateKeys ¶
func (o *OAuthClient) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates DynamoDB keys
type OAuthDeviceSession ¶ added in v0.1.36
type OAuthDeviceSession struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"-"` // OAUTH_DEVICE#<deviceCodeHash>
SK string `theorydb:"sk,attr:SK" json:"-"` // SESSION
// GSI1 - user_code lookup (web approval flow)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // OAUTH_DEVICE_USER_CODE#<userCode>
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // <createdAt>#<deviceCodeHash>
// Core fields
DeviceCodeHash string `theorydb:"attr:deviceCodeHash" json:"device_code_hash"`
UserCode string `theorydb:"attr:userCode" json:"user_code"`
ClientID string `theorydb:"attr:clientID" json:"client_id"`
Scopes []string `theorydb:"attr:scopes" json:"scopes,omitempty"`
// State machine
Status string `theorydb:"attr:status" json:"status"` // pending|approved|denied|consumed
// Polling governance (abuse control)
IntervalSeconds int `theorydb:"attr:intervalSeconds" json:"interval_seconds"`
PollCount int `theorydb:"attr:pollCount" json:"poll_count,omitempty"`
LastPolledAt *time.Time `theorydb:"attr:lastPolledAt" json:"last_polled_at,omitempty"`
// Approval outcome
ApprovedUsername string `theorydb:"attr:approvedUsername" json:"approved_username,omitempty"`
ApprovedAt *time.Time `theorydb:"attr:approvedAt" json:"approved_at,omitempty"`
DeniedAt *time.Time `theorydb:"attr:deniedAt" json:"denied_at,omitempty"`
ConsumedAt *time.Time `theorydb:"attr:consumedAt" json:"consumed_at,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
// DynamoDB TTL (derived from ExpiresAt)
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
OAuthDeviceSession represents an OAuth device authorization session (RFC 8628-style).
The device_code is treated as a secret and is never stored directly; callers store only a hash. The user_code is short and human-entered, and is indexed for lookup by the web UI approval flow.
func (*OAuthDeviceSession) GetPK ¶ added in v0.1.36
func (o *OAuthDeviceSession) GetPK() string
GetPK returns the DynamoDB partition key for the session.
func (*OAuthDeviceSession) GetSK ¶ added in v0.1.36
func (o *OAuthDeviceSession) GetSK() string
GetSK returns the DynamoDB sort key for the session.
func (OAuthDeviceSession) TableName ¶ added in v0.1.36
func (OAuthDeviceSession) TableName() string
TableName returns the DynamoDB table name for OAuth device sessions.
func (*OAuthDeviceSession) UpdateKeys ¶ added in v0.1.36
func (o *OAuthDeviceSession) UpdateKeys() error
UpdateKeys derives primary/GSI keys and TTL fields from the session content.
type OAuthRefreshAuthority ¶ added in v1.6.23
type OAuthRefreshAuthority struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
Username string `theorydb:"attr:username" json:"username"`
ClientID string `theorydb:"attr:clientID" json:"client_id"`
Resource string `theorydb:"attr:resource,omitempty" json:"resource,omitempty"`
Slots []OAuthRefreshFamilySlot `theorydb:"json,attr:slots" json:"slots"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
Revision int `theorydb:"version,attr:revision" json:"revision"`
// contains filtered or unexported fields
}
OAuthRefreshAuthority is the strongly-consistent singleton authority for a (username, client, resource) tuple. Revision is the CAS boundary.
func (*OAuthRefreshAuthority) BeforeCreate ¶ added in v1.6.23
func (a *OAuthRefreshAuthority) BeforeCreate() error
BeforeCreate prepares keys and creation defaults.
func (OAuthRefreshAuthority) TableName ¶ added in v1.6.23
func (OAuthRefreshAuthority) TableName() string
TableName returns the shared single-table DynamoDB name.
func (*OAuthRefreshAuthority) UpdateKeys ¶ added in v1.6.23
func (a *OAuthRefreshAuthority) UpdateKeys() error
UpdateKeys derives the tuple-scoped authority primary key.
type OAuthRefreshFamilySlot ¶ added in v1.6.23
type OAuthRefreshFamilySlot struct {
FamilyID string `json:"family_id"`
HeadTokenHash string `json:"head_token_hash"`
Generation int `json:"generation"`
ExpiresAt time.Time `json:"expires_at"`
UpdatedAt time.Time `json:"updated_at"`
}
OAuthRefreshFamilySlot is one live refresh family in a tuple-scoped authority row. Slots are ordered least-recently-used to most-recently-used.
type OAuthRefreshSuccessorArtifact ¶ added in v1.6.23
type OAuthRefreshSuccessorArtifact struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
FamilyID string `theorydb:"attr:familyID" json:"family_id"`
PredecessorHash string `theorydb:"attr:predecessorHash" json:"predecessor_hash"`
SuccessorHash string `theorydb:"attr:successorHash" json:"successor_hash"`
SuccessorToken string `theorydb:"encrypted,attr:successorToken" json:"successor_token"`
SuccessorGeneration int `theorydb:"attr:successorGeneration" json:"successor_generation"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
OAuthRefreshSuccessorArtifact is one immutable edge in a refresh lineage. Only the successor credential is encrypted; all lookup and integrity fields are hashes.
func (*OAuthRefreshSuccessorArtifact) BeforeCreate ¶ added in v1.6.23
func (a *OAuthRefreshSuccessorArtifact) BeforeCreate() error
BeforeCreate validates artifact integrity fields and creation defaults.
func (OAuthRefreshSuccessorArtifact) TableName ¶ added in v1.6.23
func (OAuthRefreshSuccessorArtifact) TableName() string
TableName returns the shared single-table DynamoDB name.
func (*OAuthRefreshSuccessorArtifact) UpdateKeys ¶ added in v1.6.23
func (a *OAuthRefreshSuccessorArtifact) UpdateKeys() error
UpdateKeys derives the family and predecessor-scoped artifact key.
type OAuthRefreshWalkBudget ¶ added in v1.6.23
type OAuthRefreshWalkBudget struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
FamilyID string `theorydb:"attr:familyID" json:"family_id"`
Window string `theorydb:"attr:window" json:"window"`
Consumed int `theorydb:"attr:consumed" json:"consumed"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
OAuthRefreshWalkBudget bounds replay-chain work per family and time window.
func (*OAuthRefreshWalkBudget) BeforeCreate ¶ added in v1.6.23
func (b *OAuthRefreshWalkBudget) BeforeCreate() error
BeforeCreate prepares keys and creation defaults.
func (OAuthRefreshWalkBudget) TableName ¶ added in v1.6.23
func (OAuthRefreshWalkBudget) TableName() string
TableName returns the shared single-table DynamoDB name.
func (*OAuthRefreshWalkBudget) UpdateKeys ¶ added in v1.6.23
func (b *OAuthRefreshWalkBudget) UpdateKeys() error
UpdateKeys derives the family and time-window-scoped budget key.
type OAuthState ¶
type OAuthState struct {
// Key fields
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// State data fields
State string `theorydb:"attr:state" json:"state"`
Provider string `theorydb:"attr:provider" json:"provider"`
RedirectURI string `theorydb:"attr:redirectURI" json:"redirect_uri"`
Username string `theorydb:"attr:username" json:"username,omitempty"`
PrincipalUsername string `theorydb:"attr:principalUsername,omitempty" json:"principal_username,omitempty"`
AgentUsername string `theorydb:"attr:agentUsername,omitempty" json:"agent_username,omitempty"`
ClientID string `theorydb:"attr:clientID" json:"client_id,omitempty"`
Scopes []string `theorydb:"attr:scopes" json:"scopes,omitempty"`
CodeChallenge string `theorydb:"attr:codeChallenge" json:"code_challenge,omitempty"`
CodeChallengeMethod string `theorydb:"attr:codeChallengeMethod" json:"code_challenge_method,omitempty"`
Resource string `theorydb:"attr:resource,omitempty" json:"resource,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
// DynamoDB TTL field
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
OAuthState represents OAuth state data in DynamoDB
func (*OAuthState) GetPK ¶
func (o *OAuthState) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*OAuthState) GetSK ¶
func (o *OAuthState) GetSK() string
GetSK returns the sort key for BaseModel interface
func (OAuthState) TableName ¶
func (OAuthState) TableName() string
TableName returns the DynamoDB table backing OAuthState.
func (*OAuthState) UpdateKeys ¶
func (o *OAuthState) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates the composite keys based on the state
type Object ¶
type Object struct {
// Primary key - object by ID
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "object#{id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "object#{id}"
// GSI1 - by actor
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "actor#{actor_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "object#{published}#{id}"
// GSI2 - by type
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "object#type#{type}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{published}#{id}"
// GSI6 - for replies (used when InReplyTo is set)
GSI6PK string `theorydb:"index:gsi6,pk,attr:gsi6PK,omitempty" json:"gsi6_pk,omitempty"` // Format: "REPLIES#{parent_object_id}"
GSI6SK string `theorydb:"index:gsi6,sk,attr:gsi6SK,omitempty" json:"gsi6_sk,omitempty"` // Format: "{timestamp}#{id}"
// Object data - stored as JSON
ID string `theorydb:"attr:id" json:"id"`
Type string `theorydb:"attr:type" json:"type"`
AttributedTo string `theorydb:"attr:attributedTo" json:"attributed_to,omitempty"`
Content string `theorydb:"attr:content" json:"content,omitempty"`
Name string `theorydb:"attr:name" json:"name,omitempty"`
Summary string `theorydb:"attr:summary" json:"summary,omitempty"`
URL string `theorydb:"attr:url" json:"url,omitempty"`
Published time.Time `theorydb:"attr:published" json:"published"`
Updated time.Time `theorydb:"attr:updated" json:"updated"`
InReplyTo *string `theorydb:"attr:inReplyTo" json:"in_reply_to,omitempty"`
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive,omitempty"`
// Addressing
To []string `theorydb:"attr:to" json:"to,omitempty"`
CC []string `theorydb:"attr:cc" json:"cc,omitempty"`
BTo []string `theorydb:"attr:bto" json:"bto,omitempty"`
BCC []string `theorydb:"attr:bcc" json:"bcc,omitempty"`
// Additional fields stored as JSON
AttachmentJSON string `theorydb:"attr:attachmentJSON" json:"attachment_json,omitempty"` // JSON array of attachments
TagJSON string `theorydb:"attr:tagJSON" json:"tag_json,omitempty"` // JSON array of tags
ContextJSON string `theorydb:"attr:contextJSON" json:"context_json,omitempty"` // JSON for @context
// Metadata
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id,omitempty"`
Visibility string `theorydb:"attr:visibility" json:"visibility,omitempty"`
IsRemote bool `theorydb:"attr:isRemote" json:"is_remote"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
Object represents a generic ActivityPub object in DynamoDB This is used for storing various object types (Note, Article, etc.)
func (*Object) UpdateGSIKeys ¶
func (o *Object) UpdateGSIKeys()
UpdateGSIKeys updates the GSI keys based on current data
func (*Object) UpdateKeys ¶
UpdateKeys updates the GSI keys (required by BaseModel)
type OptimizationDecision ¶
type OptimizationDecision struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // OPTIMIZATION
SK string `theorydb:"sk,attr:SK" json:"sk"` // DECISION#{timestampNano}
// Decision data
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
MessageSize int64 `theorydb:"attr:messageSize" json:"message_size"`
RouteIDs []string `theorydb:"attr:routeIDs" json:"route_ids"`
Decision string `theorydb:"attr:decision" json:"decision"` // JSON-encoded decision data
// TTL for cleanup (7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
OptimizationDecision represents a route optimization decision record
func (*OptimizationDecision) GetPK ¶
func (o *OptimizationDecision) GetPK() string
GetPK returns the partition key
func (*OptimizationDecision) GetSK ¶
func (o *OptimizationDecision) GetSK() string
GetSK returns the sort key
func (OptimizationDecision) TableName ¶
func (OptimizationDecision) TableName() string
TableName returns the DynamoDB table backing OptimizationDecision.
func (*OptimizationDecision) UpdateKeys ¶
func (o *OptimizationDecision) UpdateKeys() error
UpdateKeys updates the keys based on the current data
type OutboxItem ¶
type OutboxItem struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI fields for public outbox queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// Business fields
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // The actor who created the activity
ActivityID string `theorydb:"attr:activityID" json:"activity_id"` // The activity ID
Activity *activitypub.Activity `theorydb:"attr:activity" json:"activity"` // The full activity object
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When the activity was created
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
Public bool `theorydb:"attr:public" json:"public"` // Whether this is a public activity
// contains filtered or unexported fields
}
OutboxItem represents an activity created by an actor (in their outbox)
func (OutboxItem) TableName ¶
func (OutboxItem) TableName() string
TableName returns the DynamoDB table backing OutboxItem.
func (*OutboxItem) UpdateKeys ¶
func (o *OutboxItem) UpdateKeys()
UpdateKeys updates the composite keys based on the outbox item data
type PasskeyRegistrationProof ¶ added in v1.6.22
type PasskeyRegistrationProof struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
CeremonyID string `theorydb:"attr:ceremonyID" json:"ceremony_id"`
CredentialID string `theorydb:"attr:credentialID" json:"credential_id"`
PublicKey []byte `theorydb:"attr:publicKey" json:"public_key"`
AttestationType string `theorydb:"attr:attestationType" json:"attestation_type"`
AAGUID []byte `theorydb:"attr:aaguid" json:"aaguid"`
SignCount uint32 `theorydb:"attr:signCount" json:"sign_count"`
CloneWarning bool `theorydb:"attr:cloneWarning" json:"clone_warning"`
BackupEligible bool `theorydb:"attr:backupEligible" json:"backup_eligible"`
BackupState bool `theorydb:"attr:backupState" json:"backup_state"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Consumed bool `theorydb:"attr:consumed" json:"consumed"`
ConsumedAt time.Time `theorydb:"attr:consumedAt" json:"consumed_at,omitempty"`
// contains filtered or unexported fields
}
PasskeyRegistrationProof is the single-use proof persisted between WebAuthn signup verification and account registration.
func (*PasskeyRegistrationProof) BeforeCreate ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) BeforeCreate() error
BeforeCreate sets keys and TTL defaults before creation.
func (*PasskeyRegistrationProof) BeforeUpdate ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) BeforeUpdate() error
BeforeUpdate keeps keys and TTL aligned on update.
func (*PasskeyRegistrationProof) GetPK ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) GetPK() string
GetPK returns the partition key.
func (*PasskeyRegistrationProof) GetSK ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) GetSK() string
GetSK returns the sort key.
func (*PasskeyRegistrationProof) IsExpired ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) IsExpired(now time.Time) bool
IsExpired reports whether the proof is expired at the provided time.
func (PasskeyRegistrationProof) TableName ¶ added in v1.6.22
func (PasskeyRegistrationProof) TableName() string
TableName returns the DynamoDB table name.
func (*PasskeyRegistrationProof) UpdateKeys ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) UpdateKeys() error
UpdateKeys updates the keys and TTL from the current model state.
func (*PasskeyRegistrationProof) Validate ¶ added in v1.6.22
func (p *PasskeyRegistrationProof) Validate() error
Validate ensures the persisted proof is internally consistent.
type PasswordReset ¶
type PasswordReset struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // USER#{username}
SK string `theorydb:"sk,attr:SK" json:"sk"` // RESET#{token}
// GSI1 for token lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // RESET_TOKEN#{token}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // USERNAME#{username}
Username string `theorydb:"attr:username" json:"username"`
Token string `theorydb:"attr:token" json:"token"`
Email string `theorydb:"attr:email" json:"email"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Used bool `theorydb:"attr:used" json:"used"`
UsedAt time.Time `theorydb:"attr:usedAt" json:"used_at,omitempty"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
PasswordReset represents a password reset token
func (*PasswordReset) BeforeCreate ¶
func (r *PasswordReset) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*PasswordReset) GetPK ¶
func (r *PasswordReset) GetPK() string
GetPK returns the partition key
func (PasswordReset) TableName ¶
func (PasswordReset) TableName() string
TableName returns the DynamoDB table name
func (*PasswordReset) UpdateKeys ¶
func (r *PasswordReset) UpdateKeys() error
UpdateKeys updates the keys
type PatternCache ¶
type PatternCache struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "PATTERN_CACHE#{pattern_type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "COMPILED#{pattern_id}"
// GSI1 - Cache invalidation queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // "PATTERN_CACHE#ACTIVE"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // "{last_updated}#{pattern_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "PATTERN_CACHE"
// Cache data
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
PatternType string `theorydb:"attr:patternType" json:"pattern_type"`
CompilationHash string `theorydb:"attr:compilationHash" json:"compilation_hash"`
CompiledData map[string]interface{} `theorydb:"attr:compiledData" json:"compiled_data"` // Serialized compiled pattern data
CompileTime float64 `theorydb:"attr:compileTime" json:"compile_time"` // Time taken to compile in milliseconds
CacheHits int64 `theorydb:"attr:cacheHits" json:"cache_hits"` // Number of times this cache entry was used
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for cache expiration (24 hours default)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
PatternCache represents cached compiled patterns for performance
func (PatternCache) TableName ¶
func (PatternCache) TableName() string
TableName returns the DynamoDB table name
func (*PatternCache) UpdateKeys ¶
func (c *PatternCache) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type PatternFeedback ¶
type PatternFeedback struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // PATTERN#{patternID}
SK string `theorydb:"sk,attr:SK" json:"-"` // FEEDBACK#{timestamp}#{feedbackID}
// Attributes from interface
WasMatch bool `theorydb:"attr:wasMatch" json:"was_match"`
WasFalsePositive bool `theorydb:"attr:wasFalsePositive" json:"was_false_positive"`
// Additional attributes
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
FeedbackID string `theorydb:"attr:feedbackID" json:"feedback_id"`
SubmittedBy string `theorydb:"attr:submittedBy" json:"submitted_by"` // User or system that submitted feedback
SubmittedAt time.Time `theorydb:"attr:submittedAt" json:"submitted_at"`
ContentID string `theorydb:"attr:contentID" json:"content_id"` // ID of content that was evaluated
ContentType string `theorydb:"attr:contentType" json:"content_type"` // Type of content (status, user, etc)
PatternType string `theorydb:"attr:patternType" json:"pattern_type"` // spam, abuse, etc
Confidence float64 `theorydb:"attr:confidence" json:"confidence"` // Original confidence score
Notes string `theorydb:"attr:notes" json:"notes,omitempty"` // Additional feedback notes
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 90 days retention
// contains filtered or unexported fields
}
PatternFeedback represents feedback on pattern matching results
func NewPatternFeedback ¶
func NewPatternFeedback(patternID, contentID, submittedBy string) *PatternFeedback
NewPatternFeedback creates a new pattern feedback entry
func (*PatternFeedback) GetFeedbackType ¶
func (p *PatternFeedback) GetFeedbackType() string
GetFeedbackType returns a string describing the type of feedback
func (*PatternFeedback) IsCorrect ¶
func (p *PatternFeedback) IsCorrect() bool
IsCorrect returns true if the pattern matched correctly
func (PatternFeedback) TableName ¶
func (PatternFeedback) TableName() string
TableName returns the DynamoDB table backing PatternFeedback.
func (*PatternFeedback) UpdateKeys ¶
func (p *PatternFeedback) UpdateKeys()
UpdateKeys updates the partition and sort keys
type PatternPerformanceMetric ¶
type PatternPerformanceMetric struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "PATTERN_METRICS#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TIME#{date}#{hour}"
// GSI1 - Pattern performance queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "METRICS#{pattern_type}#{date}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "{hour}#{pattern_id}"
// GSI2 - Aggregated metrics queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // "PATTERN_PERFORMANCE"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // "{date}#{pattern_type}#{pattern_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "PATTERN_METRIC"
// Metric data
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
PatternType string `theorydb:"attr:patternType" json:"pattern_type"`
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD
Hour int `theorydb:"attr:hour" json:"hour"` // 0-23
// Performance counters
MatchAttempts int64 `theorydb:"attr:matchAttempts" json:"match_attempts"` // Total match attempts
SuccessfulMatches int64 `theorydb:"attr:successfulMatches" json:"successful_matches"` // Actual matches
FalsePositives int64 `theorydb:"attr:falsePositives" json:"false_positives"` // Confirmed false positives
TruePositives int64 `theorydb:"attr:truePositives" json:"true_positives"` // Confirmed true positives
AverageMatchTime float64 `theorydb:"attr:averageMatchTime" json:"average_match_time"` // Average time per match in milliseconds
MaxMatchTime float64 `theorydb:"attr:maxMatchTime" json:"max_match_time"` // Maximum time for a single match
MinMatchTime float64 `theorydb:"attr:minMatchTime" json:"min_match_time"` // Minimum time for a single match
TotalMatchTime float64 `theorydb:"attr:totalMatchTime" json:"total_match_time"` // Total time spent matching
MemoryUsage int64 `theorydb:"attr:memoryUsage" json:"memory_usage"` // Memory usage in bytes
CPUTime float64 `theorydb:"attr:cpuTime" json:"cpu_time"` // CPU time used in milliseconds
// Quality metrics
Precision float64 `theorydb:"attr:precision" json:"precision"` // true_positives / ...
Recall float64 `theorydb:"attr:recall" json:"recall"` // true_positives / (true_positives + false_negatives)
F1Score float64 `theorydb:"attr:f1Score" json:"f1_score"` // 2 * (precision * recall) / (precision + recall)
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL (30 days for detailed metrics)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
PatternPerformanceMetric tracks detailed performance metrics for patterns
func (*PatternPerformanceMetric) CalculateQualityMetrics ¶
func (m *PatternPerformanceMetric) CalculateQualityMetrics()
CalculateQualityMetrics calculates precision, recall, and F1 score
func (*PatternPerformanceMetric) GetPK ¶
func (m *PatternPerformanceMetric) GetPK() string
GetPK returns the partition key
func (*PatternPerformanceMetric) GetSK ¶
func (m *PatternPerformanceMetric) GetSK() string
GetSK returns the sort key
func (PatternPerformanceMetric) TableName ¶
func (PatternPerformanceMetric) TableName() string
TableName returns the DynamoDB table name
func (*PatternPerformanceMetric) UpdateKeys ¶
func (m *PatternPerformanceMetric) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type PatternStats ¶
PatternStats represents pattern matching statistics
func (PatternStats) TableName ¶
func (PatternStats) TableName() string
TableName returns the DynamoDB table backing PatternStats.
type PatternTestResult ¶
type PatternTestResult struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "PATTERN_TEST#{pattern_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "TEST#{test_id}"
// GSI1 - Test result queries by type
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk,omitempty"` // Format: "PATTERN_TESTS#{test_type}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk,omitempty"` // Format: "{score}#{timestamp}#{test_id}"
// Type marker
Type string `theorydb:"attr:type" json:"type"` // "PATTERN_TEST"
// Test identification
TestID string `theorydb:"attr:testID" json:"test_id"`
PatternID string `theorydb:"attr:patternID" json:"pattern_id"`
PatternType string `theorydb:"attr:patternType" json:"pattern_type"`
TestType string `theorydb:"attr:testType" json:"test_type"` // "validation", ...
// Test configuration
TestDescription string `theorydb:"attr:testDescription" json:"test_description"`
TestParameters map[string]interface{} `theorydb:"attr:testParameters" json:"test_parameters"`
TestData []string `theorydb:"attr:testData" json:"test_data,omitempty"` // Test inputs
// Test results
Passed bool `theorydb:"attr:passed" json:"passed"`
Score float64 `theorydb:"attr:score" json:"score"` // 0.0-1.0
ExecutionTime float64 `theorydb:"attr:executionTime" json:"execution_time"` // Time in milliseconds
MemoryUsage int64 `theorydb:"attr:memoryUsage" json:"memory_usage"` // Memory usage in bytes
Results map[string]interface{} `theorydb:"attr:results" json:"results"` // Detailed test results
ExpectedResults []string `theorydb:"attr:expectedResults" json:"expected_results,omitempty"`
ActualResults []string `theorydb:"attr:actualResults" json:"actual_results,omitempty"`
Errors []string `theorydb:"attr:errors" json:"errors,omitempty"`
// Test metadata
TestVersion string `theorydb:"attr:testVersion" json:"test_version"`
RunBy string `theorydb:"attr:runBy" json:"run_by"`
RunAt time.Time `theorydb:"attr:runAt" json:"run_at"`
Environment string `theorydb:"attr:environment" json:"environment"` // "development", "staging", "production"
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL (90 days for test results)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
PatternTestResult stores results from pattern testing and validation
func (*PatternTestResult) GetPK ¶
func (t *PatternTestResult) GetPK() string
GetPK returns the partition key
func (*PatternTestResult) GetSK ¶
func (t *PatternTestResult) GetSK() string
GetSK returns the sort key
func (*PatternTestResult) GetSecurityScore ¶
func (t *PatternTestResult) GetSecurityScore() float64
GetSecurityScore returns the security score if this is a security test
func (*PatternTestResult) IsSecurityTest ¶
func (t *PatternTestResult) IsSecurityTest() bool
IsSecurityTest checks if this is a security-related test
func (PatternTestResult) TableName ¶
func (PatternTestResult) TableName() string
TableName returns the DynamoDB table name
func (*PatternTestResult) UpdateKeys ¶
func (t *PatternTestResult) UpdateKeys() error
UpdateKeys updates the GSI keys based on current field values
type Poll ¶
type Poll struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"-"` // POLL#{pollId}
SK string `theorydb:"sk,attr:SK" json:"-"` // METADATA
// GSI keys for querying by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{statusId}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // POLL
// Business fields
ID string `theorydb:"attr:id" json:"id"`
StatusID string `theorydb:"attr:statusId" json:"statusId"`
CreatedBy string `theorydb:"attr:createdBy" json:"createdBy"`
Options []string `theorydb:"attr:options" json:"options"`
Multiple bool `theorydb:"attr:multiple" json:"multiple"`
HideTotals bool `theorydb:"attr:hideTotals" json:"hideTotals"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expiresAt"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"createdAt"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updatedAt"`
VotesCount int `theorydb:"attr:votesCount" json:"votesCount"`
VotersCount int `theorydb:"attr:votersCount" json:"votersCount"`
Votes map[string][]int `theorydb:"attr:votes" json:"votes"` // Map of voter ID to option indices
// TTL for expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Poll represents a poll entity in DynamoDB
func (*Poll) UpdateKeys ¶
UpdateKeys updates the DynamoDB keys based on the business fields
type PollVote ¶
type PollVote struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"-"` // POLL#{pollId}
SK string `theorydb:"sk,attr:SK" json:"-"` // VOTE#{voterId}
// Business fields
VoterID string `theorydb:"attr:voterId" json:"voterId"`
Choices []int `theorydb:"attr:choices" json:"choices"`
VotedAt time.Time `theorydb:"attr:votedAt" json:"votedAt"`
// contains filtered or unexported fields
}
PollVote represents an individual vote on a poll
func (*PollVote) SetPollID ¶
SetPollID sets the poll ID and updates keys (used during vote creation)
func (*PollVote) UpdateKeys ¶
UpdateKeys updates the DynamoDB keys based on the business fields
type PopularQueryCounter ¶
type PopularQueryCounter struct {
// Key fields for atomic counter operations
PK string `theorydb:"pk,attr:PK"` // POPULAR_QUERY#query_hash
SK string `theorydb:"sk,attr:SK"` // COUNTER#time_bucket (daily, weekly, monthly)
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"` // For time-based queries
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"` // For ranking by count
// Business fields
QueryHash string `theorydb:"attr:queryHash" json:"query_hash"` // Hashed query for privacy
Query string `theorydb:"attr:query" json:"query"` // Original query (if not sensitive)
TimeBucket string `theorydb:"attr:timeBucket" json:"time_bucket"` // daily, weekly, monthly
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD format
Count int64 `theorydb:"attr:count" json:"count"` // Atomic counter value
UserCount int64 `theorydb:"attr:userCount" json:"user_count"` // Unique users who searched
AvgResults float64 `theorydb:"attr:avgResults" json:"avg_results"` // Average result count
LastQueried time.Time `theorydb:"attr:lastQueried" json:"last_queried"` // Most recent query time
FirstQueried time.Time `theorydb:"attr:firstQueried" json:"first_queried"` // First time this query was seen
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
PopularQueryCounter represents an atomic counter for popular search queries
func (*PopularQueryCounter) GetPK ¶
func (p *PopularQueryCounter) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*PopularQueryCounter) GetSK ¶
func (p *PopularQueryCounter) GetSK() string
GetSK returns the sort key for BaseModel interface
func (PopularQueryCounter) TableName ¶
func (PopularQueryCounter) TableName() string
TableName returns the DynamoDB table backing PopularQueryCounter.
func (*PopularQueryCounter) UpdateKeys ¶
func (p *PopularQueryCounter) UpdateKeys() error
UpdateKeys updates the GSI keys for popular query counter
type PromoPackage ¶ added in v1.6.23
type PromoPackage struct {
// Primary keys: USER#{ownerID}#PROMO#PACKAGE / PACKAGE#{packageID}
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
PackageID string `theorydb:"attr:packageID"`
OwnerID string `theorydb:"attr:ownerID"`
// ArticleID is the published article's object ID that the post promotes.
ArticleID string `theorydb:"attr:articleID"`
// PostText is the outbound post content; the package can append nothing at
// release beyond what review bound.
PostText string `theorydb:"attr:postText"`
// Visibility is public or unlisted only (issue #1446 scope).
Visibility string `theorydb:"attr:visibility"`
// Assets is the ordered asset set attached to the post. Order is
// semantically meaningful (attachment order), so the content hash covers the
// binding order and reordering re-requires review.
Assets []PromoPackageAsset `theorydb:"attr:assets,omitempty"`
// ContentHash is the canonical package digest over post text, visibility,
// article reference, and ordered asset digests. Review verdicts bind to it;
// any content change re-hashes and stales prior approvals.
ContentHash string `theorydb:"attr:contentHash,omitempty"`
// Status is draft or released.
Status string `theorydb:"attr:status"`
// ReleasedStatusID is the outbound Status created by the release
// transition; stamped exactly once, and its presence blocks re-release.
ReleasedStatusID string `theorydb:"attr:releasedStatusID,omitempty"`
ReleasedAt *time.Time `theorydb:"attr:releasedAt,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt"`
UpdatedAt time.Time `theorydb:"attr:updatedAt"`
// ModelVersion provides optimistic concurrency for the field-scoped content
// and release writes (CAS), mirroring the M2 UpdateMediaPublishedState
// precedent.
ModelVersion int `theorydb:"version,attr:modelVersion"`
}
PromoPackage is a reviewed promotional package: outbound post text and an exact, ordered set of PUBLISHED media assets attached to a public/unlisted post, promoting a published article. Pre-release the record is visible only to its owner and holders of an active PromoReviewGrant.
func (*PromoPackage) GetPK ¶ added in v1.6.23
func (p *PromoPackage) GetPK() string
GetPK returns the partition key.
func (*PromoPackage) GetSK ¶ added in v1.6.23
func (p *PromoPackage) GetSK() string
GetSK returns the sort key.
func (*PromoPackage) IsReleased ¶ added in v1.6.23
func (p *PromoPackage) IsReleased() bool
IsReleased reports whether the release transition already stamped an outbound Status for this package.
func (*PromoPackage) IsReleasing ¶ added in v1.6.23
func (p *PromoPackage) IsReleasing() bool
IsReleasing reports whether the package is mid-release: the version- conditioned release reservation was won but the outbound Status has not been stamped yet (or the process crashed between reservation and stamp). Release and composition are refused while this transient state is held.
func (PromoPackage) TableName ¶ added in v1.6.23
func (PromoPackage) TableName() string
TableName returns the DynamoDB table backing PromoPackage.
func (*PromoPackage) UpdateKeys ¶ added in v1.6.23
func (p *PromoPackage) UpdateKeys() error
UpdateKeys derives the primary keys for a promo package.
type PromoPackageAsset ¶ added in v1.6.23
type PromoPackageAsset struct {
MediaID string `json:"media_id"`
ContentHash string `json:"content_hash"`
// PublishedURL snapshots the M2 durable serving at compose time. It is a
// presentation copy for the review surface; release re-reads the media
// record and requires digest equality before attaching the record's current
// PublishedURL, so a stale snapshot can never substitute for the reviewed
// bytes.
PublishedURL string `json:"published_url,omitempty"`
}
PromoPackageAsset is one asset bound into a promo package. The binding carries the media identity plus the canonical sha256:<hex> digest as bound at review time and the durable published serving minted by the M2 publish transition. The digest snapshot is what review verdicts hash over; release re-verifies the live media record still carries the same digest and is still in the PUBLISHED durable state, so the exact reviewed bytes are what attach to the outbound post.
func NormalizePromoPackageAssets ¶ added in v1.6.23
func NormalizePromoPackageAssets(assets []PromoPackageAsset) ([]PromoPackageAsset, error)
NormalizePromoPackageAssets validates and canonicalizes the ordered asset set. Each asset must name a media ID and carry the canonical sha256:<hex> digest of the bytes bound at review time; the same media cannot be bound twice; the set is capped at the outbound Status attachment limit. PublishedURL, when present, must be an http(s) URL.
type PromoReviewGrant ¶ added in v1.6.23
type PromoReviewGrant struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
OwnerID string `theorydb:"attr:ownerID"`
PackageID string `theorydb:"attr:packageID"`
Reviewer string `theorydb:"attr:reviewer"`
GrantedAt time.Time `theorydb:"attr:grantedAt"`
// ExpiresAt bounds the grant. Grants recorded without an expiry are treated
// as expired so pre-M4 rows cannot authorize reads or approval indefinitely.
ExpiresAt *time.Time `theorydb:"attr:expiresAt,omitempty"`
RevokedAt *time.Time `theorydb:"attr:revokedAt,omitempty"`
Version int `theorydb:"version,attr:version"`
}
PromoReviewGrant authorizes one local account to review an owner's promo package before release. Semantics mirror the M2 draft-review grant exactly: owner-scoped, expiry-bounded (7 days, refreshed on re-share), and fail-closed — a revoked or expired grant authorizes neither package reads nor approval.
func (*PromoReviewGrant) Expired ¶ added in v1.6.23
func (g *PromoReviewGrant) Expired(now time.Time) bool
Expired reports whether a bounded grant has passed its expiry. Revocation is reported separately by the active checks; this predicate only classifies un-revoked grants that can no longer authorize anything.
func (*PromoReviewGrant) IsActive ¶ added in v1.6.23
func (g *PromoReviewGrant) IsActive(now time.Time) bool
IsActive reports whether the grant is currently usable: not revoked and not past its bounded expiry. A grant without an expiry is deliberately treated as expired (fail-closed).
func (PromoReviewGrant) TableName ¶ added in v1.6.23
func (PromoReviewGrant) TableName() string
TableName returns the table for a promo review grant.
func (*PromoReviewGrant) UpdateKeys ¶ added in v1.6.23
func (g *PromoReviewGrant) UpdateKeys() error
UpdateKeys derives grant primary and sparse reviewer-queue keys.
type PromoReviewVerdict ¶ added in v1.6.23
type PromoReviewVerdict struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
OwnerID string `theorydb:"attr:ownerID"`
PackageID string `theorydb:"attr:packageID"`
Reviewer string `theorydb:"attr:reviewer"`
Verdict string `theorydb:"attr:verdict"`
Notes string `theorydb:"attr:notes,omitempty"`
ContentHash string `theorydb:"attr:contentHash,omitempty"`
RecordedAt time.Time `theorydb:"attr:recordedAt"`
Version int `theorydb:"version,attr:version"`
}
PromoReviewVerdict is an immutable review decision audit record bound to the exact package content hash. Any package content change re-hashes and the verdict-vs-hash comparison stales the approval, matching M2.
func (PromoReviewVerdict) TableName ¶ added in v1.6.23
func (PromoReviewVerdict) TableName() string
TableName returns the table for a promo review verdict.
func (*PromoReviewVerdict) UpdateKeys ¶ added in v1.6.23
func (v *PromoReviewVerdict) UpdateKeys() error
UpdateKeys derives verdict primary keys.
type ProviderAccount ¶
type ProviderAccount struct {
// Primary key - using composite key for user + provider relationship
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "user#{userID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "provider#{provider}#{providerID}"
// GSI1 - Provider lookup (find user by provider account)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "PROVIDER#{provider}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{providerID}#{userID}"
// GSI2 - User's provider accounts
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "USER_PROVIDERS#{userID}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{provider}#{created_at}"
// Core provider data
UserID string `theorydb:"attr:userID" json:"user_id"`
Provider string `theorydb:"attr:provider" json:"provider"` // "google", "github", "twitter", etc.
ProviderID string `theorydb:"attr:providerID" json:"provider_id"` // Provider's unique ID for the user
ProviderName string `theorydb:"attr:providerName" json:"provider_name,omitempty"` // Display name from provider
// OAuth tokens (stored encrypted)
AccessToken string `theorydb:"attr:accessToken" json:"access_token,omitempty"`
RefreshToken string `theorydb:"attr:refreshToken" json:"refresh_token,omitempty"`
TokenExpiry time.Time `theorydb:"attr:tokenExpiry" json:"token_expiry,omitempty"`
// Profile data from provider
Email string `theorydb:"attr:email" json:"email,omitempty"`
Username string `theorydb:"attr:username" json:"username,omitempty"`
DisplayName string `theorydb:"attr:displayName" json:"display_name,omitempty"`
AvatarURL string `theorydb:"attr:avatarURL" json:"avatar_url,omitempty"`
// Status
IsActive bool `theorydb:"attr:isActive" json:"is_active"`
IsPrimary bool `theorydb:"attr:isPrimary" json:"is_primary"` // Is this the primary auth method?
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastUsedAt *time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at,omitempty"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
ProviderAccount represents an OAuth provider account linked to a user
func (*ProviderAccount) BeforeCreate ¶
func (pa *ProviderAccount) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*ProviderAccount) BeforeUpdate ¶
func (pa *ProviderAccount) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*ProviderAccount) ClearPrimary ¶
func (pa *ProviderAccount) ClearPrimary()
ClearPrimary removes the primary status from this provider account
func (*ProviderAccount) GetDisplayName ¶
func (pa *ProviderAccount) GetDisplayName() string
GetDisplayName returns the best available display name
func (*ProviderAccount) HasValidToken ¶
func (pa *ProviderAccount) HasValidToken() bool
HasValidToken returns true if the account has a valid, non-expired access token
func (*ProviderAccount) IsTokenExpired ¶
func (pa *ProviderAccount) IsTokenExpired() bool
IsTokenExpired returns true if the access token has expired
func (*ProviderAccount) MarkUsed ¶
func (pa *ProviderAccount) MarkUsed()
MarkUsed updates the last used timestamp
func (*ProviderAccount) NeedsRefresh ¶
func (pa *ProviderAccount) NeedsRefresh() bool
NeedsRefresh returns true if the token expires soon and should be refreshed
func (*ProviderAccount) SetPrimary ¶
func (pa *ProviderAccount) SetPrimary()
SetPrimary marks this provider account as the primary authentication method
func (ProviderAccount) TableName ¶
func (ProviderAccount) TableName() string
TableName returns the DynamoDB table name for the ProviderAccount model
func (*ProviderAccount) Validate ¶
func (pa *ProviderAccount) Validate() error
Validate performs validation on the ProviderAccount
type PublicKeyCache ¶
type PublicKeyCache struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
ActorURL string `theorydb:"attr:actorURL" json:"actor_url"` // URL of the actor
KeyID string `theorydb:"attr:keyID" json:"key_id"` // Public key ID
PublicKeyPEM string `theorydb:"attr:publicKeyPEM" json:"public_key_pem"` // PEM-encoded public key
Algorithm string `theorydb:"attr:algorithm" json:"algorithm"` // Signature algorithm (rsa-sha256, etc.)
FetchedAt time.Time `theorydb:"attr:fetchedAt" json:"fetched_at"` // When the key was fetched
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"` // Last time this key was used
SuccessCount int `theorydb:"attr:successCount" json:"success_count"` // Number of successful verifications
FailureCount int `theorydb:"attr:failureCount" json:"failure_count"` // Number of failed verifications
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // Unix timestamp for DynamoDB TTL
// contains filtered or unexported fields
}
PublicKeyCache represents a cached public key for ActivityPub signature verification
func NewPublicKeyCache ¶
func NewPublicKeyCache(actorURL, keyID, publicKeyPEM, algorithm string) *PublicKeyCache
NewPublicKeyCache creates a new public key cache entry
func (*PublicKeyCache) ExtendTTL ¶
func (p *PublicKeyCache) ExtendTTL(duration time.Duration)
ExtendTTL extends the cache entry TTL by the specified duration
func (*PublicKeyCache) GetPK ¶
func (p *PublicKeyCache) GetPK() string
GetPK returns the partition key
func (*PublicKeyCache) GetPublicKeyPEM ¶
func (p *PublicKeyCache) GetPublicKeyPEM() []byte
GetPublicKeyPEM returns the cached PEM public key for parsing elsewhere
func (*PublicKeyCache) IsValid ¶
func (p *PublicKeyCache) IsValid() bool
IsValid checks if the cache entry is still valid
func (*PublicKeyCache) RecordFailure ¶
func (p *PublicKeyCache) RecordFailure()
RecordFailure increments the failure count
func (*PublicKeyCache) RecordSuccess ¶
func (p *PublicKeyCache) RecordSuccess()
RecordSuccess increments the success count and updates last used time
func (*PublicKeyCache) ShouldRefresh ¶
func (p *PublicKeyCache) ShouldRefresh() bool
ShouldRefresh checks if the key should be refreshed based on failure rate
func (PublicKeyCache) TableName ¶
func (PublicKeyCache) TableName() string
TableName returns the DynamoDB table backing PublicKeyCache.
func (*PublicKeyCache) UpdateKeys ¶
func (p *PublicKeyCache) UpdateKeys() error
UpdateKeys updates the partition and sort keys based on the model's attributes
type Publication ¶
type Publication struct {
PK string `theorydb:"pk,attr:PK"` // PUBLICATION#{id}
SK string `theorydb:"sk,attr:SK"` // METADATA
ID string `theorydb:"attr:id" json:"id"`
Name string `theorydb:"attr:name" json:"name"`
Tagline string `theorydb:"attr:tagline" json:"tagline,omitempty"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Slug string `theorydb:"attr:slug" json:"slug"`
// Branding
LogoURL string `theorydb:"attr:logoURL" json:"logo_url,omitempty"`
BannerURL string `theorydb:"attr:bannerURL" json:"banner_url,omitempty"`
Theme string `theorydb:"attr:theme" json:"theme,omitempty"` // JSON theme config
// Configuration
CustomDomain string `theorydb:"attr:customDomain" json:"custom_domain,omitempty"`
// ActivityPub
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // The AP Actor for this publication
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
Publication represents a blog/newsletter publication with multiple contributors
func (Publication) TableName ¶
func (Publication) TableName() string
TableName returns the DynamoDB table backing Publication.
func (*Publication) UpdateKeys ¶
func (p *Publication) UpdateKeys() error
UpdateKeys updates the keys for the Publication model
type PublicationMember ¶
type PublicationMember struct {
PK string `theorydb:"pk,attr:PK"` // PUBLICATION#{pub_id}#MEMBER
SK string `theorydb:"sk,attr:SK"` // USER#{user_id}
// GSI1: USER#{user_id}#PUBLICATION / PUBLICATION#{pub_id}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
PublicationID string `theorydb:"attr:publicationID" json:"publication_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Role string `theorydb:"attr:role" json:"role"` // owner, editor, writer, contributor
// Display
DisplayName string `theorydb:"attr:displayName" json:"display_name,omitempty"` // Override user's name
Bio string `theorydb:"attr:bio" json:"bio,omitempty"` // Publication-specific bio
// Timestamps
JoinedAt time.Time `theorydb:"attr:joinedAt" json:"joined_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
PublicationMember represents a contributor to a publication
func (*PublicationMember) GetPK ¶
func (pm *PublicationMember) GetPK() string
GetPK returns the partition key
func (*PublicationMember) GetSK ¶
func (pm *PublicationMember) GetSK() string
GetSK returns the sort key
func (PublicationMember) TableName ¶
func (PublicationMember) TableName() string
TableName returns the DynamoDB table backing PublicationMember.
func (*PublicationMember) UpdateKeys ¶
func (pm *PublicationMember) UpdateKeys() error
UpdateKeys updates the keys for the PublicationMember model
type PushSubscription ¶
type PushSubscription struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // PUSH#username
SK string `theorydb:"sk,attr:SK" json:"sk"` // SUB#subscriptionID
// GSI for endpoint lookup (to prevent duplicates)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // PUSH_ENDPOINT#endpoint_hash
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // username
// Core subscription data
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
Endpoint string `theorydb:"attr:endpoint" json:"endpoint"`
P256dh string `theorydb:"attr:p256dh" json:"p256dh"` // Public key for encryption
Auth string `theorydb:"attr:auth" json:"auth"` // Auth secret
Alerts PushSubscriptionAlerts `theorydb:"attr:alerts" json:"alerts"` // Which notifications to send
Policy string `theorydb:"attr:policy" json:"policy,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used,omitempty"`
// contains filtered or unexported fields
}
PushSubscription represents a push subscription stored in DynamoDB
func (*PushSubscription) BeforeCreate ¶
func (p *PushSubscription) BeforeCreate() error
BeforeCreate is called before creating a new push subscription
func (*PushSubscription) BeforeUpdate ¶
func (p *PushSubscription) BeforeUpdate() error
BeforeUpdate is called before updating a push subscription
func (*PushSubscription) GetPK ¶
func (p *PushSubscription) GetPK() string
GetPK returns the partition key
func (*PushSubscription) GetSK ¶
func (p *PushSubscription) GetSK() string
GetSK returns the sort key
func (PushSubscription) TableName ¶
func (PushSubscription) TableName() string
TableName returns the DynamoDB table name
func (*PushSubscription) UpdateKeys ¶
func (p *PushSubscription) UpdateKeys() error
UpdateKeys updates the GSI keys for the push subscription
func (*PushSubscription) UpdateLastUsed ¶
func (p *PushSubscription) UpdateLastUsed()
UpdateLastUsed updates the last used timestamp
func (*PushSubscription) Validate ¶
func (p *PushSubscription) Validate() error
Validate performs validation on the PushSubscription
type PushSubscriptionAlerts ¶
type PushSubscriptionAlerts struct {
Follow bool `json:"follow"`
Favourite bool `json:"favourite"`
Reblog bool `json:"reblog"`
Mention bool `json:"mention"`
Poll bool `json:"poll"`
FollowRequest bool `json:"follow_request"`
Status bool `json:"status"`
Update bool `json:"update"`
AdminSignUp bool `json:"admin_sign_up"`
AdminReport bool `json:"admin_report"`
}
PushSubscriptionAlerts represents which events trigger push notifications
func (PushSubscriptionAlerts) TableName ¶
func (PushSubscriptionAlerts) TableName() string
TableName returns the DynamoDB table backing PushSubscriptionAlerts.
type QualityChange ¶
type QualityChange struct {
// DynamoDB Keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // QUALITY#{sessionID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // timestamp (nanoseconds)
// Business fields
SessionID string `theorydb:"attr:sessionID" json:"session_id"`
Quality string `theorydb:"attr:quality" json:"quality"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// TTL for analytics cleanup (7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
QualityChange represents a quality change event for analytics
func (*QualityChange) GetPK ¶
func (q *QualityChange) GetPK() string
GetPK returns the partition key
func (QualityChange) TableName ¶
func (QualityChange) TableName() string
TableName returns the DynamoDB table backing QualityChange.
func (*QualityChange) UpdateKeys ¶
func (q *QualityChange) UpdateKeys() error
UpdateKeys sets the keys for quality change tracking
type QualityCodecInfo ¶
type QualityCodecInfo struct {
VideoCodec string `json:"video_codec"` // H.264 profile/level string like "avc1.640028"
AudioCodec string `json:"audio_codec"` // Audio codec string like "mp4a.40.2"
Bandwidth int `json:"bandwidth"` // Required bandwidth in bps
Width int `json:"width"` // Video width in pixels
Height int `json:"height"` // Video height in pixels
}
QualityCodecInfo contains codec information for a specific quality level
func (QualityCodecInfo) TableName ¶
func (QualityCodecInfo) TableName() string
TableName returns the DynamoDB table backing QualityCodecInfo.
type QualityMetric ¶
type QualityMetric struct {
Quality string `json:"quality"` // 480p, 720p, 1080p, 4k
ViewerCount int64 `json:"viewer_count"` // Current viewers at this quality
ViewerPercentage float64 `json:"viewer_percentage"` // Percentage of total viewers
BufferingRate float64 `json:"buffering_rate"` // Buffering events per viewer per hour
AverageLatencyMs int64 `json:"average_latency_ms"` // Average response time for this quality
ErrorRate float64 `json:"error_rate"` // Error rate for this quality
BitrateUtilization float64 `json:"bitrate_utilization"` // Actual vs target bitrate
StartupTimeMs int64 `json:"startup_time_ms"` // Time to first frame
}
QualityMetric represents metrics for a specific streaming quality
func (QualityMetric) TableName ¶
func (QualityMetric) TableName() string
TableName returns the DynamoDB table backing QualityMetric.
type QueryCacheEntry ¶
type QueryCacheEntry struct {
// Primary keys
// - PK=CACHE#{namespace}
// - SK=KEY#{cacheKey}
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Cache data
CacheKey string `theorydb:"attr:cacheKey" json:"cache_key"`
Value string `theorydb:"attr:value" json:"value"` // JSON-encoded cached value
Size int `theorydb:"attr:size" json:"size"` // Size for LRU calculations
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"` // Manual expiry tracking
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
QueryCacheEntry represents a cached query result in DynamoDB
func (*QueryCacheEntry) GetPK ¶
func (q *QueryCacheEntry) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*QueryCacheEntry) GetSK ¶
func (q *QueryCacheEntry) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*QueryCacheEntry) IsExpired ¶
func (q *QueryCacheEntry) IsExpired() bool
IsExpired checks if the cache entry has expired
func (QueryCacheEntry) TableName ¶
func (QueryCacheEntry) TableName() string
TableName returns the DynamoDB table backing QueryCacheEntry.
func (*QueryCacheEntry) UpdateKeys ¶
func (q *QueryCacheEntry) UpdateKeys() error
UpdateKeys ensures keys are properly set before saving
type QuotePermissions ¶
type QuotePermissions struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Business fields
Username string `theorydb:"attr:username" json:"username"`
AllowPublic bool `theorydb:"attr:allowPublic" json:"allow_public"`
AllowFollowers bool `theorydb:"attr:allowFollowers" json:"allow_followers"`
AllowMentioned bool `theorydb:"attr:allowMentioned" json:"allow_mentioned"`
BlockList []string `theorydb:"attr:blockList" json:"block_list"` // List of usernames blocked from quoting
// contains filtered or unexported fields
}
QuotePermissions represents quote permissions for a user's statuses
func (*QuotePermissions) AddToBlockList ¶
func (q *QuotePermissions) AddToBlockList(username string)
AddToBlockList adds a username to the block list
func (*QuotePermissions) ApplyVisibilityDefaults ¶
func (q *QuotePermissions) ApplyVisibilityDefaults(visibility string)
ApplyVisibilityDefaults aligns permissions with the user's default posting visibility.
func (*QuotePermissions) GetPK ¶
func (q *QuotePermissions) GetPK() string
GetPK returns the partition key
func (*QuotePermissions) GetSK ¶
func (q *QuotePermissions) GetSK() string
GetSK returns the sort key
func (*QuotePermissions) IsAllowed ¶
func (q *QuotePermissions) IsAllowed(quoterUsername string, isFollower bool, isMentioned bool) bool
IsAllowed checks if a given user is allowed to quote based on permissions. Account-level permissions are persisted by the GraphQL updateAccountQuotePermissions mutation. The GraphQL quote path enforces the equivalent predicate in QuoteService.CheckQuotePermissions; REST quote creation must do the same.
func (*QuotePermissions) RemoveFromBlockList ¶
func (q *QuotePermissions) RemoveFromBlockList(username string)
RemoveFromBlockList removes a username from the block list
func (*QuotePermissions) SetDefaults ¶
func (q *QuotePermissions) SetDefaults()
SetDefaults sets default quote permissions for a new user
func (QuotePermissions) TableName ¶
func (QuotePermissions) TableName() string
TableName returns the DynamoDB table backing QuotePermissions.
func (*QuotePermissions) UpdateKeys ¶
func (q *QuotePermissions) UpdateKeys() error
UpdateKeys updates the composite keys based on the quote permissions
type QuoteRelationship ¶
type QuoteRelationship struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying by quoted status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// GSI fields for querying by author
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk,omitempty"`
// Business fields
ID string `theorydb:"attr:id" json:"id"`
QuoterNoteID string `theorydb:"attr:quoterNoteID" json:"quoter_note_id"`
TargetNoteID string `theorydb:"attr:targetNoteID" json:"target_note_id"`
QuoterID string `theorydb:"attr:quoterID" json:"quoter_id"`
TargetAuthorID string `theorydb:"attr:targetAuthorID" json:"target_author_id,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Withdrawn bool `theorydb:"attr:withdrawn" json:"withdrawn"`
WithdrawnAt *time.Time `theorydb:"attr:withdrawnAt" json:"withdrawn_at,omitempty"`
// contains filtered or unexported fields
}
QuoteRelationship represents a quote relationship between notes
func (*QuoteRelationship) GenerateID ¶
func (q *QuoteRelationship) GenerateID()
GenerateID generates a unique ID for the quote relationship
func (*QuoteRelationship) GetPK ¶
func (q *QuoteRelationship) GetPK() string
GetPK returns the partition key
func (*QuoteRelationship) GetSK ¶
func (q *QuoteRelationship) GetSK() string
GetSK returns the sort key
func (*QuoteRelationship) IsActive ¶
func (q *QuoteRelationship) IsActive() bool
IsActive returns whether the quote relationship is active (not withdrawn)
func (QuoteRelationship) TableName ¶
func (QuoteRelationship) TableName() string
TableName returns the DynamoDB table backing QuoteRelationship.
func (*QuoteRelationship) UpdateKeys ¶
func (q *QuoteRelationship) UpdateKeys() error
UpdateKeys updates the composite keys based on the quote relationship
func (*QuoteRelationship) Withdraw ¶
func (q *QuoteRelationship) Withdraw()
Withdraw marks the quote relationship as withdrawn
type RateLimitLockout ¶
type RateLimitLockout struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // RATELIMIT#{identifier}
SK string `theorydb:"sk,attr:SK" json:"sk"` // "LOCKOUT"
// Attributes
Type string `theorydb:"attr:type" json:"type"` // "RateLimitLockout"
UnlockTime time.Time `theorydb:"attr:unlockTime" json:"unlock_time"` // when the lockout expires
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // automatic cleanup
// contains filtered or unexported fields
}
RateLimitLockout represents an active rate limit lockout
func NewRateLimitLockout ¶
func NewRateLimitLockout(identifier string, unlockTime time.Time) *RateLimitLockout
NewRateLimitLockout creates a new RateLimitLockout record
func (*RateLimitLockout) GetPK ¶
func (rll *RateLimitLockout) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*RateLimitLockout) GetSK ¶
func (rll *RateLimitLockout) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (RateLimitLockout) TableName ¶
func (RateLimitLockout) TableName() string
TableName returns the DynamoDB table name for rate limit lockouts
func (*RateLimitLockout) UpdateKeys ¶
func (rll *RateLimitLockout) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the RateLimitLockout model
type RateLimitViolation ¶
type RateLimitViolation struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // RATELIMIT_VIOLATION#{userID|domain}
SK string `theorydb:"sk,attr:SK" json:"sk"` // timestamp of violation
// Attributes
Type string `theorydb:"attr:type" json:"type"` // "RateLimitViolation"
UserID string `theorydb:"attr:userID" json:"user_id"` // User identifier
Domain string `theorydb:"attr:domain" json:"domain,omitempty"` // Domain for federation violations
Endpoint string `theorydb:"attr:endpoint" json:"endpoint"` // Endpoint that was rate limited
ViolationType string `theorydb:"attr:violationType" json:"violation_type"` // "api" or "federation"
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When violation occurred
PenaltyMinutes int `theorydb:"attr:penaltyMinutes" json:"penalty_minutes"` // Minutes of penalty applied
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Cleanup after 7 days
// contains filtered or unexported fields
}
RateLimitViolation represents a rate limit violation for escalating penalties
func NewRateLimitViolation ¶
func NewRateLimitViolation(userID, domain, endpoint, violationType string, penaltyMinutes int) *RateLimitViolation
NewRateLimitViolation creates a new rate limit violation record
func (*RateLimitViolation) GetPK ¶
func (rlv *RateLimitViolation) GetPK() string
GetPK returns the partition key - required for BaseModel interface
func (*RateLimitViolation) GetSK ¶
func (rlv *RateLimitViolation) GetSK() string
GetSK returns the sort key - required for BaseModel interface
func (RateLimitViolation) TableName ¶
func (RateLimitViolation) TableName() string
TableName returns the DynamoDB table name for rate limit violations
func (*RateLimitViolation) UpdateKeys ¶
func (rlv *RateLimitViolation) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the RateLimitViolation model
type Reaction ¶
type Reaction struct {
Name string `json:"name"` // Emoji name or custom emoji shortcode
Count int `json:"count"` // Number of users who reacted
Me bool `json:"me"` // Whether the current user reacted
URL string `json:"url,omitempty"` // URL for custom emoji
StaticURL string `json:"static_url,omitempty"` // Static URL for custom emoji
}
Reaction represents an available reaction for announcements
type RealtimeStats ¶
type RealtimeStats struct {
Uptime time.Duration
TotalAnalyzed int64
AnalysisRate float64 // per second
AllowRate float64
FlagRate float64
RemoveRate float64
QuarantineRate float64
AvgResponseTime time.Duration
P95ResponseTime time.Duration
}
RealtimeStats represents current real-time statistics
func (RealtimeStats) TableName ¶
func (RealtimeStats) TableName() string
TableName returns the DynamoDB table backing RealtimeStats.
type ReconnectionAttempt ¶
type ReconnectionAttempt struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Domain string `theorydb:"attr:domain" json:"domain"`
AttemptedAt time.Time `theorydb:"attr:attemptedAt" json:"attempted_at"`
Success bool `theorydb:"attr:success" json:"success"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
Method string `theorydb:"attr:method" json:"method"` // "manual", "automatic", "scheduled"
// contains filtered or unexported fields
}
ReconnectionAttempt tracks attempts to reconnect to severed domains
func (ReconnectionAttempt) TableName ¶
func (ReconnectionAttempt) TableName() string
TableName returns the DynamoDB table backing ReconnectionAttempt.
func (*ReconnectionAttempt) UpdateKeys ¶
func (r *ReconnectionAttempt) UpdateKeys()
UpdateKeys updates the GSI keys for reconnection attempt
type RecoveryCode ¶
type RecoveryCode struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"` // USER#username
SK string `theorydb:"sk,attr:SK"` // RECOVERY_CODE#position
// Business fields
Username string `theorydb:"attr:username" json:"username"`
CodeHash string `theorydb:"attr:codeHash" json:"code_hash"` // bcrypt hash of the code
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UsedAt *time.Time `theorydb:"attr:usedAt" json:"used_at,omitempty"`
Position int `theorydb:"attr:position" json:"position"` // Position in the list (0-7 typically)
// contains filtered or unexported fields
}
RecoveryCode represents a single recovery code
func (RecoveryCode) TableName ¶
func (RecoveryCode) TableName() string
TableName returns the DynamoDB table backing RecoveryCode.
func (*RecoveryCode) UpdateKeys ¶
func (c *RecoveryCode) UpdateKeys() error
UpdateKeys updates the primary and GSI keys based on the model's business fields
type RecoveryRequest ¶
type RecoveryRequest struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"` // RECOVERY#id
SK string `theorydb:"sk,attr:SK"` // REQUEST
// GSI1 for querying by username
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // USER#username
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // RECOVERY#timestamp
// Business fields
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
InitiatedAt time.Time `theorydb:"attr:initiatedAt" json:"initiated_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
RequiredVotes int `theorydb:"attr:requiredVotes" json:"required_votes"`
ReceivedVotes map[string]bool `theorydb:"attr:receivedVotes" json:"received_votes"` // trustee_id -> voted
RecoveryToken string `theorydb:"attr:recoveryToken" json:"recovery_token"`
Status string `theorydb:"attr:status" json:"status"` // pending, approved, expired, cancelled
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RecoveryRequest represents an active social recovery request
func (*RecoveryRequest) GetPK ¶
func (r *RecoveryRequest) GetPK() string
GetPK returns the partition key
func (RecoveryRequest) TableName ¶
func (RecoveryRequest) TableName() string
TableName returns the DynamoDB table backing RecoveryRequest.
func (*RecoveryRequest) UpdateKeys ¶
func (r *RecoveryRequest) UpdateKeys() error
UpdateKeys updates the primary and GSI keys based on the model's business fields
type RecoveryToken ¶
type RecoveryToken struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"` // The key parameter directly
SK string `theorydb:"sk,attr:SK"` // TOKEN
// Business fields
Data map[string]any `theorydb:"attr:data" json:"data"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for automatic cleanup (24 hours)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RecoveryToken represents a generic recovery token with custom data
func (*RecoveryToken) GetPK ¶
func (t *RecoveryToken) GetPK() string
GetPK returns the partition key
func (RecoveryToken) TableName ¶
func (RecoveryToken) TableName() string
TableName returns the DynamoDB table backing RecoveryToken.
func (*RecoveryToken) UpdateKeys ¶
func (t *RecoveryToken) UpdateKeys() error
UpdateKeys updates the primary keys and TTL based on the model's business fields
type RefreshToken ¶
type RefreshToken struct {
// DynamoDB keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"-"` // REFRESHTOKEN#token
SK string `theorydb:"sk,attr:SK" json:"-"` // TOKEN
// Refresh lineage and runtime-session lookup GSIs. GSI2 indexes every
// refresh family; GSI1/GSI3 remain sparse to tokens carrying runtime state.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"`
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"`
// Core fields from legacy storage.RefreshToken
Token string `theorydb:"attr:token" json:"Token"`
ClientID string `theorydb:"attr:clientID" json:"ClientID"`
Username string `theorydb:"attr:username" json:"Username"`
PrincipalUsername string `theorydb:"attr:principalUsername,omitempty" json:"PrincipalUsername,omitempty"`
Resource string `theorydb:"attr:resource,omitempty" json:"Resource,omitempty"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"ExpiresAt"`
Scopes []string `theorydb:"attr:scopes" json:"Scopes"`
ClientClass string `theorydb:"attr:clientClass" json:"ClientClass,omitempty"`
SessionID string `theorydb:"attr:sessionID" json:"SessionID,omitempty"`
// Rotation lineage is shared by all refresh clients. The remaining optional
// runtime-session metadata supports long-lived agent clients and
// operator-visible session management.
FamilyID string `theorydb:"attr:familyID,omitempty" json:"FamilyID,omitempty"`
Generation int `theorydb:"attr:generation,omitempty" json:"Generation,omitempty"`
Current bool `theorydb:"attr:current" json:"Current"`
Revoked bool `theorydb:"attr:revoked" json:"Revoked"`
RevokedAt time.Time `theorydb:"attr:revokedAt,omitempty" json:"RevokedAt,omitempty"`
RevokedReason string `theorydb:"attr:revokedReason,omitempty" json:"RevokedReason,omitempty"`
ReplacedByHash string `theorydb:"attr:replacedByHash,omitempty" json:"ReplacedByHash,omitempty"`
RetryRedeemedAt time.Time `theorydb:"attr:retryRedeemedAt,omitempty" json:"RetryRedeemedAt,omitempty"`
DeviceLabel string `theorydb:"attr:deviceLabel,omitempty" json:"DeviceLabel,omitempty"`
LastUsedAt time.Time `theorydb:"attr:lastUsedAt,omitempty" json:"LastUsedAt,omitempty"`
IdleExpiresAt time.Time `theorydb:"attr:idleExpiresAt,omitempty" json:"IdleExpiresAt,omitempty"`
AbsoluteExpiresAt time.Time `theorydb:"attr:absoluteExpiresAt,omitempty" json:"AbsoluteExpiresAt,omitempty"`
SessionCreatedAt time.Time `theorydb:"attr:sessionCreatedAt,omitempty" json:"SessionCreatedAt,omitempty"`
AccessTTLSeconds int `theorydb:"attr:accessTTLSeconds,omitempty" json:"AccessTTLSeconds,omitempty"`
ReuseDetectedAt time.Time `theorydb:"attr:reuseDetectedAt,omitempty" json:"ReuseDetectedAt,omitempty"`
ReuseDetectedFromIP string `theorydb:"attr:reuseDetectedFromIP,omitempty" json:"ReuseDetectedFromIP,omitempty"`
ReuseDetectedFromUA string `theorydb:"attr:reuseDetectedFromUA,omitempty" json:"ReuseDetectedFromUA,omitempty"`
LastAuthFailureCode string `theorydb:"attr:lastAuthFailureCode,omitempty" json:"LastAuthFailureCode,omitempty"`
LastAuthFailureAt time.Time `theorydb:"attr:lastAuthFailureAt,omitempty" json:"LastAuthFailureAt,omitempty"`
LastAuthFailureMsg string `theorydb:"attr:lastAuthFailureMsg,omitempty" json:"LastAuthFailureMsg,omitempty"`
LastAuthSuccessAt time.Time `theorydb:"attr:lastAuthSuccessAt,omitempty" json:"LastAuthSuccessAt,omitempty"`
// Tracking fields
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
// TTL field for automatic expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// Version enables optimistic locking so refresh rotation can use compare-and-swap semantics.
Version int `theorydb:"version,attr:version" json:"Version,omitempty"`
// contains filtered or unexported fields
}
RefreshToken represents an OAuth 2.0 refresh token
func (*RefreshToken) BeforeCreate ¶
func (r *RefreshToken) BeforeCreate() error
BeforeCreate sets up the keys and TTL before creating
func (*RefreshToken) GetPK ¶
func (r *RefreshToken) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*RefreshToken) GetSK ¶
func (r *RefreshToken) GetSK() string
GetSK returns the sort key for BaseModel interface
func (RefreshToken) TableName ¶
func (RefreshToken) TableName() string
TableName returns the DynamoDB table name
func (*RefreshToken) UpdateKeys ¶
func (r *RefreshToken) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates DynamoDB keys
type RelationshipRecord ¶
type RelationshipRecord struct {
// Primary keys - MUST match legacy exactly (UPPERCASE prefixes!)
PK string `theorydb:"pk,attr:PK" json:"PK"` // FOLLOW#{followerUsername}
SK string `theorydb:"sk,attr:SK" json:"SK"` // FOLLOWING#{followingUsername}
// GSI1 for reverse lookups (who follows me)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // FOLLOW#{followedUsername}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // FOLLOWER#{followerUsername}
// GSI2 for follower domain queries (Phase 2.4 - severance detection)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2PK,omitempty"` // FOLLOWER_DOMAIN#{domain}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2SK,omitempty"` // FOLLOWING#{username}
// GSI3 for following domain queries (Phase 2.4 - severance detection)
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3PK,omitempty"` // FOLLOWING_DOMAIN#{domain}
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3SK,omitempty"` // FOLLOWER#{username}
// Core fields from legacy
ActivityID string `theorydb:"attr:activityID" json:"ActivityID"`
State string `theorydb:"attr:state" json:"State"` // pending, accepted, rejected
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"UpdatedAt"`
// Relationship preferences
Notifying bool `theorydb:"attr:notifying" json:"Notifying"` // Receive notifications for this user's posts
ShowingReblogs bool `theorydb:"attr:showingReblogs" json:"ShowingReblogs"` // Show reblogs from this user in timeline
Languages []string `theorydb:"attr:languages" json:"Languages,omitempty"` // Filter to specific languages (empty = all)
Note string `theorydb:"attr:note" json:"Note,omitempty"` // Private note about this relationship
// contains filtered or unexported fields
}
RelationshipRecord represents a follow relationship between users This model preserves the EXACT key patterns from the legacy implementation
func NewRelationshipRecord ¶
func NewRelationshipRecord(followerUsername, followingUsername, activityID string) *RelationshipRecord
NewRelationshipRecord creates a new relationship record with proper keys
func (*RelationshipRecord) Accept ¶
func (r *RelationshipRecord) Accept()
Accept updates the relationship to accepted state
func (*RelationshipRecord) BeforeCreate ¶
func (r *RelationshipRecord) BeforeCreate() error
BeforeCreate sets up the record before creation
func (*RelationshipRecord) BeforeUpdate ¶
func (r *RelationshipRecord) BeforeUpdate() error
BeforeUpdate updates timestamps
func (*RelationshipRecord) ExtractFollowerFromGSI ¶
func (r *RelationshipRecord) ExtractFollowerFromGSI() string
ExtractFollowerFromGSI extracts follower username from GSI1SK
func (*RelationshipRecord) ExtractFollowerUsername ¶
func (r *RelationshipRecord) ExtractFollowerUsername() string
ExtractFollowerUsername extracts the follower username from PK
func (*RelationshipRecord) ExtractFollowingUsername ¶
func (r *RelationshipRecord) ExtractFollowingUsername() string
ExtractFollowingUsername extracts the following username from SK
func (*RelationshipRecord) GetPK ¶
func (r *RelationshipRecord) GetPK() string
GetPK returns the partition key
func (*RelationshipRecord) GetSK ¶
func (r *RelationshipRecord) GetSK() string
GetSK returns the sort key
func (*RelationshipRecord) Reject ¶
func (r *RelationshipRecord) Reject()
Reject updates the relationship to rejected state
func (RelationshipRecord) TableName ¶
func (RelationshipRecord) TableName() string
TableName returns the DynamoDB table name
func (*RelationshipRecord) UpdateKeys ¶
func (r *RelationshipRecord) UpdateKeys() error
UpdateKeys updates GSI keys based on primary keys
type RelationshipState ¶
type RelationshipState string
RelationshipState represents the lifecycle state of a federation relationship
const ( // StateActive indicates recent activity StateActive RelationshipState = "ACTIVE" // StateIdle indicates no recent activity (7+ days) StateIdle RelationshipState = "IDLE" // StateDormant indicates long inactive period (30+ days) StateDormant RelationshipState = "DORMANT" // StateArchived indicates moved to cold storage (90+ days) StateArchived RelationshipState = "ARCHIVED" // StateExpired indicates marked for deletion (365+ days) StateExpired RelationshipState = "EXPIRED" )
Relationship states for federation lifecycle tracking
type Relay ¶
type Relay struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying active relays
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// GSI fields for querying by domain
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk,omitempty"`
// GSI8 fields for listing all relays
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty" json:"gsi8pk,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty" json:"gsi8sk,omitempty"`
// Business fields matching storage.RelayInfo
URL string `theorydb:"attr:url" json:"url"`
InboxURL string `theorydb:"attr:inboxURL" json:"inbox_url"`
Active bool `theorydb:"attr:active" json:"active"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
LastSeenAt time.Time `theorydb:"attr:lastSeenAt" json:"last_seen_at"`
Domain string `theorydb:"attr:domain" json:"domain,omitempty"`
Status string `theorydb:"attr:status" json:"status,omitempty"` // pending/active/rejected/error
ErrorCount int `theorydb:"attr:errorCount" json:"error_count,omitempty"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // For automatic cleanup
// contains filtered or unexported fields
}
Relay represents a relay server for federation
func (*Relay) UpdateKeys ¶
UpdateKeys updates the composite keys based on the relay data
type RelayBudget ¶
type RelayBudget struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Budget details
RelayURL string `theorydb:"attr:relayURL" json:"relay_url"`
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // "daily", "weekly", "monthly"
LimitMicroCents int64 `theorydb:"attr:limitMicroCents" json:"limit_micro_cents"` // Budget limit in microdollars
// Alert thresholds
WarningThresholdPercent float64 `theorydb:"attr:warningThresholdPercent" json:"warning_threshold_percent"` // e.g., 75.0 for 75%
CriticalThresholdPercent float64 `theorydb:"attr:criticalThresholdPercent" json:"critical_threshold_percent"` // e.g., 90.0 for 90%
// Current usage
CurrentUsageMicroCents int64 `theorydb:"attr:currentUsageMicroCents" json:"current_usage_micro_cents"`
CurrentUsagePercent float64 `theorydb:"attr:currentUsagePercent" json:"current_usage_percent"`
LastResetAt time.Time `theorydb:"attr:lastResetAt" json:"last_reset_at"`
// Alert status
WarningAlertSent bool `theorydb:"attr:warningAlertSent" json:"warning_alert_sent"`
CriticalAlertSent bool `theorydb:"attr:criticalAlertSent" json:"critical_alert_sent"`
BudgetExceeded bool `theorydb:"attr:budgetExceeded" json:"budget_exceeded"`
// Actions on budget exceeded
PauseRelay bool `theorydb:"attr:pauseRelay" json:"pause_relay"` // Pause relay when budget exceeded
NotifyAdmin bool `theorydb:"attr:notifyAdmin" json:"notify_admin"` // Send admin notification
ReduceFrequency bool `theorydb:"attr:reduceFrequency" json:"reduce_frequency"` // Reduce relay forwarding frequency
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RelayBudget represents budget limits for relay operations
func (*RelayBudget) BeforeCreate ¶
func (rb *RelayBudget) BeforeCreate() error
BeforeCreate validates and sets up the model before creation
func (*RelayBudget) BeforeUpdate ¶
func (rb *RelayBudget) BeforeUpdate() error
BeforeUpdate validates and sets up the model before update
func (RelayBudget) TableName ¶
func (RelayBudget) TableName() string
TableName returns the DynamoDB table backing RelayBudget.
func (*RelayBudget) UpdateKeys ¶
func (rb *RelayBudget) UpdateKeys()
UpdateKeys updates the composite keys based on the relay budget data
type RelayCost ¶
type RelayCost struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying by relay URL
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// GSI fields for querying by time period
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk,omitempty"`
// Cost tracking fields
RelayURL string `theorydb:"attr:relayURL" json:"relay_url"`
Domain string `theorydb:"attr:domain" json:"domain"`
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // "subscription", "delivery", "processing", "bandwidth"
Direction string `theorydb:"attr:direction" json:"direction"` // "inbound", "outbound"
ActivityType string `theorydb:"attr:activityType" json:"activity_type,omitempty"` // Create, Announce, Follow, etc.
// Cost details
HTTPRequestCount int64 `theorydb:"attr:httpRequestCount" json:"http_request_count"` // Number of HTTP requests
HTTPRequestCost int64 `theorydb:"attr:httpRequestCost" json:"http_request_cost"` // Cost in microdollars
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Bytes transferred
DataTransferCost int64 `theorydb:"attr:dataTransferCost" json:"data_transfer_cost"` // Cost in microdollars
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Lambda processing time
LambdaCost int64 `theorydb:"attr:lambdaCost" json:"lambda_cost"` // Cost in microdollars
DynamoDBOperations int64 `theorydb:"attr:dynamoDBOperations" json:"dynamodb_operations"` // DB operation count
DynamoDBCost int64 `theorydb:"attr:dynamoDBCost" json:"dynamodb_cost"` // Cost in microdollars
SQSMessages int64 `theorydb:"attr:sqsMessages" json:"sqs_messages"` // SQS message count
SQSCost int64 `theorydb:"attr:sqsCost" json:"sqs_cost"` // Cost in microdollars
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost in microdollars
// Performance metrics
ResponseTimeMs int64 `theorydb:"attr:responseTimeMs" json:"response_time_ms"`
Success bool `theorydb:"attr:success" json:"success"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"`
// Metadata
RequestID string `theorydb:"attr:requestID" json:"request_id,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // For automatic cleanup
// contains filtered or unexported fields
}
RelayCost represents cost tracking for relay operations
func (*RelayCost) BeforeCreate ¶
BeforeCreate validates and sets up the model before creation
func (*RelayCost) UpdateKeys ¶
func (rc *RelayCost) UpdateKeys()
UpdateKeys updates the composite keys based on the relay cost data
type RelayInfo ¶
type RelayInfo struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying active relays
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// GSI fields for querying by status
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk,omitempty"`
// Business fields
URL string `theorydb:"attr:url" json:"url"`
InboxURL string `theorydb:"attr:inboxURL" json:"inbox_url"`
Active bool `theorydb:"attr:active" json:"active"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
LastSeenAt time.Time `theorydb:"attr:lastSeenAt" json:"last_seen_at"`
Domain string `theorydb:"attr:domain" json:"domain"`
Status string `theorydb:"attr:status" json:"status,omitempty"` // pending/active/rejected/error
ErrorCount int `theorydb:"attr:errorCount" json:"error_count,omitempty"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // For automatic cleanup
// contains filtered or unexported fields
}
RelayInfo represents information about a federation relay
func (*RelayInfo) SetError ¶
func (r *RelayInfo) SetError()
SetError increments the error count and updates status
func (*RelayInfo) SetSuccess ¶
func (r *RelayInfo) SetSuccess()
SetSuccess resets error count and updates status
func (*RelayInfo) ShouldRetry ¶
ShouldRetry determines if the relay should be retried based on error count
func (*RelayInfo) UpdateKeys ¶
func (r *RelayInfo) UpdateKeys()
UpdateKeys updates the composite keys based on the relay info
type RelayMetrics ¶
type RelayMetrics struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying by relay URL
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// Metrics details
RelayURL string `theorydb:"attr:relayURL" json:"relay_url"`
Domain string `theorydb:"attr:domain" json:"domain"`
Period string `theorydb:"attr:period" json:"period"` // "hourly", "daily", "weekly", "monthly"
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"`
// Aggregate counts
TotalOperations int64 `theorydb:"attr:totalOperations" json:"total_operations"`
SuccessfulOperations int64 `theorydb:"attr:successfulOperations" json:"successful_operations"`
FailedOperations int64 `theorydb:"attr:failedOperations" json:"failed_operations"`
TotalHTTPRequests int64 `theorydb:"attr:totalHTTPRequests" json:"total_http_requests"`
TotalDataTransferBytes int64 `theorydb:"attr:totalDataTransferBytes" json:"total_data_transfer_bytes"`
TotalLambdaDurationMs int64 `theorydb:"attr:totalLambdaDurationMs" json:"total_lambda_duration_ms"`
TotalDynamoDBOps int64 `theorydb:"attr:totalDynamoDBOps" json:"total_dynamodb_ops"`
TotalSQSMessages int64 `theorydb:"attr:totalSQSMessages" json:"total_sqs_messages"`
// Aggregate costs (in microdollars)
TotalHTTPRequestCost int64 `theorydb:"attr:totalHTTPRequestCost" json:"total_http_request_cost"`
TotalDataTransferCost int64 `theorydb:"attr:totalDataTransferCost" json:"total_data_transfer_cost"`
TotalLambdaCost int64 `theorydb:"attr:totalLambdaCost" json:"total_lambda_cost"`
TotalDynamoDBCost int64 `theorydb:"attr:totalDynamoDBCost" json:"total_dynamodb_cost"`
TotalSQSCost int64 `theorydb:"attr:totalSQSCost" json:"total_sqs_cost"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
// Performance metrics
AverageResponseTimeMs float64 `theorydb:"attr:averageResponseTimeMs" json:"average_response_time_ms"`
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"` // 0.0 to 1.0
AverageRetryCount float64 `theorydb:"attr:averageRetryCount" json:"average_retry_count"`
// Cost efficiency metrics
CostPerOperation float64 `theorydb:"attr:costPerOperation" json:"cost_per_operation"` // Dollars
CostPerSuccessfulOp float64 `theorydb:"attr:costPerSuccessfulOp" json:"cost_per_successful_op"` // Dollars
CostPerMB float64 `theorydb:"attr:costPerMB" json:"cost_per_mb"` // Dollars per MB
// Breakdown by operation type
OperationBreakdown map[string]*RelayOperationStats `theorydb:"attr:operationBreakdown" json:"operation_breakdown,omitempty"`
// Budget tracking
BudgetLimitMicroCents int64 `theorydb:"attr:budgetLimitMicroCents" json:"budget_limit_micro_cents,omitempty"`
BudgetUsedPercent float64 `theorydb:"attr:budgetUsedPercent" json:"budget_used_percent,omitempty"`
BudgetExceeded bool `theorydb:"attr:budgetExceeded" json:"budget_exceeded,omitempty"`
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RelayMetrics represents aggregated metrics for relay operations
func (*RelayMetrics) BeforeCreate ¶
func (rm *RelayMetrics) BeforeCreate() error
BeforeCreate validates and sets up the model before creation
func (*RelayMetrics) BeforeUpdate ¶
func (rm *RelayMetrics) BeforeUpdate() error
BeforeUpdate validates and sets up the model before update
func (RelayMetrics) TableName ¶
func (RelayMetrics) TableName() string
TableName returns the DynamoDB table backing RelayMetrics.
func (*RelayMetrics) UpdateKeys ¶
func (rm *RelayMetrics) UpdateKeys()
UpdateKeys updates the composite keys based on the relay metrics data
type RelayOperationStats ¶
type RelayOperationStats struct {
OperationType string `theorydb:"attr:operationType" json:"operation_type"`
Count int64 `theorydb:"attr:count" json:"count"`
SuccessCount int64 `theorydb:"attr:successCount" json:"success_count"`
FailureCount int64 `theorydb:"attr:failureCount" json:"failure_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
AverageResponseTime float64 `theorydb:"attr:averageResponseTimeMs" json:"average_response_time_ms"`
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"`
// contains filtered or unexported fields
}
RelayOperationStats represents stats for a specific operation type
func (RelayOperationStats) TableName ¶
func (RelayOperationStats) TableName() string
TableName returns the DynamoDB table backing RelayOperationStats.
type RemoteActor ¶
type RemoteActor struct {
// Primary key: REMOTE_ACTOR#{handle}
PK string `theorydb:"pk,attr:PK" json:"pk"`
// Sort key: PROFILE
SK string `theorydb:"sk,attr:SK" json:"sk"`
// Actor data (ActivityPub actor object)
Actor *activitypub.Actor `theorydb:"json,attr:actor" json:"actor"`
// Handle (user@domain format)
Handle string `theorydb:"attr:handle" json:"handle"`
// Domain extracted from handle
Domain string `theorydb:"attr:domain" json:"domain"`
// Cache expiration time
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
// When this was first cached
CachedAt time.Time `theorydb:"attr:cachedAt" json:"cached_at"`
// When this was last updated
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for DynamoDB automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
RemoteActor represents a cached remote actor in DynamoDB using DynamORM
func (RemoteActor) TableName ¶
func (RemoteActor) TableName() string
TableName returns the DynamoDB table backing RemoteActor.
func (*RemoteActor) UpdateKeys ¶
func (r *RemoteActor) UpdateKeys()
UpdateKeys updates the key fields for DynamORM
type ReplySyncRecord ¶
type ReplySyncRecord struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "REPLY_SYNC#{status_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "SYNC#{timestamp}"
// Core fields
StatusID string `theorydb:"attr:statusID" json:"status_id"` // The status we're syncing replies for
SyncAttempt time.Time `theorydb:"attr:syncAttempt" json:"sync_attempt"` // When the sync was attempted
SyncResult string `theorydb:"attr:syncResult" json:"sync_result"` // "success", "partial", "failed"
// Sync details
TotalReplies int `theorydb:"attr:totalReplies" json:"total_replies"` // Total replies known to exist
FetchedReplies int `theorydb:"attr:fetchedReplies" json:"fetched_replies"` // Successfully fetched replies
FailedReplies int `theorydb:"attr:failedReplies" json:"failed_replies"` // Failed to fetch
// Error tracking
LastError string `theorydb:"attr:lastError" json:"last_error,omitempty"` // Last error message
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"` // Number of retries
NextRetryAt *time.Time `theorydb:"attr:nextRetryAt" json:"next_retry_at,omitempty"` // When to retry next
// TTL for automatic cleanup (30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ReplySyncRecord tracks remote reply synchronization attempts
func NewReplySyncRecord ¶
func NewReplySyncRecord(statusID string) *ReplySyncRecord
NewReplySyncRecord creates a new reply sync record
func (*ReplySyncRecord) BeforeCreate ¶
func (r *ReplySyncRecord) BeforeCreate() error
BeforeCreate is called before creating the record
func (*ReplySyncRecord) BeforeUpdate ¶
func (r *ReplySyncRecord) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*ReplySyncRecord) IsExpired ¶
func (r *ReplySyncRecord) IsExpired() bool
IsExpired returns whether this record should be cleaned up
func (*ReplySyncRecord) MarkFailed ¶
func (r *ReplySyncRecord) MarkFailed(errorMsg string)
MarkFailed marks the sync as failed and schedules retry
func (*ReplySyncRecord) MarkPartial ¶
func (r *ReplySyncRecord) MarkPartial(fetched, failed int)
MarkPartial marks the sync as partially successful
func (*ReplySyncRecord) MarkSuccess ¶
func (r *ReplySyncRecord) MarkSuccess(fetched int)
MarkSuccess marks the sync as successful
func (*ReplySyncRecord) ShouldRetry ¶
func (r *ReplySyncRecord) ShouldRetry() bool
ShouldRetry returns whether this sync should be retried
func (ReplySyncRecord) TableName ¶
func (ReplySyncRecord) TableName() string
TableName returns the DynamoDB table name
func (*ReplySyncRecord) UpdateKeys ¶
func (r *ReplySyncRecord) UpdateKeys()
UpdateKeys updates the DynamoDB keys
type Report ¶
type Report struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // REPORT#id
SK string `theorydb:"sk,attr:SK" json:"-"` // REPORT
// GSI fields
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // USER#reporterID
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // REPORT#timestamp
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // REPORTED#targetAccountID
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // REPORT#timestamp
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // STATUS#status
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // REPORT#timestamp
// Report fields
ID string `theorydb:"attr:id" json:"id"`
ReporterID string `theorydb:"attr:reporterID" json:"reporter_id"`
TargetAccountID string `theorydb:"attr:targetAccountID" json:"target_account_id"`
StatusIDs []string `theorydb:"attr:statusIDs" json:"status_ids,omitempty"`
Comment string `theorydb:"attr:comment" json:"comment"`
Category string `theorydb:"attr:category" json:"category"`
RuleIDs []int `theorydb:"attr:ruleIDs" json:"rule_ids,omitempty"`
Forwarded bool `theorydb:"attr:forwarded" json:"forwarded"`
Status string `theorydb:"attr:status" json:"status"`
ActionTaken string `theorydb:"attr:actionTaken" json:"action_taken,omitempty"`
ActionTakenAt *time.Time `theorydb:"attr:actionTakenAt" json:"action_taken_at,omitempty"`
ModeratorID string `theorydb:"attr:moderatorID" json:"moderator_id,omitempty"`
ModerationEventID string `theorydb:"attr:moderationEventID" json:"moderation_event_id,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
AssignedTo string `theorydb:"attr:assignedTo" json:"assigned_to,omitempty"`
// TTL for auto-deletion (90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Report represents a user report stored in DynamoDB
func (*Report) UpdateKeys ¶
func (r *Report) UpdateKeys()
UpdateKeys updates the GSI keys based on the report data
type ReportStats ¶
type ReportStats struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // USER#username
SK string `theorydb:"sk,attr:SK" json:"-"` // REPORT_STATS
// Stats fields
TotalReports int `theorydb:"attr:totalReports" json:"total_reports"`
ResolvedReports int `theorydb:"attr:resolvedReports" json:"resolved_reports"`
FalseReports int `theorydb:"attr:falseReports" json:"false_reports"`
LastReportAt *time.Time `theorydb:"attr:lastReportAt" json:"last_report_at,omitempty"`
LastFalseReportAt *time.Time `theorydb:"attr:lastFalseReportAt" json:"last_false_report_at,omitempty"`
// contains filtered or unexported fields
}
ReportStats represents reporting statistics for a user
func (ReportStats) TableName ¶
func (ReportStats) TableName() string
TableName returns the DynamoDB table backing ReportStats.
func (*ReportStats) UpdateKeys ¶
func (rs *ReportStats) UpdateKeys(username string)
UpdateKeys updates the primary key fields
type Reputation ¶
type Reputation struct {
// Primary key fields - EXACT pattern from legacy
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// Reputation data stored as JSON
ReputationData string `theorydb:"attr:reputationData" json:"reputation_data"`
// Indexed fields for queries
TotalScore int `theorydb:"attr:totalScore" json:"total_score"`
CalculatedAt string `theorydb:"attr:calculatedAt" json:"calculated_at"`
// TTL for 90-day expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
Reputation represents reputation data for an actor
func (Reputation) TableName ¶
func (Reputation) TableName() string
TableName returns the DynamoDB table backing Reputation.
func (*Reputation) ToStorageReputation ¶
func (r *Reputation) ToStorageReputation() (interface{}, error)
ToStorageReputation converts the model back to a map that can be used as storage.Reputation
func (*Reputation) UpdateKeys ¶
func (r *Reputation) UpdateKeys(actorID string, reputation interface{}) error
UpdateKeys updates the PK and SK based on the reputation data
type RetryPolicy ¶
type RetryPolicy struct {
MaxRetries int `json:"max_retries"`
InitialBackoff time.Duration `json:"initial_backoff"`
MaxBackoff time.Duration `json:"max_backoff"`
BackoffFactor float64 `json:"backoff_factor"`
}
RetryPolicy defines retry behavior for federation operations
func (RetryPolicy) TableName ¶
func (RetryPolicy) TableName() string
TableName returns the DynamoDB table backing RetryPolicy.
type ReviewerStats ¶
type ReviewerStats struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // REVIEWER#{reviewerID}
SK string `theorydb:"sk,attr:SK" json:"-"` // STATS
// Attributes from interface
ReviewerID string `theorydb:"attr:reviewerID" json:"reviewer_id"`
TotalReviews int `theorydb:"attr:totalReviews" json:"total_reviews"`
AccurateReviews int `theorydb:"attr:accurateReviews" json:"accurate_reviews"`
AccuracyRate float64 `theorydb:"attr:accuracyRate" json:"accuracy_rate"`
LastReviewAt time.Time `theorydb:"attr:lastReviewAt" json:"last_review_at"`
TrustScore float64 `theorydb:"attr:trustScore" json:"trust_score"`
JoinedAt time.Time `theorydb:"attr:joinedAt" json:"joined_at"`
ReviewsByCategory map[string]int `theorydb:"attr:reviewsByCategory" json:"reviews_by_category"`
// Additional statistics
ConsecutiveAccurate int `theorydb:"attr:consecutiveAccurate" json:"consecutive_accurate"` // Current streak
MaxStreak int `theorydb:"attr:maxStreak" json:"max_streak"` // Best streak
RecentAccuracy float64 `theorydb:"attr:recentAccuracy" json:"recent_accuracy"` // Last 100 reviews
ResponseTimeAvg float64 `theorydb:"attr:responseTimeAvg" json:"response_time_avg"` // Average response time in seconds
DisagreementRate float64 `theorydb:"attr:disagreementRate" json:"disagreement_rate"` // Rate of disagreeing with consensus
SpecializationScores map[string]float64 `theorydb:"attr:specializationScores" json:"specialization_scores"` // Accuracy by category
LastTrainingCompleted *time.Time `theorydb:"attr:lastTrainingCompleted" json:"last_training_completed,omitempty"`
BadgesEarned []string `theorydb:"attr:badgesEarned" json:"badges_earned,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
ReviewerStats represents statistics about a moderation reviewer
func NewReviewerStats ¶
func NewReviewerStats(reviewerID string) *ReviewerStats
NewReviewerStats creates new reviewer statistics
func (*ReviewerStats) CalculateAccuracyRate ¶
func (r *ReviewerStats) CalculateAccuracyRate()
CalculateAccuracyRate calculates the overall accuracy rate
func (*ReviewerStats) CalculateTrustScore ¶
func (r *ReviewerStats) CalculateTrustScore()
CalculateTrustScore calculates trust score based on multiple factors
func (*ReviewerStats) EarnBadge ¶
func (r *ReviewerStats) EarnBadge(badge string) bool
EarnBadge adds a badge if not already earned
func (*ReviewerStats) GetSpecialization ¶
func (r *ReviewerStats) GetSpecialization() (category string, score float64)
GetSpecialization returns the reviewer's best category
func (*ReviewerStats) IsExperienced ¶
func (r *ReviewerStats) IsExperienced() bool
IsExperienced checks if reviewer has enough experience
func (*ReviewerStats) IsTrusted ¶
func (r *ReviewerStats) IsTrusted() bool
IsTrusted checks if reviewer is highly trusted
func (*ReviewerStats) NeedsTraining ¶
func (r *ReviewerStats) NeedsTraining() bool
NeedsTraining checks if reviewer needs additional training
func (*ReviewerStats) RecordReview ¶
func (r *ReviewerStats) RecordReview(category string, wasAccurate bool, responseTime float64)
RecordReview updates stats after a review
func (ReviewerStats) TableName ¶
func (ReviewerStats) TableName() string
TableName returns the DynamoDB table backing ReviewerStats.
func (*ReviewerStats) UpdateKeys ¶
func (r *ReviewerStats) UpdateKeys()
UpdateKeys updates the partition and sort keys
func (*ReviewerStats) UpdateSpecializationScore ¶
func (r *ReviewerStats) UpdateSpecializationScore(category string, recentAccuracy float64)
UpdateSpecializationScore updates accuracy for a specific category
type Revision ¶
type Revision struct {
// Primary keys: OBJECT#{object_id}#REVISION / VERSION#{version}
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// Core fields
ID string `theorydb:"attr:id" json:"id"` // Unique revision ID
ObjectID string `theorydb:"attr:objectID" json:"object_id"`
Version int `theorydb:"attr:version" json:"version"`
// Snapshot of content at this version
Content string `theorydb:"attr:content" json:"content"`
ContentHash string `theorydb:"attr:contentHash" json:"content_hash"` // SHA256 for deduplication
MetadataJSON string `theorydb:"attr:metadataJSON" json:"metadata_json"`
// Change tracking
ChangeSummary string `theorydb:"attr:changeSummary" json:"change_summary,omitempty"` // Optional commit message
ChangedBy string `theorydb:"attr:changedBy" json:"changed_by"`
ChangeType string `theorydb:"attr:changeType" json:"change_type"` // create, update, restore
GeneratedBy string `theorydb:"attr:generatedBy,omitempty" json:"generated_by,omitempty"`
ReviewedBy string `theorydb:"attr:reviewedBy,omitempty" json:"reviewed_by,omitempty"`
PublishedBy string `theorydb:"attr:publishedBy,omitempty" json:"published_by,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
Revision represents a historical version of a published object
func (*Revision) UpdateKeys ¶
UpdateKeys updates the keys for the Revision model
type RevokedAccessToken ¶ added in v0.1.36
type RevokedAccessToken struct {
PK string `theorydb:"pk,attr:PK" json:"-"` // REVOKEDTOKEN#<jti>
SK string `theorydb:"sk,attr:SK" json:"-"` // TOKEN
JTI string `theorydb:"attr:jti" json:"jti"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
RevokedAt time.Time `theorydb:"attr:revokedAt" json:"revoked_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
RevokedAccessToken represents a revoked OAuth access token (JWT ID / JTI).
Records are short-lived and should expire automatically via DynamoDB TTL when the token expires.
func (*RevokedAccessToken) BeforeCreate ¶ added in v0.1.36
func (r *RevokedAccessToken) BeforeCreate() error
BeforeCreate sets up keys and TTL before creation.
func (*RevokedAccessToken) GetPK ¶ added in v0.1.36
func (r *RevokedAccessToken) GetPK() string
GetPK implements BaseModel interface.
func (*RevokedAccessToken) GetSK ¶ added in v0.1.36
func (r *RevokedAccessToken) GetSK() string
GetSK implements BaseModel interface.
func (RevokedAccessToken) TableName ¶ added in v0.1.36
func (RevokedAccessToken) TableName() string
TableName returns the DynamoDB table name.
func (*RevokedAccessToken) UpdateKeys ¶ added in v0.1.36
func (r *RevokedAccessToken) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates DynamoDB keys.
type RouteDeliveryResult ¶
type RouteDeliveryResult struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // ROUTE#{routeID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // RESULT#{timestampNano}
// GSI keys for time-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // RESULTS
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {timestamp}#{routeID}
// Delivery data
MessageID string `theorydb:"attr:messageID" json:"message_id"`
RouteID string `theorydb:"attr:routeID" json:"route_id"`
Success bool `theorydb:"attr:success" json:"success"`
StatusCode int `theorydb:"attr:statusCode" json:"status_code"`
Duration int64 `theorydb:"attr:duration" json:"duration_ms"` // Duration in milliseconds
BytesSent int64 `theorydb:"attr:bytesSent" json:"bytes_sent"`
Cost float64 `theorydb:"attr:cost" json:"cost"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RouteDeliveryResult represents a delivery result record for route optimization
func (*RouteDeliveryResult) GetPK ¶
func (r *RouteDeliveryResult) GetPK() string
GetPK returns the partition key
func (*RouteDeliveryResult) GetSK ¶
func (r *RouteDeliveryResult) GetSK() string
GetSK returns the sort key
func (RouteDeliveryResult) TableName ¶
func (RouteDeliveryResult) TableName() string
TableName returns the DynamoDB table backing RouteDeliveryResult.
func (*RouteDeliveryResult) UpdateKeys ¶
func (r *RouteDeliveryResult) UpdateKeys() error
UpdateKeys updates the GSI keys based on the current data
type RouteMetricsWindow ¶
type RouteMetricsWindow struct {
// Primary keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // METRICS#ROUTE#{routeID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // WINDOW#{windowStartUnix}
// Route and time info
RouteID string `theorydb:"attr:routeID" json:"route_id"`
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"`
WindowSize int64 `theorydb:"attr:windowSizeMinutes" json:"window_size_minutes"`
// Aggregated metrics
MessageCount int64 `theorydb:"attr:messageCount" json:"message_count"`
SuccessCount int64 `theorydb:"attr:successCount" json:"success_count"`
FailureCount int64 `theorydb:"attr:failureCount" json:"failure_count"`
TotalBytes int64 `theorydb:"attr:totalBytes" json:"total_bytes"`
TotalCost float64 `theorydb:"attr:totalCost" json:"total_cost"`
AvgLatency int64 `theorydb:"attr:avgLatencyMs" json:"avg_latency_ms"`
CircuitChanges int64 `theorydb:"attr:circuitChanges" json:"circuit_changes"`
// Latency histogram (JSON-encoded map[int]int64)
LatencyHistogram string `theorydb:"attr:latencyHistogram" json:"latency_histogram,omitempty"`
// Error types (JSON-encoded map[string]int64)
ErrorTypes string `theorydb:"attr:errorTypes" json:"error_types,omitempty"`
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
RouteMetricsWindow represents aggregated route metrics for a time window
func (*RouteMetricsWindow) GetPK ¶
func (r *RouteMetricsWindow) GetPK() string
GetPK returns the partition key
func (*RouteMetricsWindow) GetSK ¶
func (r *RouteMetricsWindow) GetSK() string
GetSK returns the sort key
func (RouteMetricsWindow) TableName ¶
func (RouteMetricsWindow) TableName() string
TableName returns the DynamoDB table backing RouteMetricsWindow.
func (*RouteMetricsWindow) UpdateKeys ¶
func (r *RouteMetricsWindow) UpdateKeys() error
UpdateKeys updates the keys based on the current data
type RouteRecommendation ¶
type RouteRecommendation struct {
Type string `json:"type"` // performance, reliability, cost, etc.
Priority string `json:"priority"` // critical, high, medium, low
Title string `json:"title"` // Brief title
Description string `json:"description"` // Detailed description
Action string `json:"action"` // Recommended action
Impact string `json:"impact"` // Expected impact level
}
RouteRecommendation represents a route optimization recommendation
func (RouteRecommendation) TableName ¶
func (RouteRecommendation) TableName() string
TableName returns the DynamoDB table backing RouteRecommendation.
type ScheduledJobCategoryStats ¶
type ScheduledJobCategoryStats struct {
Category string `theorydb:"attr:category" json:"category"`
ExecutionCount int64 `theorydb:"attr:executionCount" json:"execution_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerExecution float64 `theorydb:"attr:averageCostPerExecution" json:"average_cost_per_execution"`
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"`
// contains filtered or unexported fields
}
ScheduledJobCategoryStats represents cost statistics for a job category
func (ScheduledJobCategoryStats) TableName ¶
func (ScheduledJobCategoryStats) TableName() string
TableName returns the DynamoDB table backing ScheduledJobCategoryStats.
type ScheduledJobCostAggregation ¶
type ScheduledJobCostAggregation struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "SCHEDULED_JOB_AGG#{period}#{jobName}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "WINDOW#{windowStart}"
// Aggregation details
JobName string `theorydb:"attr:jobName" json:"job_name"` // Specific job or "all" for all jobs
Period string `theorydb:"attr:period" json:"period"` // "hour", "day", "week", "month"
Schedule string `theorydb:"attr:schedule" json:"schedule"` // Job schedule pattern
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"` // Start of aggregation window
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"` // End of aggregation window
// Execution statistics
TotalExecutions int64 `theorydb:"attr:totalExecutions" json:"total_executions"` // Total job executions
SuccessfulExecutions int64 `theorydb:"attr:successfulExecutions" json:"successful_executions"` // Successful executions
FailedExecutions int64 `theorydb:"attr:failedExecutions" json:"failed_executions"` // Failed executions
TimeoutExecutions int64 `theorydb:"attr:timeoutExecutions" json:"timeout_executions"` // Timed out executions
CancelledExecutions int64 `theorydb:"attr:cancelledExecutions" json:"cancelled_executions"` // Cancelled executions
SuccessRate float64 `theorydb:"attr:successRate" json:"success_rate"` // Success rate percentage
AverageExecutionTime float64 `theorydb:"attr:averageExecutionTime" json:"average_execution_time"` // Average execution time (ms)
MedianExecutionTime float64 `theorydb:"attr:medianExecutionTime" json:"median_execution_time"` // Median execution time (ms)
P95ExecutionTime float64 `theorydb:"attr:p95ExecutionTime" json:"p95_execution_time"` // 95th percentile execution time (ms)
// Resource aggregations
TotalLambdaInvocations int64 `theorydb:"attr:totalLambdaInvocations" json:"total_lambda_invocations"`
TotalLambdaDurationMs int64 `theorydb:"attr:totalLambdaDurationMs" json:"total_lambda_duration_ms"`
AverageLambdaMemoryUsedMB float64 `theorydb:"attr:averageLambdaMemoryUsedMB" json:"average_lambda_memory_used_mb"`
TotalDynamoDBOperations int64 `theorydb:"attr:totalDynamoDBOperations" json:"total_dynamodb_operations"`
TotalDynamoDBCapacity float64 `theorydb:"attr:totalDynamoDBCapacity" json:"total_dynamodb_capacity"`
TotalItemsProcessed int64 `theorydb:"attr:totalItemsProcessed" json:"total_items_processed"`
TotalItemsErrored int64 `theorydb:"attr:totalItemsErrored" json:"total_items_errored"`
// Cost aggregations
TotalLambdaCostMicroCents int64 `theorydb:"attr:totalLambdaCostMicroCents" json:"total_lambda_cost_micro_cents"`
TotalDynamoDBCostMicroCents int64 `theorydb:"attr:totalDynamoDBCostMicroCents" json:"total_dynamodb_cost_micro_cents"`
TotalSQSCostMicroCents int64 `theorydb:"attr:totalSQSCostMicroCents" json:"total_sqs_cost_micro_cents"`
TotalS3CostMicroCents int64 `theorydb:"attr:totalS3CostMicroCents" json:"total_s3_cost_micro_cents"`
TotalCloudWatchCostMicroCents int64 `theorydb:"attr:totalCloudWatchCostMicroCents" json:"total_cloudwatch_cost_micro_cents"`
TotalDataTransferCostMicroCents int64 `theorydb:"attr:totalDataTransferCostMicroCents" json:"total_data_transfer_cost_micro_cents"`
TotalExternalAPICostMicroCents int64 `theorydb:"attr:totalExternalAPICostMicroCents" json:"total_external_api_cost_micro_cents"`
TotalCascadingCostMicroCents int64 `theorydb:"attr:totalCascadingCostMicroCents" json:"total_cascading_cost_micro_cents"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerExecution float64 `theorydb:"attr:averageCostPerExecution" json:"average_cost_per_execution"`
// Cost efficiency metrics
CostPerItemProcessed float64 `theorydb:"attr:costPerItemProcessed" json:"cost_per_item_processed"` // Cost efficiency
CostPerSuccessfulExecution float64 `theorydb:"attr:costPerSuccessfulExecution" json:"cost_per_successful_execution"` // Cost of successful runs
CostEfficiencyTrend float64 `theorydb:"attr:costEfficiencyTrend" json:"cost_efficiency_trend"` // Trend in cost efficiency
// Breakdown by job properties
JobCategoryBreakdown map[string]*ScheduledJobCategoryStats `theorydb:"attr:jobCategoryBreakdown" json:"job_category_breakdown,omitempty"`
EnvironmentBreakdown map[string]*ScheduledJobEnvironmentStats `theorydb:"attr:environmentBreakdown" json:"environment_breakdown,omitempty"`
ScheduleBreakdown map[string]*ScheduledJobScheduleStats `theorydb:"attr:scheduleBreakdown" json:"schedule_breakdown,omitempty"`
// Performance trends
ExecutionTimePercentiles map[string]float64 `theorydb:"attr:executionTimePercentiles" json:"execution_time_percentiles,omitempty"` // p50, p90, p95, p99
CostPercentiles map[string]float64 `theorydb:"attr:costPercentiles" json:"cost_percentiles,omitempty"` // Cost distribution
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL (longer for aggregated data - 365 days)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"`
// contains filtered or unexported fields
}
ScheduledJobCostAggregation represents pre-computed aggregations for scheduled job costs
func (*ScheduledJobCostAggregation) BeforeCreate ¶
func (sjca *ScheduledJobCostAggregation) BeforeCreate() error
BeforeCreate for ScheduledJobCostAggregation
func (*ScheduledJobCostAggregation) BeforeUpdate ¶
func (sjca *ScheduledJobCostAggregation) BeforeUpdate() error
BeforeUpdate for ScheduledJobCostAggregation
func (*ScheduledJobCostAggregation) GetPK ¶
func (sjca *ScheduledJobCostAggregation) GetPK() string
GetPK returns the partition key for ScheduledJobCostAggregation
func (*ScheduledJobCostAggregation) GetSK ¶
func (sjca *ScheduledJobCostAggregation) GetSK() string
GetSK returns the sort key for ScheduledJobCostAggregation
func (ScheduledJobCostAggregation) TableName ¶
func (ScheduledJobCostAggregation) TableName() string
TableName returns the DynamoDB table backing ScheduledJobCostAggregation.
func (*ScheduledJobCostAggregation) UpdateKeys ¶
func (sjca *ScheduledJobCostAggregation) UpdateKeys() error
UpdateKeys updates the keys for ScheduledJobCostAggregation
func (*ScheduledJobCostAggregation) Validate ¶
func (sjca *ScheduledJobCostAggregation) Validate() error
Validate for ScheduledJobCostAggregation
type ScheduledJobCostRecord ¶
type ScheduledJobCostRecord struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "SCHEDULED_JOB_COST#{jobName}#{schedule}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "RUN#{timestamp}#{id}"
// GSI1 - Job status and performance queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "SCHEDULED_JOB_STATUS#{status}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{jobName}#{id}"
// GSI2 - Date range queries across all jobs
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "SCHEDULED_JOB_DATE#{dateStr}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{jobName}#{id}"
// Core job information
ID string `theorydb:"attr:id" json:"id"` // Unique execution ID
JobName string `theorydb:"attr:jobName" json:"job_name"` // e.g., "cost-aggregation", "cleanup-expired-data"
Schedule string `theorydb:"attr:schedule" json:"schedule"` // e.g., "hourly", "daily", "weekly", "monthly"
CronPattern string `theorydb:"attr:cronPattern" json:"cron_pattern,omitempty"` // Actual cron expression if available
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"` // When the job ran
StartTime time.Time `theorydb:"attr:startTime" json:"start_time"` // Job start time
EndTime time.Time `theorydb:"attr:endTime" json:"end_time"` // Job end time
Duration int64 `theorydb:"attr:durationMs" json:"duration_ms"` // Duration in milliseconds
// Job execution status
Status string `theorydb:"attr:status" json:"status"` // "success", "failed", "timeout", "cancelled"
Success bool `theorydb:"attr:success" json:"success"` // Whether job completed successfully
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"` // Error details if failed
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"` // Number of retries attempted
MaxRetries int `theorydb:"attr:maxRetries" json:"max_retries"` // Maximum retries configured
// Resource usage tracking
LambdaInvocations int64 `theorydb:"attr:lambdaInvocations" json:"lambda_invocations"` // Number of Lambda invocations
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Total Lambda execution time
LambdaMemoryUsedMB int `theorydb:"attr:lambdaMemoryUsedMB" json:"lambda_memory_used_mb"` // Peak memory usage
LambdaRequestCount int64 `theorydb:"attr:lambdaRequestCount" json:"lambda_request_count"` // Total Lambda requests
// DynamoDB operations performed by the job
DynamoDBReadOperations int64 `theorydb:"attr:dynamoDBReadOperations" json:"dynamodb_read_operations"` // Read operations count
DynamoDBWriteOperations int64 `theorydb:"attr:dynamoDBWriteOperations" json:"dynamodb_write_operations"` // Write operations count
DynamoDBReadCapacity float64 `theorydb:"attr:dynamoDBReadCapacity" json:"dynamodb_read_capacity"` // Read capacity consumed
DynamoDBWriteCapacity float64 `theorydb:"attr:dynamoDBWriteCapacity" json:"dynamodb_write_capacity"` // Write capacity consumed
// Other AWS service usage
SQSMessages int64 `theorydb:"attr:sqsMessages" json:"sqs_messages"` // SQS messages processed
S3Operations int64 `theorydb:"attr:s3Operations" json:"s3_operations"` // S3 operations performed
CloudWatchLogs int64 `theorydb:"attr:cloudWatchLogs" json:"cloudwatch_logs"` // Log entries written
DataTransferBytes int64 `theorydb:"attr:dataTransferBytes" json:"data_transfer_bytes"` // Data transfer volume
ExternalAPIRequests int64 `theorydb:"attr:externalAPIRequests" json:"external_api_requests"` // External API calls made
// Cost breakdown (in microcents for precision)
LambdaCostMicroCents int64 `theorydb:"attr:lambdaCostMicroCents" json:"lambda_cost_micro_cents"` // Lambda execution cost
DynamoDBCostMicroCents int64 `theorydb:"attr:dynamodbCostMicroCents" json:"dynamodb_cost_micro_cents"` // DynamoDB operations cost
SQSCostMicroCents int64 `theorydb:"attr:sqsCostMicroCents" json:"sqs_cost_micro_cents"` // SQS cost
S3CostMicroCents int64 `theorydb:"attr:s3CostMicroCents" json:"s3_cost_micro_cents"` // S3 operations cost
CloudWatchCostMicroCents int64 `theorydb:"attr:cloudWatchCostMicroCents" json:"cloudwatch_cost_micro_cents"` // CloudWatch logs cost
DataTransferCostMicroCents int64 `theorydb:"attr:dataTransferCostMicroCents" json:"data_transfer_cost_micro_cents"` // Data transfer cost
ExternalAPICostMicroCents int64 `theorydb:"attr:externalAPICostMicroCents" json:"external_api_cost_micro_cents"` // External API costs
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost
// Cost in dollars for display
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
// Job-specific metrics and properties
ItemsProcessed int64 `theorydb:"attr:itemsProcessed" json:"items_processed"` // Number of items/records processed
ItemsSkipped int64 `theorydb:"attr:itemsSkipped" json:"items_skipped"` // Items skipped due to conditions
ItemsErrored int64 `theorydb:"attr:itemsErrored" json:"items_errored"` // Items that failed processing
BatchSize int `theorydb:"attr:batchSize" json:"batch_size"` // Batch size used
JobProperties map[string]interface{} `theorydb:"attr:jobProperties" json:"job_properties,omitempty"` // Job-specific properties
PerformanceMetrics map[string]float64 `theorydb:"attr:performanceMetrics" json:"performance_metrics,omitempty"` // Performance indicators
// Cascading costs (costs triggered by this job)
TriggeredJobs []string `theorydb:"attr:triggeredJobs" json:"triggered_jobs,omitempty"` // Jobs triggered by this execution
CascadingCostMicroCents int64 `theorydb:"attr:cascadingCostMicroCents" json:"cascading_cost_micro_cents"` // Cost of triggered operations
DownstreamOperations int64 `theorydb:"attr:downstreamOperations" json:"downstream_operations"` // Operations triggered downstream
// Job context and metadata
Environment string `theorydb:"attr:environment" json:"environment"` // "production", "staging", etc.
Region string `theorydb:"attr:region" json:"region"` // AWS region
FunctionName string `theorydb:"attr:functionName" json:"function_name"` // Lambda function name
RequestID string `theorydb:"attr:requestID" json:"request_id"` // AWS request ID
Tags map[string]string `theorydb:"attr:tags" json:"tags,omitempty"` // Custom tags
JobCategory string `theorydb:"attr:jobCategory" json:"job_category"` // "maintenance", "aggregation", "cleanup", etc.
Priority string `theorydb:"attr:priority" json:"priority"` // "low", "normal", "high", "critical"
// Scheduling context
ScheduledTime time.Time `theorydb:"attr:scheduledTime" json:"scheduled_time"` // When job was scheduled to run
ActualStartDelay int64 `theorydb:"attr:actualStartDelay" json:"actual_start_delay"` // Delay between scheduled and actual start (ms)
NextScheduledTime time.Time `theorydb:"attr:nextScheduledTime" json:"next_scheduled_time"` // Next scheduled execution
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (90 days for job execution records)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
ScheduledJobCostRecord represents detailed cost tracking for scheduled/cron jobs
func (*ScheduledJobCostRecord) AddTag ¶
func (sjcr *ScheduledJobCostRecord) AddTag(key, value string)
AddTag adds a tag to the scheduled job cost record
func (*ScheduledJobCostRecord) BeforeCreate ¶
func (sjcr *ScheduledJobCostRecord) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*ScheduledJobCostRecord) BeforeUpdate ¶
func (sjcr *ScheduledJobCostRecord) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*ScheduledJobCostRecord) GetJobProperty ¶
func (sjcr *ScheduledJobCostRecord) GetJobProperty(key string) (interface{}, bool)
GetJobProperty gets a job-specific property
func (*ScheduledJobCostRecord) GetPK ¶
func (sjcr *ScheduledJobCostRecord) GetPK() string
GetPK returns the partition key for ScheduledJobCostRecord
func (*ScheduledJobCostRecord) GetPerformanceMetric ¶
func (sjcr *ScheduledJobCostRecord) GetPerformanceMetric(key string) (float64, bool)
GetPerformanceMetric gets a performance metric
func (*ScheduledJobCostRecord) GetSK ¶
func (sjcr *ScheduledJobCostRecord) GetSK() string
GetSK returns the sort key for ScheduledJobCostRecord
func (*ScheduledJobCostRecord) SetJobProperty ¶
func (sjcr *ScheduledJobCostRecord) SetJobProperty(key string, value interface{})
SetJobProperty sets a job-specific property
func (*ScheduledJobCostRecord) SetPerformanceMetric ¶
func (sjcr *ScheduledJobCostRecord) SetPerformanceMetric(key string, value float64)
SetPerformanceMetric sets a performance metric
func (ScheduledJobCostRecord) TableName ¶
func (ScheduledJobCostRecord) TableName() string
TableName returns the DynamoDB table backing ScheduledJobCostRecord.
func (*ScheduledJobCostRecord) UpdateKeys ¶
func (sjcr *ScheduledJobCostRecord) UpdateKeys() error
UpdateKeys updates the keys - implementation already exists in BeforeCreate/BeforeUpdate
func (*ScheduledJobCostRecord) Validate ¶
func (sjcr *ScheduledJobCostRecord) Validate() error
Validate performs validation on the ScheduledJobCostRecord
type ScheduledJobCostRecordBuilder ¶
type ScheduledJobCostRecordBuilder struct {
// contains filtered or unexported fields
}
ScheduledJobCostRecordBuilder helps create scheduled job cost tracking records
func NewScheduledJobCostRecordBuilder ¶
func NewScheduledJobCostRecordBuilder() *ScheduledJobCostRecordBuilder
NewScheduledJobCostRecordBuilder creates a new builder
func (*ScheduledJobCostRecordBuilder) Build ¶
func (builder *ScheduledJobCostRecordBuilder) Build() *ScheduledJobCostRecord
Build creates the scheduled job cost record
func (*ScheduledJobCostRecordBuilder) ForJob ¶
func (builder *ScheduledJobCostRecordBuilder) ForJob(jobName, schedule string) *ScheduledJobCostRecordBuilder
ForJob sets the job name and schedule
func (ScheduledJobCostRecordBuilder) TableName ¶
func (ScheduledJobCostRecordBuilder) TableName() string
TableName returns the DynamoDB table backing ScheduledJobCostRecordBuilder.
func (*ScheduledJobCostRecordBuilder) WithCascadingCosts ¶
func (builder *ScheduledJobCostRecordBuilder) WithCascadingCosts(triggeredJobs []string, cascadingCost int64, downstreamOps int64) *ScheduledJobCostRecordBuilder
WithCascadingCosts sets cascading cost information
func (*ScheduledJobCostRecordBuilder) WithCategory ¶
func (builder *ScheduledJobCostRecordBuilder) WithCategory(category, priority string) *ScheduledJobCostRecordBuilder
WithCategory sets job category and priority
func (*ScheduledJobCostRecordBuilder) WithContext ¶
func (builder *ScheduledJobCostRecordBuilder) WithContext(environment, region, functionName, requestID string) *ScheduledJobCostRecordBuilder
WithContext sets execution context
func (*ScheduledJobCostRecordBuilder) WithCosts ¶
func (builder *ScheduledJobCostRecordBuilder) WithCosts(lambdaCost, dynamoDBCost, sqsCost, s3Cost, cloudWatchCost, dataTransferCost, externalAPICost int64) *ScheduledJobCostRecordBuilder
WithCosts sets the cost breakdown in microcents
func (*ScheduledJobCostRecordBuilder) WithDynamoDBUsage ¶
func (builder *ScheduledJobCostRecordBuilder) WithDynamoDBUsage(readOps, writeOps int64, readCapacity, writeCapacity float64) *ScheduledJobCostRecordBuilder
WithDynamoDBUsage sets DynamoDB resource usage
func (*ScheduledJobCostRecordBuilder) WithError ¶
func (builder *ScheduledJobCostRecordBuilder) WithError(errorMessage string, retryCount, maxRetries int) *ScheduledJobCostRecordBuilder
WithError sets error information
func (*ScheduledJobCostRecordBuilder) WithItemsProcessed ¶
func (builder *ScheduledJobCostRecordBuilder) WithItemsProcessed(processed, skipped, errored int64) *ScheduledJobCostRecordBuilder
WithItemsProcessed sets the items processing metrics
func (*ScheduledJobCostRecordBuilder) WithJobProperty ¶
func (builder *ScheduledJobCostRecordBuilder) WithJobProperty(key string, value interface{}) *ScheduledJobCostRecordBuilder
WithJobProperty sets a job property
func (*ScheduledJobCostRecordBuilder) WithLambdaUsage ¶
func (builder *ScheduledJobCostRecordBuilder) WithLambdaUsage(invocations, durationMs int64, memoryMB int) *ScheduledJobCostRecordBuilder
WithLambdaUsage sets Lambda resource usage
func (*ScheduledJobCostRecordBuilder) WithPerformanceMetric ¶
func (builder *ScheduledJobCostRecordBuilder) WithPerformanceMetric(key string, value float64) *ScheduledJobCostRecordBuilder
WithPerformanceMetric sets a performance metric
func (*ScheduledJobCostRecordBuilder) WithStatus ¶
func (builder *ScheduledJobCostRecordBuilder) WithStatus(status string) *ScheduledJobCostRecordBuilder
WithStatus sets the execution status
func (*ScheduledJobCostRecordBuilder) WithTag ¶
func (builder *ScheduledJobCostRecordBuilder) WithTag(key, value string) *ScheduledJobCostRecordBuilder
WithTag adds a tag
func (*ScheduledJobCostRecordBuilder) WithTiming ¶
func (builder *ScheduledJobCostRecordBuilder) WithTiming(scheduledTime, startTime, endTime time.Time) *ScheduledJobCostRecordBuilder
WithTiming sets the execution timing
type ScheduledJobEnvironmentStats ¶
type ScheduledJobEnvironmentStats struct {
Environment string `theorydb:"attr:environment" json:"environment"`
ExecutionCount int64 `theorydb:"attr:executionCount" json:"execution_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerExecution float64 `theorydb:"attr:averageCostPerExecution" json:"average_cost_per_execution"`
// contains filtered or unexported fields
}
ScheduledJobEnvironmentStats represents cost statistics for an environment
func (ScheduledJobEnvironmentStats) TableName ¶
func (ScheduledJobEnvironmentStats) TableName() string
TableName returns the DynamoDB table backing ScheduledJobEnvironmentStats.
type ScheduledJobScheduleStats ¶
type ScheduledJobScheduleStats struct {
Schedule string `theorydb:"attr:schedule" json:"schedule"`
ExecutionCount int64 `theorydb:"attr:executionCount" json:"execution_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerExecution float64 `theorydb:"attr:averageCostPerExecution" json:"average_cost_per_execution"`
AverageExecutionTime float64 `theorydb:"attr:averageExecutionTime" json:"average_execution_time"`
// contains filtered or unexported fields
}
ScheduledJobScheduleStats represents cost statistics for a schedule pattern
func (ScheduledJobScheduleStats) TableName ¶
func (ScheduledJobScheduleStats) TableName() string
TableName returns the DynamoDB table backing ScheduledJobScheduleStats.
type ScheduledStatus ¶
type ScheduledStatus struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"` // USER#{username}#SCHEDULED
SK string `theorydb:"sk,attr:SK"` // ID#{id}
// GSI1 keys for time-based queries (due status queries)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // SCHEDULED#DUE
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // TIME#{scheduled_at_RFC3339Nano}#ID#{id}
// Business fields - embedded from storage.ScheduledStatus
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"` // Who scheduled the status
Status string `theorydb:"attr:status" json:"status"` // The status content
MediaIDs []string `theorydb:"attr:mediaIDs" json:"media_ids,omitempty"`
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"`
SpoilerText string `theorydb:"attr:spoilerText" json:"spoiler_text,omitempty"`
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Language string `theorydb:"attr:language" json:"language,omitempty"`
InReplyToID string `theorydb:"attr:inReplyToID" json:"in_reply_to_id,omitempty"`
Poll map[string]any `theorydb:"attr:poll" json:"poll,omitempty"` // Poll data if any
ScheduledAt time.Time `theorydb:"attr:scheduledAt" json:"scheduled_at"` // When to publish
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Published bool `theorydb:"attr:published" json:"published"` // Whether it has been published
PublishedAt *time.Time `theorydb:"attr:publishedAt" json:"published_at,omitempty"`
ApplicationID string `theorydb:"attr:applicationID" json:"application_id,omitempty"` // OAuth app that created it
// contains filtered or unexported fields
}
ScheduledStatus represents a scheduled status post in DynamoDB
func (*ScheduledStatus) GetPK ¶
func (s *ScheduledStatus) GetPK() string
GetPK returns the partition key
func (ScheduledStatus) TableName ¶
func (ScheduledStatus) TableName() string
TableName returns the DynamoDB table backing ScheduledStatus.
func (*ScheduledStatus) UpdateKeys ¶
func (s *ScheduledStatus) UpdateKeys() error
UpdateKeys updates the DynamoDB keys based on the current field values
type SearchAnalytics ¶
type SearchAnalytics struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
Query string `theorydb:"attr:query" json:"query"`
ResultCount int `theorydb:"attr:resultCount" json:"result_count"`
SearchTime int64 `theorydb:"attr:searchTime" json:"search_time"` // milliseconds
UserID *string `theorydb:"attr:userID" json:"user_id,omitempty"` // optional
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
ClickedResult *string `theorydb:"attr:clickedResult" json:"clicked_result,omitempty"` // optional
SearchType string `theorydb:"attr:searchType" json:"search_type"` // accounts, statuses, hashtags
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 90 days expiration
// contains filtered or unexported fields
}
SearchAnalytics represents search event analytics
func (SearchAnalytics) TableName ¶
func (SearchAnalytics) TableName() string
TableName returns the DynamoDB table backing SearchAnalytics.
func (*SearchAnalytics) UpdateKeys ¶
func (s *SearchAnalytics) UpdateKeys()
UpdateKeys updates the partition and sort keys based on the model's attributes
type SearchBudget ¶
type SearchBudget struct {
PK string `theorydb:"pk,attr:PK"` // SEARCH_BUDGET#user_id
SK string `theorydb:"sk,attr:SK"` // PERIOD#date_period
Type string `theorydb:"attr:type" json:"type"` // Always "SearchBudget"
// Budget identifiers
UserID string `theorydb:"attr:userID" json:"user_id"`
Period string `theorydb:"attr:period" json:"period"` // daily, monthly, yearly
PeriodDate string `theorydb:"attr:periodDate" json:"period_date"` // 2024-01-15, 2024-01, 2024
// Budget limits (in microcents)
BudgetLimitMicros int64 `theorydb:"attr:budgetLimitMicros" json:"budget_limit_micros"` // Total budget limit
SearchBudgetMicros int64 `theorydb:"attr:searchBudgetMicros" json:"search_budget_micros"` // Budget for regular search
SemanticBudgetMicros int64 `theorydb:"attr:semanticBudgetMicros" json:"semantic_budget_micros"` // Budget for semantic search
IndexingBudgetMicros int64 `theorydb:"attr:indexingBudgetMicros" json:"indexing_budget_micros"` // Budget for search indexing
// Current usage (in microcents)
UsedBudgetMicros int64 `theorydb:"attr:usedBudgetMicros" json:"used_budget_micros"` // Total used budget
SearchUsedMicros int64 `theorydb:"attr:searchUsedMicros" json:"search_used_micros"` // Used for regular search
SemanticUsedMicros int64 `theorydb:"attr:semanticUsedMicros" json:"semantic_used_micros"` // Used for semantic search
IndexingUsedMicros int64 `theorydb:"attr:indexingUsedMicros" json:"indexing_used_micros"` // Used for indexing
// Request limits
MaxRequestsPerHour int `theorydb:"attr:maxRequestsPerHour" json:"max_requests_per_hour"` // Max search requests per hour
MaxSemanticPerHour int `theorydb:"attr:maxSemanticPerHour" json:"max_semantic_per_hour"` // Max semantic searches per hour
CurrentRequests int `theorydb:"attr:currentRequests" json:"current_requests"` // Current requests in period
CurrentSemanticRequests int `theorydb:"attr:currentSemanticRequests" json:"current_semantic_requests"` // Current semantic requests
// Budget status
BudgetExceeded bool `theorydb:"attr:budgetExceeded" json:"budget_exceeded"` // Whether budget is exceeded
LastResetTime time.Time `theorydb:"attr:lastResetTime" json:"last_reset_time"` // When budget was last reset
LastUsageTime time.Time `theorydb:"attr:lastUsageTime" json:"last_usage_time"` // When budget was last used
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl"`
// contains filtered or unexported fields
}
SearchBudget tracks search budgets and limits per user
func (*SearchBudget) CanMakeRequest ¶
func (sb *SearchBudget) CanMakeRequest(operationType string, estimatedCostMicros int64) bool
CanMakeRequest checks if user can make a search request within budget
func (*SearchBudget) RecordUsage ¶
func (sb *SearchBudget) RecordUsage(operationType string, costMicros int64)
RecordUsage records usage against the budget
func (SearchBudget) TableName ¶
func (SearchBudget) TableName() string
TableName returns the DynamoDB table backing SearchBudget.
func (*SearchBudget) UpdateKeys ¶
func (sb *SearchBudget) UpdateKeys() error
UpdateKeys sets the composite keys for search budget tracking
type SearchCache ¶
type SearchCache struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
Query string `theorydb:"attr:query" json:"query"` // original query
Results map[string]interface{} `theorydb:"attr:results" json:"results"` // cached search results
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // Unix timestamp
// contains filtered or unexported fields
}
SearchCache represents cached search results
func NewSearchCache ¶
func NewSearchCache(query string) *SearchCache
NewSearchCache creates a new search cache entry
func (*SearchCache) InvalidateCache ¶
func (s *SearchCache) InvalidateCache(reason string)
InvalidateCache marks the cache as invalid by adding invalidation reason
func (*SearchCache) IsValid ¶
func (s *SearchCache) IsValid() bool
IsValid checks if the cache entry is still valid
func (SearchCache) TableName ¶
func (SearchCache) TableName() string
TableName returns the DynamoDB table backing SearchCache.
func (*SearchCache) UpdateKeys ¶
func (s *SearchCache) UpdateKeys()
UpdateKeys updates the partition and sort keys based on the model's attributes
type SearchClickRate ¶
type SearchClickRate struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
Query string `theorydb:"attr:query" json:"query"`
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
ClickCount int `theorydb:"attr:clickCount" json:"click_count"`
LastClicked time.Time `theorydb:"attr:lastClicked" json:"last_clicked"`
// contains filtered or unexported fields
}
SearchClickRate represents click-through rate tracking for search results
func (SearchClickRate) TableName ¶
func (SearchClickRate) TableName() string
TableName returns the DynamoDB table backing SearchClickRate.
func (*SearchClickRate) UpdateKeys ¶
func (c *SearchClickRate) UpdateKeys()
UpdateKeys updates the partition and sort keys based on the model's attributes
type SearchCostAggregation ¶
type SearchCostAggregation struct {
PK string `theorydb:"pk"` // SEARCH_AGG#date#aggregation_type
SK string `theorydb:"sk"` // METRIC#metric_name
Type string `json:"type"` // Always "SearchCostAggregation"
// Aggregation identifiers
Date string `json:"date"` // 2024-01-15
AggregationType string `json:"aggregation_type"` // daily, hourly, user, operation_type
MetricName string `json:"metric_name"` // total_cost, avg_cost_per_search, etc.
// Aggregated metrics
TotalCostMicros int64 `json:"total_cost_micros"`
TotalRequests int64 `json:"total_requests"`
AverageCostMicros int64 `json:"average_cost_micros"`
MedianResponseTimeMs int64 `json:"median_response_time_ms"`
CacheHitRate float64 `json:"cache_hit_rate"`
// Operation breakdown
TextSearches int64 `json:"text_searches"`
HashtagSearches int64 `json:"hashtag_searches"`
UserSearches int64 `json:"user_searches"`
SemanticSearches int64 `json:"semantic_searches"`
SuggestionRequests int64 `json:"suggestion_requests"`
IndexingOperations int64 `json:"indexing_operations"`
// Cost breakdown
DynamoCostMicros int64 `json:"dynamo_cost_micros"`
BedrockCostMicros int64 `json:"bedrock_cost_micros"`
LambdaCostMicros int64 `json:"lambda_cost_micros"`
// Performance metrics
AverageResponseTimeMs int64 `json:"average_response_time_ms"`
P95ResponseTimeMs int64 `json:"p95_response_time_ms"`
AverageResultCount int `json:"average_result_count"`
// Timestamps
StartTime time.Time `json:"start_time"`
EndTime time.Time `json:"end_time"`
GeneratedAt time.Time `json:"generated_at"`
// TTL for cleanup
TTL int64 `theorydb:"ttl"`
}
SearchCostAggregation provides aggregated cost data for reporting
func (*SearchCostAggregation) GetPK ¶
func (sca *SearchCostAggregation) GetPK() string
GetPK returns the partition key
func (*SearchCostAggregation) GetSK ¶
func (sca *SearchCostAggregation) GetSK() string
GetSK returns the sort key
func (SearchCostAggregation) TableName ¶
func (SearchCostAggregation) TableName() string
TableName returns the DynamoDB table backing SearchCostAggregation.
func (*SearchCostAggregation) UpdateKeys ¶
func (sca *SearchCostAggregation) UpdateKeys() error
UpdateKeys sets the composite keys for search cost aggregation
type SearchCostTracking ¶
type SearchCostTracking struct {
PK string `theorydb:"pk,attr:PK"` // SEARCH_COST#date#user_id
SK string `theorydb:"sk,attr:SK"` // OPERATION#timestamp#operation_type
Type string `theorydb:"attr:type" json:"type"` // Always "SearchCostTracking"
// Core identifiers
UserID string `theorydb:"attr:userID" json:"user_id"`
RequestID string `theorydb:"attr:requestID" json:"request_id"`
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // text_search, hashtag_search, user_search, semantic_search, search_suggestions, search_indexing
// Search-specific details
Query string `theorydb:"attr:query" json:"query"`
SearchType string `theorydb:"attr:searchType" json:"search_type"` // accounts, statuses, hashtags, all, suggestions, semantic
ResultCount int `theorydb:"attr:resultCount" json:"result_count"` // Number of results returned
QueryLength int `theorydb:"attr:queryLength" json:"query_length"` // Length of search query
CacheHit bool `theorydb:"attr:cacheHit" json:"cache_hit"` // Whether result was cached
QueryComplexity float64 `theorydb:"attr:queryComplexity" json:"query_complexity"` // Complexity score for the query
// DynamoDB costs
DynamoReads int64 `theorydb:"attr:dynamoReads" json:"dynamo_reads"` // Read capacity units consumed
DynamoWrites int64 `theorydb:"attr:dynamoWrites" json:"dynamo_writes"` // Write capacity units consumed
DynamoQueries int `theorydb:"attr:dynamoQueries" json:"dynamo_queries"` // Number of DynamoDB queries executed
GSIQueries int `theorydb:"attr:gsiQueries" json:"gsi_queries"` // Number of GSI queries executed
ScanOperations int `theorydb:"attr:scanOperations" json:"scan_operations"` // Number of scan operations
// Bedrock/AI costs (for semantic search)
BedrockRequests int `theorydb:"attr:bedrockRequests" json:"bedrock_requests"` // Number of Bedrock API calls
EmbeddingTokens int `theorydb:"attr:embeddingTokens" json:"embedding_tokens"` // Tokens used for embedding generation
EmbeddingDimension int `theorydb:"attr:embeddingDimension" json:"embedding_dimension"` // Dimension of embeddings
VectorComparisons int `theorydb:"attr:vectorComparisons" json:"vector_comparisons"` // Number of vector similarity comparisons
BedrockCostMicros int64 `theorydb:"attr:bedrockCostMicros" json:"bedrock_cost_micros"` // Bedrock cost in microcents
// Lambda execution costs
LambdaDurationMs int64 `theorydb:"attr:lambdaDurationMs" json:"lambda_duration_ms"` // Lambda execution time
LambdaMemoryMB int64 `theorydb:"attr:lambdaMemoryMB" json:"lambda_memory_mb"` // Lambda memory allocation
// Search performance metrics
ResponseTimeMs int64 `theorydb:"attr:responseTimeMs" json:"response_time_ms"` // Total response time
IndexLookupTimeMs int64 `theorydb:"attr:indexLookupTimeMs" json:"index_lookup_time_ms"` // Time spent on index lookups
FilteringTimeMs int64 `theorydb:"attr:filteringTimeMs" json:"filtering_time_ms"` // Time spent filtering results
RankingTimeMs int64 `theorydb:"attr:rankingTimeMs" json:"ranking_time_ms"` // Time spent ranking/sorting results
// Cost calculations
TotalCostMicros int64 `theorydb:"attr:totalCostMicros" json:"total_cost_micros"` // Total cost in microcents
DynamoCostMicros int64 `theorydb:"attr:dynamoCostMicros" json:"dynamo_cost_micros"` // DynamoDB cost in microcents
LambdaCostMicros int64 `theorydb:"attr:lambdaCostMicros" json:"lambda_cost_micros"` // Lambda cost in microcents
CostPerResult int64 `theorydb:"attr:costPerResult" json:"cost_per_result"` // Cost per result in microcents
EstimatedSavings int64 `theorydb:"attr:estimatedSavings" json:"estimated_savings"` // Savings from caching in microcents
// Timestamps
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD for aggregation
// TTL for cleanup
TTL int64 `theorydb:"ttl,attr:ttl"`
// contains filtered or unexported fields
}
SearchCostTracking tracks costs for search operations
func (*SearchCostTracking) GetPK ¶
func (sct *SearchCostTracking) GetPK() string
GetPK returns the partition key
func (*SearchCostTracking) GetSK ¶
func (sct *SearchCostTracking) GetSK() string
GetSK returns the sort key
func (SearchCostTracking) TableName ¶
func (SearchCostTracking) TableName() string
TableName returns the DynamoDB table backing SearchCostTracking.
func (*SearchCostTracking) UpdateKeys ¶
func (sct *SearchCostTracking) UpdateKeys() error
UpdateKeys sets the composite keys for search cost tracking
type SearchEmbedding ¶
type SearchEmbedding struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
ContentID string `theorydb:"attr:contentID" json:"content_id"` // status/actor ID
ContentType string `theorydb:"attr:contentType" json:"content_type"` // actor, status
Embedding []float32 `theorydb:"attr:embedding" json:"embedding"` // vector representation
Score float64 `theorydb:"attr:score" json:"score"`
Metadata map[string]string `theorydb:"attr:metadata" json:"metadata,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
SearchEmbedding represents vector embeddings for semantic search
func (*SearchEmbedding) GetPK ¶
func (s *SearchEmbedding) GetPK() string
GetPK returns the partition key
func (SearchEmbedding) TableName ¶
func (SearchEmbedding) TableName() string
TableName returns the DynamoDB table backing SearchEmbedding.
func (*SearchEmbedding) UpdateKeys ¶
func (s *SearchEmbedding) UpdateKeys() error
UpdateKeys updates the partition and sort keys based on the model's attributes
type SearchHistoryEntry ¶
type SearchHistoryEntry struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Query string `theorydb:"attr:query" json:"query"`
ResultCount int `theorydb:"attr:resultCount" json:"result_count"`
ClickedIDs []string `theorydb:"attr:clickedIDs" json:"clicked_ids"` // IDs of results user clicked
SearchedAt time.Time `theorydb:"attr:searchedAt" json:"searched_at"`
// contains filtered or unexported fields
}
SearchHistoryEntry represents a user's search history entry Stored in DynamoDB with pattern: PK: USER#username SK: SEARCH_HISTORY#{timestamp}#{queryHash}
func NewSearchHistoryEntry ¶
func NewSearchHistoryEntry(userID, query string, resultCount int) *SearchHistoryEntry
NewSearchHistoryEntry creates a new search history entry
func (*SearchHistoryEntry) AddClickedID ¶
func (s *SearchHistoryEntry) AddClickedID(id string)
AddClickedID adds a clicked result ID to the history
func (*SearchHistoryEntry) GetClickRate ¶
func (s *SearchHistoryEntry) GetClickRate() float64
GetClickRate returns the click-through rate for this search
func (*SearchHistoryEntry) IsRecent ¶
func (s *SearchHistoryEntry) IsRecent(duration time.Duration) bool
IsRecent returns true if the search was performed within the specified duration
func (SearchHistoryEntry) TableName ¶
func (SearchHistoryEntry) TableName() string
TableName returns the DynamoDB table backing SearchHistoryEntry.
func (*SearchHistoryEntry) UpdateKeys ¶
func (s *SearchHistoryEntry) UpdateKeys()
UpdateKeys updates the DynamoDB keys based on the entry data
type SearchQuery ¶
type SearchQuery struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Query string `theorydb:"attr:query" json:"query"`
UserID string `theorydb:"attr:userID" json:"user_id"`
ResultCount int `theorydb:"attr:resultCount" json:"result_count"`
SearchedAt time.Time `theorydb:"attr:searchedAt" json:"searched_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
SearchQuery represents a search query for analytics
func (*SearchQuery) GetPK ¶
func (s *SearchQuery) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*SearchQuery) GetSK ¶
func (s *SearchQuery) GetSK() string
GetSK returns the sort key for BaseModel interface
func (SearchQuery) TableName ¶
func (SearchQuery) TableName() string
TableName returns the DynamoDB table backing SearchQuery.
func (*SearchQuery) UpdateKeys ¶
func (s *SearchQuery) UpdateKeys() error
UpdateKeys updates the GSI keys for search query
type SearchQueryStats ¶
type SearchQueryStats struct {
PK string `theorydb:"pk"` // SEARCH_STATS#query_hash
SK string `theorydb:"sk"` // STATS#period
Type string `json:"type"` // Always "SearchQueryStats"
// Query identifiers
QueryHash string `json:"query_hash"` // Hash of the query for privacy
QueryType string `json:"query_type"` // text, hashtag, user, semantic
QueryLength int `json:"query_length"` // Length of original query
Period string `json:"period"` // daily, weekly, monthly
// Usage statistics
QueryCount int64 `json:"query_count"` // Number of times queried
UniqueUsers int `json:"unique_users"` // Number of unique users
TotalResultCount int64 `json:"total_result_count"` // Total results returned
AverageResults float64 `json:"average_results"` // Average results per query
CacheHitCount int64 `json:"cache_hit_count"` // Number of cache hits
CacheHitRate float64 `json:"cache_hit_rate"` // Cache hit percentage
// Performance statistics
TotalResponseTimeMs int64 `json:"total_response_time_ms"` // Total response time
AverageResponseTimeMs float64 `json:"average_response_time_ms"` // Average response time
MinResponseTimeMs int64 `json:"min_response_time_ms"` // Minimum response time
MaxResponseTimeMs int64 `json:"max_response_time_ms"` // Maximum response time
// Cost statistics
TotalCostMicros int64 `json:"total_cost_micros"` // Total cost for this query
AverageCostMicros float64 `json:"average_cost_micros"` // Average cost per execution
CostEfficiency float64 `json:"cost_efficiency"` // Cost per result ratio
// Timestamps
FirstQueried time.Time `json:"first_queried"`
LastQueried time.Time `json:"last_queried"`
UpdatedAt time.Time `json:"updated_at"`
// TTL for cleanup
TTL int64 `theorydb:"ttl"`
}
SearchQueryStats tracks statistics for specific search queries
func (*SearchQueryStats) GetPK ¶
func (sqs *SearchQueryStats) GetPK() string
GetPK returns the partition key
func (*SearchQueryStats) GetSK ¶
func (sqs *SearchQueryStats) GetSK() string
GetSK returns the sort key
func (SearchQueryStats) TableName ¶
func (SearchQueryStats) TableName() string
TableName returns the DynamoDB table backing SearchQueryStats.
func (*SearchQueryStats) UpdateKeys ¶
func (sqs *SearchQueryStats) UpdateKeys() error
UpdateKeys sets the composite keys for search query stats
type SearchResults ¶
type SearchResults struct {
Accounts []*activitypub.Actor `json:"accounts"`
Statuses []*StatusSearchResult `json:"statuses"`
}
SearchResults combines all search result types This is a composite response type, not stored in DynamoDB
func NewSearchResults ¶
func NewSearchResults() *SearchResults
NewSearchResults creates a new empty search results container
func (*SearchResults) AddAccount ¶
func (s *SearchResults) AddAccount(account *activitypub.Actor)
AddAccount adds an account to the search results
func (*SearchResults) AddHashtag ¶
func (s *SearchResults) AddHashtag(hashtag *HashtagSearchResult)
AddHashtag adds a hashtag to the search results
func (*SearchResults) AddStatus ¶
func (s *SearchResults) AddStatus(status *StatusSearchResult)
AddStatus adds a status to the search results
func (*SearchResults) Count ¶
func (s *SearchResults) Count() int
Count returns the total number of results across all types
func (*SearchResults) IsEmpty ¶
func (s *SearchResults) IsEmpty() bool
IsEmpty returns true if there are no results of any type
func (*SearchResults) Merge ¶
func (s *SearchResults) Merge(other *SearchResults)
Merge combines another SearchResults into this one
func (SearchResults) TableName ¶
func (SearchResults) TableName() string
TableName returns the DynamoDB table backing SearchResults.
func (*SearchResults) TruncateToLimit ¶
func (s *SearchResults) TruncateToLimit(limit int)
TruncateToLimit ensures no category exceeds the specified limit
type SearchSuggestion ¶
type SearchSuggestion struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Fields
Type string `theorydb:"attr:type" json:"type"` // hashtag, account, username, display_name
Term string `theorydb:"attr:term" json:"term"` // the search term
Score float64 `theorydb:"attr:score" json:"score"` // popularity/relevance score
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"`
UseCount int `theorydb:"attr:useCount" json:"use_count"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
SearchSuggestion represents search autocomplete suggestions
func (*SearchSuggestion) GetPK ¶
func (s *SearchSuggestion) GetPK() string
GetPK returns the partition key
func (*SearchSuggestion) GetSK ¶
func (s *SearchSuggestion) GetSK() string
GetSK returns the sort key
func (SearchSuggestion) TableName ¶
func (SearchSuggestion) TableName() string
TableName returns the DynamoDB table backing SearchSuggestion.
func (*SearchSuggestion) UpdateKeys ¶
func (s *SearchSuggestion) UpdateKeys() error
UpdateKeys updates the partition and sort keys based on the model's attributes
type Series ¶
type Series struct {
PK string `theorydb:"pk,attr:PK"` // AUTHOR#{author_id}#SERIES
SK string `theorydb:"sk,attr:SK"` // ID#{series_id}
ID string `theorydb:"attr:id" json:"id"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Tenant string `theorydb:"attr:tenant,omitempty" json:"tenant,omitempty"`
Title string `theorydb:"attr:title" json:"title"`
Description string `theorydb:"attr:description" json:"description,omitempty"`
Slug string `theorydb:"attr:slug" json:"slug"`
CoverImage string `theorydb:"attr:coverImage" json:"cover_image,omitempty"`
// Status
IsComplete bool `theorydb:"attr:isComplete" json:"is_complete"`
ArticleCount int `theorydb:"attr:articleCount" json:"article_count"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
}
Series represents a multi-part content series
func (*Series) UpdateKeys ¶
UpdateKeys updates the keys for the Series model
type Session ¶
type Session struct {
// Primary key - using session ID as partition key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "session#{sessionID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "session#{sessionID}" (same as PK for simple key)
// GSI1 - User sessions lookup
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USER_SESSIONS#{userID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{created_at}#{sessionID}"
// GSI2 - Access token lookup
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "TOKEN#{access_token_hash}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "{userID}"
// Core session data
SessionID string `theorydb:"attr:sessionID" json:"session_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
AccessToken string `theorydb:"attr:accessToken" json:"access_token"` // Stored encrypted
RefreshToken string `theorydb:"attr:refreshToken" json:"refresh_token,omitempty"` // Stored encrypted
Scopes []string `theorydb:"attr:scopes" json:"scopes,omitempty"`
// Session metadata
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
DeviceID string `theorydb:"attr:deviceID" json:"device_id,omitempty"`
// Security and tracking
IsRevoked bool `theorydb:"attr:isRevoked" json:"is_revoked"`
RevokedAt *time.Time `theorydb:"attr:revokedAt" json:"revoked_at,omitempty"`
RevokeReason string `theorydb:"attr:revokeReason" json:"revoke_reason,omitempty"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
LastUsedAt time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at"`
// TTL for automatic cleanup
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp for DynamoDB TTL
// Additional context data
Context map[string]interface{} `theorydb:"attr:context" json:"context,omitempty"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Session represents a user session with OAuth tokens
func (*Session) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Session) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Session) GetContext ¶
GetContext gets a context value
func (*Session) IsValid ¶
IsValid returns true if the session is valid (not revoked and not expired)
func (*Session) RemainingTime ¶
RemainingTime returns the time until the session expires
func (*Session) SetContext ¶
SetContext sets a context value
func (*Session) Touch ¶
func (s *Session) Touch()
Touch updates the last used timestamp and extends expiry if needed
func (*Session) ValidateRequest ¶
ValidateRequest validates the session against request metadata for security
type SetupSession ¶
type SetupSession struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
Purpose string `theorydb:"attr:purpose" json:"purpose"`
WalletType string `theorydb:"attr:walletType" json:"wallet_type"`
WalletAddr string `theorydb:"attr:walletAddress" json:"wallet_address"`
IssuedAt time.Time `theorydb:"attr:issuedAt" json:"issued_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
InstanceLock bool `theorydb:"attr:instanceLocked" json:"instance_locked"`
// contains filtered or unexported fields
}
SetupSession represents a short-lived bearer token used during initial instance setup. Tokens are stored with TTL for automatic cleanup.
func (SetupSession) TableName ¶
func (SetupSession) TableName() string
TableName returns the DynamoDB table backing SetupSession.
func (*SetupSession) UpdateKeys ¶
func (s *SetupSession) UpdateKeys() error
UpdateKeys updates DynamoDB keys and TTL based on the session fields.
type SeveranceReason ¶
type SeveranceReason string
SeveranceReason represents why a federation relationship was severed
const ( // SeveranceReasonDomainBlock represents a blocked severance reason SeveranceReasonDomainBlock SeveranceReason = "DOMAIN_BLOCK" // SeveranceReasonInstanceDown represents an unavailable severance reason SeveranceReasonInstanceDown SeveranceReason = "INSTANCE_DOWN" // SeveranceReasonDefederation represents a defederated severance reason SeveranceReasonDefederation SeveranceReason = "DEFEDERATION" // SeveranceReasonPolicyViolation represents a policy violation severance reason SeveranceReasonPolicyViolation SeveranceReason = "POLICY_VIOLATION" // SeveranceReasonOther represents other severance reasons SeveranceReasonOther SeveranceReason = "OTHER" )
type SeveranceReconnectionAttempt ¶
type SeveranceReconnectionAttempt struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // SEVERED#{severanceID}
SK string `theorydb:"sk,attr:SK" json:"-"` // RECONNECT#{attemptID}
// Fields
ID string `theorydb:"attr:id" json:"id"`
SeveranceID string `theorydb:"attr:severanceID" json:"severance_id"`
InitiatedBy string `theorydb:"attr:initiatedBy" json:"initiated_by"` // User ID who initiated
Status string `theorydb:"attr:status" json:"status"` // "pending", "in_progress", "completed", "failed"
AttemptedAt time.Time `theorydb:"attr:attemptedAt" json:"attempted_at"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
SuccessCount int `theorydb:"attr:successCount" json:"success_count"`
FailureCount int `theorydb:"attr:failureCount" json:"failure_count"`
Notes string `theorydb:"attr:notes" json:"notes,omitempty"`
ErrorMessages []string `theorydb:"attr:errorMessages" json:"error_messages,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for auto-cleanup (90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
SeveranceReconnectionAttempt represents an attempt to restore severed relationships
func NewSeveranceReconnectionAttempt ¶
func NewSeveranceReconnectionAttempt(severanceID, initiatedBy string) *SeveranceReconnectionAttempt
NewSeveranceReconnectionAttempt creates a new reconnection attempt record
func (*SeveranceReconnectionAttempt) GetPK ¶
func (r *SeveranceReconnectionAttempt) GetPK() string
GetPK returns the partition key
func (*SeveranceReconnectionAttempt) GetSK ¶
func (r *SeveranceReconnectionAttempt) GetSK() string
GetSK returns the sort key
func (*SeveranceReconnectionAttempt) MarkCompleted ¶
func (r *SeveranceReconnectionAttempt) MarkCompleted(successCount, failureCount int)
MarkCompleted marks the reconnection attempt as completed
func (*SeveranceReconnectionAttempt) MarkFailed ¶
func (r *SeveranceReconnectionAttempt) MarkFailed(errorMessage string)
MarkFailed marks the reconnection attempt as failed
func (*SeveranceReconnectionAttempt) MarkInProgress ¶
func (r *SeveranceReconnectionAttempt) MarkInProgress()
MarkInProgress marks the reconnection attempt as in progress
func (SeveranceReconnectionAttempt) TableName ¶
func (SeveranceReconnectionAttempt) TableName() string
TableName returns the DynamoDB table backing SeveranceReconnectionAttempt.
func (*SeveranceReconnectionAttempt) UpdateKeys ¶
func (r *SeveranceReconnectionAttempt) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the reconnection attempt
type SeveranceStatus ¶
type SeveranceStatus string
SeveranceStatus represents the status of a severed relationship
const ( // SeveranceStatusActive represents an active severance SeveranceStatusActive SeveranceStatus = "ACTIVE" // SeveranceStatusAcknowledged represents an acknowledged severance SeveranceStatusAcknowledged SeveranceStatus = "ACKNOWLEDGED" // SeveranceStatusRestored represents a restored relationship SeveranceStatusRestored SeveranceStatus = "RESTORED" )
type SeveredRelationship ¶
type SeveredRelationship struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // SEVERED#{localInstance}
SK string `theorydb:"sk,attr:SK" json:"-"` // INSTANCE#{remoteInstance}#{timestamp}
// GSI1 for filtering by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{status}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // TIMESTAMP#{timestamp}
// Fields
ID string `theorydb:"attr:id" json:"id"`
LocalInstance string `theorydb:"attr:localInstance" json:"local_instance"`
RemoteInstance string `theorydb:"attr:remoteInstance" json:"remote_instance"`
Reason SeveranceReason `theorydb:"attr:reason" json:"reason"`
Status SeveranceStatus `theorydb:"attr:status" json:"status"`
Severity string `theorydb:"attr:severity" json:"severity"` // "low", "medium", "high"
AffectedFollowers int `theorydb:"attr:affectedFollowers" json:"affected_followers"`
AffectedFollowing int `theorydb:"attr:affectedFollowing" json:"affected_following"`
DetectedAt time.Time `theorydb:"attr:detectedAt" json:"detected_at"`
AcknowledgedAt *time.Time `theorydb:"attr:acknowledgedAt" json:"acknowledged_at,omitempty"`
Reversible bool `theorydb:"attr:reversible" json:"reversible"`
Details string `theorydb:"attr:details" json:"details,omitempty"`
Metadata map[string]any `theorydb:"attr:metadata" json:"metadata,omitempty"`
AutoDetected bool `theorydb:"attr:autoDetected" json:"auto_detected"`
AdminNotes string `theorydb:"attr:adminNotes" json:"admin_notes,omitempty"`
ReconnectionAttempt bool `theorydb:"attr:reconnectionAttempt" json:"reconnection_attempt"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for auto-cleanup (180 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
SeveredRelationship represents a broken federation relationship
func NewSeveredRelationship ¶
func NewSeveredRelationship(localInstance, remoteInstance string, reason SeveranceReason) *SeveredRelationship
NewSeveredRelationship creates a new severed relationship record
func (*SeveredRelationship) Acknowledge ¶
func (s *SeveredRelationship) Acknowledge()
Acknowledge marks the severance as acknowledged
func (*SeveredRelationship) GetPK ¶
func (s *SeveredRelationship) GetPK() string
GetPK returns the partition key
func (*SeveredRelationship) GetSK ¶
func (s *SeveredRelationship) GetSK() string
GetSK returns the sort key
func (*SeveredRelationship) MarkReconnectionAttempt ¶
func (s *SeveredRelationship) MarkReconnectionAttempt()
MarkReconnectionAttempt marks that a reconnection attempt has been made
func (SeveredRelationship) TableName ¶
func (SeveredRelationship) TableName() string
TableName returns the DynamoDB table backing SeveredRelationship.
func (*SeveredRelationship) UpdateKeys ¶
func (s *SeveredRelationship) UpdateKeys() error
UpdateKeys updates the DynamoDB keys for the severed relationship
type Skill ¶ added in v1.3.2
type Skill struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI1 lists canonical skills by lifecycle status for later approval/catalog APIs.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
// GSI2 lists canonical skills by default exposure class without exposing private content.
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
Slug string `theorydb:"attr:slug" json:"slug"`
Name string `theorydb:"attr:name" json:"name"`
Description string `theorydb:"attr:description,omitempty" json:"description,omitempty"`
Status string `theorydb:"attr:status" json:"status"`
DefaultExposure string `theorydb:"attr:defaultExposure" json:"default_exposure"`
CurrentRevisionID string `theorydb:"attr:currentRevisionID,omitempty" json:"current_revision_id,omitempty"`
CurrentRevisionNumber int `theorydb:"attr:currentRevisionNumber,omitempty" json:"current_revision_number,omitempty"`
Capabilities []string `theorydb:"attr:capabilities" json:"capabilities,omitempty"`
Tags []string `theorydb:"attr:tags" json:"tags,omitempty"`
Provenance []SkillProvenanceRef `theorydb:"attr:provenance" json:"provenance,omitempty"`
CreatedBy string `theorydb:"attr:createdBy,omitempty" json:"created_by,omitempty"`
UpdatedBy string `theorydb:"attr:updatedBy,omitempty" json:"updated_by,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Skill stores canonical instance-owned skill authority metadata.
func (*Skill) BeforeCreate ¶ added in v1.3.2
BeforeCreate normalizes a Skill before insert.
func (*Skill) BeforeUpdate ¶ added in v1.3.2
BeforeUpdate normalizes a Skill before update.
func (*Skill) UpdateKeys ¶ added in v1.3.2
UpdateKeys refreshes Skill primary and secondary keys.
type SkillAssignment ¶ added in v1.3.2
type SkillAssignment struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI1 lists assignments by skill for audit and revocation walks.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
// GSI2 supports sparse status queues for pending/revoked assignment processing.
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
SkillID string `theorydb:"attr:skillID" json:"skill_id"`
RevisionID string `theorydb:"attr:revisionID,omitempty" json:"revision_id,omitempty"`
RevisionNumber int `theorydb:"attr:revisionNumber,omitempty" json:"revision_number,omitempty"`
SubjectType string `theorydb:"attr:subjectType" json:"subject_type"`
SubjectID string `theorydb:"attr:subjectID" json:"subject_id"`
Exposure string `theorydb:"attr:exposure" json:"exposure"`
Status string `theorydb:"attr:status" json:"status"`
ApprovalID string `theorydb:"attr:approvalID,omitempty" json:"approval_id,omitempty"`
PrincipalID string `theorydb:"attr:principalID,omitempty" json:"principal_id,omitempty"`
PrincipalApprovalID string `theorydb:"attr:principalApprovalID,omitempty" json:"principal_approval_id,omitempty"`
Provenance []SkillProvenanceRef `theorydb:"attr:provenance" json:"provenance,omitempty"`
AssignedBy string `theorydb:"attr:assignedBy,omitempty" json:"assigned_by,omitempty"`
AssignedAt time.Time `theorydb:"attr:assignedAt" json:"assigned_at"`
RevokedBy string `theorydb:"attr:revokedBy,omitempty" json:"revoked_by,omitempty"`
RevokedAt *time.Time `theorydb:"attr:revokedAt" json:"revoked_at,omitempty"`
RevokedReason string `theorydb:"attr:revokedReason,omitempty" json:"revoked_reason,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
SkillAssignment stores an explicit skill assignment for effective-resolution APIs added later.
func (*SkillAssignment) BeforeCreate ¶ added in v1.3.2
func (a *SkillAssignment) BeforeCreate() error
BeforeCreate normalizes a SkillAssignment before insert.
func (*SkillAssignment) BeforeUpdate ¶ added in v1.3.2
func (a *SkillAssignment) BeforeUpdate() error
BeforeUpdate normalizes a SkillAssignment before update.
func (*SkillAssignment) GetPK ¶ added in v1.3.2
func (a *SkillAssignment) GetPK() string
GetPK returns the partition key.
func (*SkillAssignment) GetSK ¶ added in v1.3.2
func (a *SkillAssignment) GetSK() string
GetSK returns the sort key.
func (SkillAssignment) TableName ¶ added in v1.3.2
func (SkillAssignment) TableName() string
TableName returns the DynamoDB table backing SkillAssignment.
func (*SkillAssignment) UpdateKeys ¶ added in v1.3.2
func (a *SkillAssignment) UpdateKeys() error
UpdateKeys refreshes SkillAssignment primary and secondary keys.
type SkillProposal ¶ added in v1.3.2
type SkillProposal struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI1 lists proposals for a skill.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
// GSI2 supports later proposal review queues by status.
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
SkillID string `theorydb:"attr:skillID" json:"skill_id"`
Title string `theorydb:"attr:title,omitempty" json:"title,omitempty"`
Summary string `theorydb:"attr:summary,omitempty" json:"summary,omitempty"`
Status string `theorydb:"attr:status" json:"status"`
RequestedExposure string `theorydb:"attr:requestedExposure" json:"requested_exposure"`
ProposedRevisionNumber int `theorydb:"attr:proposedRevisionNumber,omitempty" json:"proposed_revision_number,omitempty"`
ProposedManifestJSON string `theorydb:"attr:proposedManifestJSON,omitempty" json:"proposed_manifest_json,omitempty"`
ProposedManifestDigest string `theorydb:"attr:proposedManifestDigest,omitempty" json:"proposed_manifest_digest,omitempty"`
SourceType string `theorydb:"attr:sourceType,omitempty" json:"source_type,omitempty"`
SourceURI string `theorydb:"attr:sourceURI,omitempty" json:"source_uri,omitempty"`
SourceDigest string `theorydb:"attr:sourceDigest,omitempty" json:"source_digest,omitempty"`
ConversationID string `theorydb:"attr:conversationID,omitempty" json:"conversation_id,omitempty"`
ConversationMessageID string `theorydb:"attr:conversationMessageID,omitempty" json:"conversation_message_id,omitempty"`
PrincipalID string `theorydb:"attr:principalID,omitempty" json:"principal_id,omitempty"`
PrincipalApprovalID string `theorydb:"attr:principalApprovalID,omitempty" json:"principal_approval_id,omitempty"`
PromotedRevisionID string `theorydb:"attr:promotedRevisionID,omitempty" json:"promoted_revision_id,omitempty"`
PromotedRevisionNumber int `theorydb:"attr:promotedRevisionNumber,omitempty" json:"promoted_revision_number,omitempty"`
PromotionDigest string `theorydb:"attr:promotionDigest,omitempty" json:"promotion_digest,omitempty"`
PromotedBy string `theorydb:"attr:promotedBy,omitempty" json:"promoted_by,omitempty"`
PromotedAt *time.Time `theorydb:"attr:promotedAt" json:"promoted_at,omitempty"`
Provenance []SkillProvenanceRef `theorydb:"attr:provenance" json:"provenance,omitempty"`
CreatedBy string `theorydb:"attr:createdBy,omitempty" json:"created_by,omitempty"`
ReviewedBy string `theorydb:"attr:reviewedBy,omitempty" json:"reviewed_by,omitempty"`
ReviewedAt *time.Time `theorydb:"attr:reviewedAt" json:"reviewed_at,omitempty"`
ReviewReason string `theorydb:"attr:reviewReason,omitempty" json:"review_reason,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
SkillProposal stores non-authoritative source material proposed for canonicalization.
func (*SkillProposal) BeforeCreate ¶ added in v1.3.2
func (p *SkillProposal) BeforeCreate() error
BeforeCreate normalizes a SkillProposal before insert.
func (*SkillProposal) BeforeUpdate ¶ added in v1.3.2
func (p *SkillProposal) BeforeUpdate() error
BeforeUpdate normalizes a SkillProposal before update.
func (*SkillProposal) GetPK ¶ added in v1.3.2
func (p *SkillProposal) GetPK() string
GetPK returns the partition key.
func (*SkillProposal) GetSK ¶ added in v1.3.2
func (p *SkillProposal) GetSK() string
GetSK returns the sort key.
func (SkillProposal) TableName ¶ added in v1.3.2
func (SkillProposal) TableName() string
TableName returns the DynamoDB table backing SkillProposal.
func (*SkillProposal) UpdateKeys ¶ added in v1.3.2
func (p *SkillProposal) UpdateKeys() error
UpdateKeys refreshes SkillProposal primary and secondary keys.
type SkillProvenanceRef ¶ added in v1.3.2
type SkillProvenanceRef struct {
SourceType string `theorydb:"attr:sourceType" json:"source_type"`
SourceURI string `theorydb:"attr:sourceURI,omitempty" json:"source_uri,omitempty"`
Digest string `theorydb:"attr:digest,omitempty" json:"digest,omitempty"`
Ref string `theorydb:"attr:ref,omitempty" json:"ref,omitempty"`
Notes string `theorydb:"attr:notes,omitempty" json:"notes,omitempty"`
}
SkillProvenanceRef captures source/provenance for canonical skills, proposals, and revisions.
type SkillRevision ¶ added in v1.3.2
type SkillRevision struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// GSI1 supports later review/effective-resolution queues by revision status.
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
// GSI2 is sparse and supports digest/provenance de-duplication for imported manifests.
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"`
ID string `theorydb:"attr:id" json:"id"`
SkillID string `theorydb:"attr:skillID" json:"skill_id"`
RevisionNumber int `theorydb:"attr:revisionNumber" json:"revision_number"`
Status string `theorydb:"attr:status" json:"status"`
ProposalID string `theorydb:"attr:proposalID,omitempty" json:"proposal_id,omitempty"`
ManifestJSON string `theorydb:"attr:manifestJSON,omitempty" json:"manifest_json,omitempty"`
ManifestDigest string `theorydb:"attr:manifestDigest,omitempty" json:"manifest_digest,omitempty"`
BundleDigest string `theorydb:"attr:bundleDigest,omitempty" json:"bundle_digest,omitempty"`
ContentDigest string `theorydb:"attr:contentDigest,omitempty" json:"content_digest,omitempty"`
Files []SkillRevisionFile `theorydb:"attr:files" json:"files,omitempty"`
Capabilities []string `theorydb:"attr:capabilities" json:"capabilities,omitempty"`
DefaultExposure string `theorydb:"attr:defaultExposure" json:"default_exposure"`
ApprovalID string `theorydb:"attr:approvalID,omitempty" json:"approval_id,omitempty"`
ApprovalAuthorityType string `theorydb:"attr:approvalAuthorityType,omitempty" json:"approval_authority_type,omitempty"`
ApprovalAuthorityID string `theorydb:"attr:approvalAuthorityID,omitempty" json:"approval_authority_id,omitempty"`
ApprovalDigest string `theorydb:"attr:approvalDigest,omitempty" json:"approval_digest,omitempty"`
ApprovalSignature string `theorydb:"attr:approvalSignature,omitempty" json:"approval_signature,omitempty"`
ApprovalRef string `theorydb:"attr:approvalRef,omitempty" json:"approval_ref,omitempty"`
ApprovalReason string `theorydb:"attr:approvalReason,omitempty" json:"approval_reason,omitempty"`
ApprovedBy string `theorydb:"attr:approvedBy,omitempty" json:"approved_by,omitempty"`
ApprovedAt *time.Time `theorydb:"attr:approvedAt" json:"approved_at,omitempty"`
PrincipalID string `theorydb:"attr:principalID,omitempty" json:"principal_id,omitempty"`
PrincipalApprovalID string `theorydb:"attr:principalApprovalID,omitempty" json:"principal_approval_id,omitempty"`
Provenance []SkillProvenanceRef `theorydb:"attr:provenance" json:"provenance,omitempty"`
RevokedBy string `theorydb:"attr:revokedBy,omitempty" json:"revoked_by,omitempty"`
RevokedAt *time.Time `theorydb:"attr:revokedAt" json:"revoked_at,omitempty"`
RevokedReason string `theorydb:"attr:revokedReason,omitempty" json:"revoked_reason,omitempty"`
CreatedBy string `theorydb:"attr:createdBy,omitempty" json:"created_by,omitempty"`
UpdatedBy string `theorydb:"attr:updatedBy,omitempty" json:"updated_by,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
SkillRevision stores a canonical revision under its skill partition.
func (*SkillRevision) BeforeCreate ¶ added in v1.3.2
func (r *SkillRevision) BeforeCreate() error
BeforeCreate normalizes a SkillRevision before insert.
func (*SkillRevision) BeforeUpdate ¶ added in v1.3.2
func (r *SkillRevision) BeforeUpdate() error
BeforeUpdate normalizes a SkillRevision before update.
func (*SkillRevision) GetPK ¶ added in v1.3.2
func (r *SkillRevision) GetPK() string
GetPK returns the partition key.
func (*SkillRevision) GetSK ¶ added in v1.3.2
func (r *SkillRevision) GetSK() string
GetSK returns the sort key.
func (SkillRevision) TableName ¶ added in v1.3.2
func (SkillRevision) TableName() string
TableName returns the DynamoDB table backing SkillRevision.
func (*SkillRevision) UpdateKeys ¶ added in v1.3.2
func (r *SkillRevision) UpdateKeys() error
UpdateKeys refreshes SkillRevision primary and secondary keys.
type SkillRevisionFile ¶ added in v1.3.2
type SkillRevisionFile struct {
Path string `theorydb:"attr:path" json:"path"`
Digest string `theorydb:"attr:digest" json:"digest"`
ContentType string `theorydb:"attr:contentType,omitempty" json:"content_type,omitempty"`
Role string `theorydb:"attr:role,omitempty" json:"role,omitempty"`
SizeBytes int64 `theorydb:"attr:sizeBytes,omitempty" json:"size_bytes,omitempty"`
}
SkillRevisionFile records a publishable file included in a canonical skill revision manifest.
type SocialRecoveryRequest ¶
type SocialRecoveryRequest struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI fields for querying by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"`
// GSI fields for querying by username
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk,omitempty"`
// Business fields
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username"`
InitiatedAt time.Time `theorydb:"attr:initiatedAt" json:"initiated_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
RequiredVotes int `theorydb:"attr:requiredVotes" json:"required_votes"`
ReceivedVotes map[string]bool `theorydb:"attr:receivedVotes" json:"received_votes"` // trustee_id -> voted
RecoveryToken string `theorydb:"attr:recoveryToken" json:"recovery_token"`
Status string `theorydb:"attr:status" json:"status"` // pending, approved, expired, cancelled
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
SocialRecoveryRequest represents a request for social account recovery
func (*SocialRecoveryRequest) AddVote ¶
func (s *SocialRecoveryRequest) AddVote(trusteeID string) bool
AddVote adds a vote from a trustee
func (*SocialRecoveryRequest) Cancel ¶
func (s *SocialRecoveryRequest) Cancel()
Cancel cancels the recovery request
func (*SocialRecoveryRequest) GetProgress ¶
func (s *SocialRecoveryRequest) GetProgress() float64
GetProgress returns the recovery progress as a percentage
func (*SocialRecoveryRequest) GetVoteCount ¶
func (s *SocialRecoveryRequest) GetVoteCount() int
GetVoteCount returns the number of votes received
func (*SocialRecoveryRequest) IsActive ¶
func (s *SocialRecoveryRequest) IsActive() bool
IsActive checks if the recovery request is still active
func (*SocialRecoveryRequest) IsExpired ¶
func (s *SocialRecoveryRequest) IsExpired() bool
IsExpired checks if the recovery request has expired
func (*SocialRecoveryRequest) MarkExpired ¶
func (s *SocialRecoveryRequest) MarkExpired()
MarkExpired marks the request as expired
func (SocialRecoveryRequest) TableName ¶
func (SocialRecoveryRequest) TableName() string
TableName returns the DynamoDB table backing SocialRecoveryRequest.
func (*SocialRecoveryRequest) UpdateKeys ¶
func (s *SocialRecoveryRequest) UpdateKeys()
UpdateKeys updates the composite keys based on the recovery request
type Status ¶
type Status struct {
// Primary key - using status ID as the primary identifier
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "status#{status_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "status#{status_id}"
// GSI1 - Author timeline (all statuses by an author)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // Format: "AUTHOR#{author_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI2 - Public timeline (public statuses)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"-"` // Format: "PUBLIC_TIMELINE"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI3 - Conversation/thread tracking
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"-"` // Format: "CONVERSATION#{conversation_id}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI4 - Replies to a specific status
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"-"` // Format: "REPLIES#{parent_status_id}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI5 - Hashtag timeline
GSI5PK string `theorydb:"index:gsi5,pk,attr:gsi5PK,omitempty" json:"-"` // Format: "HASHTAG#{hashtag}"
GSI5SK string `theorydb:"index:gsi5,sk,attr:gsi5SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI6 - Flagged content moderation
GSI6PK string `theorydb:"index:gsi6,pk,attr:gsi6PK,omitempty" json:"-"` // Format: "FLAGGED_CONTENT"
GSI6SK string `theorydb:"index:gsi6,sk,attr:gsi6SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI7 - URL index for link searches
GSI7PK string `theorydb:"index:gsi7,pk,attr:gsi7PK,omitempty" json:"-"` // Format: "URL#{normalized_url}"
GSI7SK string `theorydb:"index:gsi7,sk,attr:gsi7SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// GSI8 - Admin timeline (all statuses, newest-first)
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty" json:"-"` // Format: "ADMIN_TIMELINE"
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty" json:"-"` // Format: "{published_timestamp}#{status_id}"
// Core status data
StatusID string `theorydb:"attr:statusID" json:"status_id"`
Note *activitypub.Note `theorydb:"attr:note" json:"note"` // The actual ActivityPub Note
AuthorID string `theorydb:"attr:authorID" json:"author_id"` // AttributedTo from the Note
AuthorUsername string `theorydb:"attr:authorUsername" json:"author_username"` // Extracted username for efficient queries
Content string `theorydb:"attr:content" json:"content"` // Cached content for search
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id,omitempty"` // Thread/conversation ID
InReplyToID string `theorydb:"attr:inReplyToID" json:"in_reply_to_id,omitempty"` // Parent status ID
ReblogOfID string `theorydb:"attr:reblogOfID" json:"reblog_of_id,omitempty"` // If this is a reblog, the original status ID
BoostOfStatusID string `theorydb:"attr:boostOfStatusID" json:"boost_of_status_id,omitempty"` // Original status ID for boost contexts
BoostOfAuthorID string `theorydb:"attr:boostOfAuthorID" json:"boost_of_author_id,omitempty"` // Author ID of the boosted status
BoostAnnounceID string `theorydb:"attr:boostActivityID" json:"boost_announce_id,omitempty"` // ActivityPub Announce ID backing this boost (legacy attribute retained)
QuoteTargetStatusID string `theorydb:"attr:quoteTargetStatusID" json:"quote_target_status_id,omitempty"` // If this status quotes another, the original status ID
QuoteTargetAuthorID string `theorydb:"attr:quoteTargetAuthorID" json:"quote_target_author_id,omitempty"` // Author ID of the quoted status
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"` // Content warning flag
Language string `theorydb:"attr:language" json:"language,omitempty"` // Content language
Mentions []string `theorydb:"attr:mentions" json:"mentions,omitempty"` // Extracted mentions
URLs []string `theorydb:"attr:urls" json:"urls,omitempty"` // Extracted URLs
MediaCount int `theorydb:"attr:mediaCount" json:"media_count"` // Number of media attachments
// Addressing fields for direct messages and limited visibility
ToRecipients []string `theorydb:"attr:toRecipients" json:"to_recipients,omitempty"` // Primary recipients (visible to all)
CcRecipients []string `theorydb:"attr:ccRecipients" json:"cc_recipients,omitempty"` // Carbon copy recipients (visible to all)
BtoRecipients []string `theorydb:"attr:btoRecipients" json:"bto_recipients,omitempty"` // Blind to recipients (hidden from others)
BccRecipients []string `theorydb:"attr:bccRecipients" json:"bcc_recipients,omitempty"` // Blind carbon copy (hidden from all)
// Engagement metrics (cached for performance)
LikeCount int `theorydb:"attr:likeCount" json:"like_count"`
ReblogCount int `theorydb:"attr:reblogCount" json:"reblog_count"`
ReplyCount int `theorydb:"attr:replyCount" json:"reply_count"`
QuoteCount int `theorydb:"attr:quoteCount" json:"quote_count,omitempty"`
// Timestamps
PublishedAt time.Time `theorydb:"attr:publishedAt" json:"published_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ModifiedAt time.Time `theorydb:"attr:modifiedAt" json:"modified_at"`
// Moderation and flags
Flagged bool `theorydb:"attr:flagged" json:"flagged,omitempty"`
Deleted bool `theorydb:"attr:deleted" json:"deleted,omitempty"`
DeletedAt *time.Time `theorydb:"attr:deletedAt" json:"deleted_at,omitempty"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Status represents an ActivityPub Note/status stored in DynamoDB using DynamORM
func (*Status) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Status) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Status) CanBeReblogged ¶
CanBeReblogged returns true if this status can be reblogged (boosted)
func (*Status) CreateHashtagIndexRecords ¶
func (s *Status) CreateHashtagIndexRecords() []*StatusHashtagIndex
CreateHashtagIndexRecords creates separate index records for each hashtag in the status
func (*Status) DeleteHashtagIndexRecords ¶
DeleteHashtagIndexRecords creates delete operations for all hashtag index records
func (*Status) GetAllHashtagIndexRecords ¶
func (s *Status) GetAllHashtagIndexRecords() []*StatusHashtagIndex
GetAllHashtagIndexRecords creates index records for ALL hashtags (including the first one) This is useful when you need separate records for all hashtags regardless of the primary record
func (*Status) GetAllRecipients ¶
GetAllRecipients returns all recipients across all addressing fields
func (*Status) GetPrivacyScore ¶
GetPrivacyScore returns a numeric score representing how private this status is (higher = more private)
func (*Status) GetVisibleRecipients ¶
GetVisibleRecipients returns recipients that should be visible to the requesting actor
func (*Status) HasHashtags ¶
HasHashtags returns true if the status contains hashtags
func (*Status) HasMentions ¶
HasMentions returns true if the status contains mentions
func (*Status) HasSpecificRecipients ¶
HasSpecificRecipients checks if status has specific actor recipients (not just collections)
func (*Status) IsConversation ¶
IsConversation returns true if this status is part of a conversation (has replies or is a reply)
func (*Status) IsRecipient ¶
IsRecipient checks if the given actor ID is a recipient of this status
func (*Status) IsVisibleTo ¶
IsVisibleTo checks if the status is visible to the given actor ID
func (*Status) RequiresFollowCheck ¶
RequiresFollowCheck returns true if visibility requires checking follower relationship
func (*Status) SanitizeForActor ¶
SanitizeForActor removes sensitive information based on viewer's relationship to the post
func (*Status) ShouldAppearInTimeline ¶
ShouldAppearInTimeline checks if status should appear in a given timeline type
func (*Status) SyncTagFieldsFromNote ¶ added in v1.1.73
func (s *Status) SyncTagFieldsFromNote()
SyncTagFieldsFromNote refreshes extracted hashtags and mentions from Note tags without touching timestamps, keys, or other persisted bookkeeping fields.
func (*Status) UpdateKeys ¶
UpdateKeys updates the GSI keys for this status (required by DynamORM)
type StatusAttachment ¶
type StatusAttachment struct {
Type string `json:"type"`
URL string `json:"url"`
MediaType string `json:"media_type,omitempty"`
Name string `json:"name,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
}
StatusAttachment represents a media attachment on a status
func (StatusAttachment) TableName ¶
func (StatusAttachment) TableName() string
TableName returns the DynamoDB table backing StatusAttachment.
type StatusEngagement ¶
type StatusEngagement struct {
PK string `theorydb:"pk,attr:PK"` // STATUS_ENGAGEMENT#statusID
SK string `theorydb:"sk,attr:SK"` // engagementType#timestamp#userID
StatusID string `theorydb:"attr:statusID" json:"status_id"` // Status being engaged with
EngagementType string `theorydb:"attr:engagementType" json:"engagement_type"` // like, boost, reply
UserID string `theorydb:"attr:userID" json:"user_id"` // User performing engagement
EngagedAt time.Time `theorydb:"attr:engagedAt" json:"engaged_at"` // When engagement occurred
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 7 day TTL
// contains filtered or unexported fields
}
StatusEngagement tracks engagement on statuses (like, boost, reply)
func (*StatusEngagement) GetPK ¶
func (s *StatusEngagement) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*StatusEngagement) GetSK ¶
func (s *StatusEngagement) GetSK() string
GetSK returns the sort key for BaseModel interface
func (StatusEngagement) TableName ¶
func (StatusEngagement) TableName() string
TableName returns the DynamoDB table backing StatusEngagement.
func (*StatusEngagement) UpdateKeys ¶
func (s *StatusEngagement) UpdateKeys() error
UpdateKeys updates GSI keys for StatusEngagement - no GSIs needed for this model
type StatusHashtagIndex ¶
type StatusHashtagIndex struct {
PK string `theorydb:"pk" json:"pk"` // Format: "HASHTAG_INDEX#{hashtag}"
SK string `theorydb:"sk" json:"sk"` // Format: "{published_timestamp}#{status_id}"
// Reference back to the original status
StatusID string `json:"status_id"`
AuthorID string `json:"author_id"`
Hashtag string `json:"hashtag"`
PublishedAt time.Time `json:"published_at"`
Visibility string `json:"visibility"`
// TTL for cleanup (optional - could be set to expire old hashtag indices)
TTL int64 `json:"ttl,omitempty" theorydb:"ttl"`
}
StatusHashtagIndex represents a separate record for each hashtag in a status
func (StatusHashtagIndex) TableName ¶
func (StatusHashtagIndex) TableName() string
TableName returns the DynamoDB table backing StatusHashtagIndex.
func (*StatusHashtagIndex) UpdateKeys ¶
func (shi *StatusHashtagIndex) UpdateKeys()
UpdateKeys sets the DynamoDB keys for hashtag index records
type StatusMetadata ¶
type StatusMetadata struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "STATUS_META#{status_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "METADATA"
// Core identification
StatusID string `theorydb:"attr:statusID" json:"status_id"`
// Quote-related metadata
QuoteType string `theorydb:"attr:quoteType" json:"quote_type"` // "public", "followers", "mentioned", "disabled"
WithdrawnFromQuotes bool `theorydb:"attr:withdrawnFromQuotes" json:"withdrawn_from_quotes"` // Whether status is withdrawn from quotes
AllowQuotes bool `theorydb:"attr:allowQuotes" json:"allow_quotes"` // Whether quotes are allowed at all
QuotePermissions string `theorydb:"attr:quotePermissions" json:"quote_permissions"` // JSON serialized quote permissions
// Reply-related metadata
AllowReplies bool `theorydb:"attr:allowReplies" json:"allow_replies"` // Whether replies are allowed
ReplyPermissions string `theorydb:"attr:replyPermissions" json:"reply_permissions"` // JSON serialized reply permissions
ReplyCount int `theorydb:"attr:replyCount" json:"reply_count"` // Cache of reply count
// Moderation metadata
ContentWarning string `theorydb:"attr:contentWarning" json:"content_warning"` // Content warning text
ModerationFlags []string `theorydb:"attr:moderationFlags" json:"moderation_flags"` // Applied moderation flags
ModerationNotes string `theorydb:"attr:moderationNotes" json:"moderation_notes"` // Internal moderation notes
// Engagement settings
DisableLikes bool `theorydb:"attr:disableLikes" json:"disable_likes"` // Whether likes are disabled
DisableReblogs bool `theorydb:"attr:disableReblogs" json:"disable_reblogs"` // Whether reblogs are disabled
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
StatusMetadata represents additional metadata for a status/object This handles features like quote permissions, withdrawal status, etc.
func NewStatusMetadata ¶
func NewStatusMetadata(statusID string) *StatusMetadata
NewStatusMetadata creates a new status metadata record
func (*StatusMetadata) AddModerationFlag ¶
func (sm *StatusMetadata) AddModerationFlag(flag string)
AddModerationFlag adds a moderation flag
func (*StatusMetadata) BeforeCreate ¶
func (sm *StatusMetadata) BeforeCreate() error
BeforeCreate is called before creating the record
func (*StatusMetadata) BeforeUpdate ¶
func (sm *StatusMetadata) BeforeUpdate() error
BeforeUpdate is called before updating the record
func (*StatusMetadata) DecrementReplyCount ¶
func (sm *StatusMetadata) DecrementReplyCount()
DecrementReplyCount decrements the reply count (with minimum of 0)
func (*StatusMetadata) HasModerationFlag ¶
func (sm *StatusMetadata) HasModerationFlag(flag string) bool
HasModerationFlag checks if a moderation flag is present
func (*StatusMetadata) IncrementReplyCount ¶
func (sm *StatusMetadata) IncrementReplyCount()
IncrementReplyCount increments the reply count
func (*StatusMetadata) IsPubliclyQuotable ¶
func (sm *StatusMetadata) IsPubliclyQuotable() bool
IsPubliclyQuotable returns whether the status can be quoted by anyone
func (*StatusMetadata) IsQuotable ¶
func (sm *StatusMetadata) IsQuotable() bool
IsQuotable returns whether the status can be quoted
func (*StatusMetadata) RemoveModerationFlag ¶
func (sm *StatusMetadata) RemoveModerationFlag(flag string)
RemoveModerationFlag removes a moderation flag
func (*StatusMetadata) RestoreToQuotes ¶
func (sm *StatusMetadata) RestoreToQuotes()
RestoreToQuotes restores the status to allow quotes
func (*StatusMetadata) SetQuoteType ¶
func (sm *StatusMetadata) SetQuoteType(quoteType string)
SetQuoteType sets the quote type and updates permissions accordingly
func (*StatusMetadata) SetReplyCount ¶
func (sm *StatusMetadata) SetReplyCount(count int)
SetReplyCount sets the reply count to a specific value
func (StatusMetadata) TableName ¶
func (StatusMetadata) TableName() string
TableName returns the DynamoDB table name
func (*StatusMetadata) UpdateKeys ¶
func (sm *StatusMetadata) UpdateKeys()
UpdateKeys updates the DynamoDB keys
func (*StatusMetadata) WithdrawFromQuotes ¶
func (sm *StatusMetadata) WithdrawFromQuotes()
WithdrawFromQuotes marks the status as withdrawn from quotes
type StatusPin ¶
type StatusPin struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // USER#{username}#PINS
SK string `theorydb:"sk,attr:SK" json:"SK"` // STATUS#{status_id}
// Core fields from legacy
Username string `theorydb:"attr:username" json:"username"` // Who pinned the status
StatusID string `theorydb:"attr:statusID" json:"status_id"` // The status that was pinned
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When it was pinned
// contains filtered or unexported fields
}
StatusPin represents a pinned status on a user's profile
func (*StatusPin) BeforeCreate ¶
BeforeCreate prepares the StatusPin for creation
func (*StatusPin) UpdateKeys ¶
UpdateKeys sets the primary keys based on the current data
type StatusSearchOptions ¶
type StatusSearchOptions struct {
Limit int `json:"limit"` // Maximum results to return
Offset int `json:"offset"` // For pagination
AccountID string `json:"account_id"` // Filter by specific account
FollowingOnly bool `json:"following_only"` // Only from accounts user follows
LocalOnly bool `json:"local_only"` // Only local statuses
MediaOnly bool `json:"media_only"` // Only statuses with media
Language string `json:"language"` // Filter by language
MinEngagement int `json:"min_engagement"` // Minimum likes/boosts
TimeRange TimeRange `json:"time_range"` // Time-based filtering
}
StatusSearchOptions configures status search behavior This is a query parameter type, not stored in DynamoDB
func NewStatusSearchOptions ¶
func NewStatusSearchOptions() *StatusSearchOptions
NewStatusSearchOptions creates new search options with defaults
func (StatusSearchOptions) TableName ¶
func (StatusSearchOptions) TableName() string
TableName returns the DynamoDB table backing StatusSearchOptions.
func (*StatusSearchOptions) Validate ¶
func (o *StatusSearchOptions) Validate() error
Validate ensures options are valid
func (*StatusSearchOptions) WithAccountID ¶
func (o *StatusSearchOptions) WithAccountID(accountID string) *StatusSearchOptions
WithAccountID filters results by account
func (*StatusSearchOptions) WithFollowingOnly ¶
func (o *StatusSearchOptions) WithFollowingOnly() *StatusSearchOptions
WithFollowingOnly restricts results to accounts the user follows
func (*StatusSearchOptions) WithLanguage ¶
func (o *StatusSearchOptions) WithLanguage(language string) *StatusSearchOptions
WithLanguage filters results by language
func (*StatusSearchOptions) WithLimit ¶
func (o *StatusSearchOptions) WithLimit(limit int) *StatusSearchOptions
WithLimit sets the maximum number of results
func (*StatusSearchOptions) WithLocalOnly ¶
func (o *StatusSearchOptions) WithLocalOnly() *StatusSearchOptions
WithLocalOnly restricts results to local statuses
func (*StatusSearchOptions) WithMediaOnly ¶
func (o *StatusSearchOptions) WithMediaOnly() *StatusSearchOptions
WithMediaOnly restricts results to statuses with media
func (*StatusSearchOptions) WithMinEngagement ¶
func (o *StatusSearchOptions) WithMinEngagement(minVal int) *StatusSearchOptions
WithMinEngagement sets minimum engagement threshold
func (*StatusSearchOptions) WithOffset ¶
func (o *StatusSearchOptions) WithOffset(offset int) *StatusSearchOptions
WithOffset sets the pagination offset
func (*StatusSearchOptions) WithTimeRange ¶
func (o *StatusSearchOptions) WithTimeRange(start, end time.Time) *StatusSearchOptions
WithTimeRange sets the time range filter
type StatusSearchResult ¶
type StatusSearchResult struct {
StatusID string `json:"status_id"`
Content string `json:"content"`
URL string `json:"url"`
AuthorID string `json:"author_id"`
AuthorUsername string `json:"author_username"`
Published time.Time `json:"published"`
Score float64 `json:"score"`
Highlights map[string]string `json:"highlights"`
}
StatusSearchResult represents a status search result This is a response type used for search results, not stored in DynamoDB
func NewStatusSearchResult ¶
func NewStatusSearchResult(statusID, content, url, authorID, authorUsername string, published time.Time) *StatusSearchResult
NewStatusSearchResult creates a new status search result
func (*StatusSearchResult) AddHighlight ¶
func (s *StatusSearchResult) AddHighlight(field, highlight string)
AddHighlight adds a highlighted snippet for a field
func (*StatusSearchResult) IsRecent ¶
func (s *StatusSearchResult) IsRecent() bool
IsRecent returns true if the status was published within the last 24 hours
func (*StatusSearchResult) SetScore ¶
func (s *StatusSearchResult) SetScore(score float64)
SetScore sets the relevance score for the search result
func (StatusSearchResult) TableName ¶
func (StatusSearchResult) TableName() string
TableName returns the DynamoDB table backing StatusSearchResult.
type StatusTag ¶
type StatusTag struct {
Type string `json:"type"`
Href string `json:"href,omitempty"`
Name string `json:"name"`
}
StatusTag represents a tag (hashtag or mention) on a status
type StatusTrend ¶
type StatusTrend struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"`
ID string `theorydb:"attr:id" json:"id"`
URL string `theorydb:"attr:url" json:"url"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Content string `theorydb:"attr:content" json:"content"`
Engagements int64 `theorydb:"attr:engagements" json:"engagements"`
PublishedAt time.Time `theorydb:"attr:publishedAt" json:"published_at"`
TrendScore float64 `theorydb:"attr:trendScore" json:"trend_score"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
StatusTrend represents a trending status
func (StatusTrend) TableName ¶
func (StatusTrend) TableName() string
TableName returns the DynamoDB table backing StatusTrend.
func (*StatusTrend) UpdateKeys ¶
func (s *StatusTrend) UpdateKeys() error
UpdateKeys updates the GSI keys for status trend
type StreamingCloudWatchMetrics ¶
type StreamingCloudWatchMetrics struct {
// DynamoDB Keys
PK string `theorydb:"pk,attr:PK" json:"pk"` // STREAMING_METRICS#{metric_type}
SK string `theorydb:"sk,attr:SK" json:"sk"` // {media_id}#{timestamp}
// GSI keys for time-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // METRIC_TIME#{date}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // {metric_type}#{timestamp}
// GSI2 for media-specific queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk"` // MEDIA#{media_id}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk"` // {metric_type}#{timestamp}
// Business fields
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
MetricType string `theorydb:"attr:metricType" json:"metric_type"` // quality_breakdown, geographic_data, concurrent_viewers, performance
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD for daily aggregation
// Quality breakdown metrics (when MetricType = "quality_breakdown")
QualityMetrics map[string]QualityMetric `theorydb:"attr:qualityMetrics" json:"quality_metrics,omitempty"`
// Geographic distribution metrics (when MetricType = "geographic_data")
GeographicMetrics map[string]GeographicMetric `theorydb:"attr:geographicMetrics" json:"geographic_metrics,omitempty"`
// Concurrent viewer metrics (when MetricType = "concurrent_viewers")
ConcurrentViewers ConcurrentViewerMetrics `theorydb:"attr:concurrentViewers" json:"concurrent_viewers,omitempty"`
// Performance metrics (when MetricType = "performance")
PerformanceMetrics StreamingPerformanceMetrics `theorydb:"attr:performanceMetrics" json:"performance_metrics,omitempty"`
// Caching metadata
CloudWatchQueryTime time.Time `theorydb:"attr:cloudWatchQueryTime" json:"cloudwatch_query_time"` // When the data was fetched from CloudWatch
DataFreshness int64 `theorydb:"attr:dataFreshness" json:"data_freshness"` // Seconds since CloudWatch query
CacheExpiry time.Time `theorydb:"attr:cacheExpiry" json:"cache_expiry"` // When this cache entry expires
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
StreamingCloudWatchMetrics caches CloudWatch metrics for streaming optimization
func (*StreamingCloudWatchMetrics) GetBestQuality ¶
func (s *StreamingCloudWatchMetrics) GetBestQuality() string
GetBestQuality returns the quality with the lowest buffering rate and good performance
func (*StreamingCloudWatchMetrics) GetBestRegionQuality ¶
func (s *StreamingCloudWatchMetrics) GetBestRegionQuality(region string) string
GetBestRegionQuality returns the best quality for a specific region
func (*StreamingCloudWatchMetrics) GetPK ¶
func (s *StreamingCloudWatchMetrics) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*StreamingCloudWatchMetrics) GetSK ¶
func (s *StreamingCloudWatchMetrics) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*StreamingCloudWatchMetrics) IsExpired ¶
func (s *StreamingCloudWatchMetrics) IsExpired() bool
IsExpired checks if the cached data has expired
func (*StreamingCloudWatchMetrics) SetConcurrentViewers ¶
func (s *StreamingCloudWatchMetrics) SetConcurrentViewers(mediaID string, metrics ConcurrentViewerMetrics)
SetConcurrentViewers configures this record for concurrent viewer metrics
func (*StreamingCloudWatchMetrics) SetGeographicData ¶
func (s *StreamingCloudWatchMetrics) SetGeographicData(mediaID string, metrics map[string]GeographicMetric)
SetGeographicData configures this record for geographic distribution metrics
func (*StreamingCloudWatchMetrics) SetPerformanceMetrics ¶
func (s *StreamingCloudWatchMetrics) SetPerformanceMetrics(mediaID string, metrics StreamingPerformanceMetrics)
SetPerformanceMetrics configures this record for performance metrics
func (*StreamingCloudWatchMetrics) SetQualityBreakdown ¶
func (s *StreamingCloudWatchMetrics) SetQualityBreakdown(mediaID string, metrics map[string]QualityMetric)
SetQualityBreakdown configures this record for quality breakdown metrics
func (*StreamingCloudWatchMetrics) ShouldAdaptQuality ¶
func (s *StreamingCloudWatchMetrics) ShouldAdaptQuality(currentQuality string) (bool, string)
ShouldAdaptQuality determines if quality should be adapted based on performance metrics
func (StreamingCloudWatchMetrics) TableName ¶
func (StreamingCloudWatchMetrics) TableName() string
TableName returns the DynamoDB table backing StreamingCloudWatchMetrics.
func (*StreamingCloudWatchMetrics) UpdateFreshness ¶
func (s *StreamingCloudWatchMetrics) UpdateFreshness()
UpdateFreshness updates the data freshness metric
func (*StreamingCloudWatchMetrics) UpdateKeys ¶
func (s *StreamingCloudWatchMetrics) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type StreamingEvent ¶
type StreamingEvent struct {
// Primary key - unique event ID
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "STREAM_EVENT#{eventID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "EVENT"
// GSI1 - Query by target (user, stream, conversation, followers)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "STREAM_TARGET#{targetType}#{targetID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{createdAt}#{eventID}"
// GSI2 - Query by event type
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "STREAM_TYPE#{eventType}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{createdAt}#{eventID}"
// Core event data
EventID string `theorydb:"attr:eventID" json:"event_id"`
EventType string `theorydb:"attr:eventType" json:"event_type"` // e.g., "status.created", "notification.created"
TargetType string `theorydb:"attr:targetType" json:"target_type"` // "user", "stream", "conversation", "followers"
TargetID string `theorydb:"attr:targetID" json:"target_id"` // The specific user/stream/conversation ID
Payload map[string]interface{} `theorydb:"attr:payload" json:"payload"` // The event data to send
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ProcessedAt *time.Time `theorydb:"attr:processedAt" json:"processed_at,omitempty"` // When stream-router processed it
DeliveredTo []string `theorydb:"attr:deliveredTo" json:"delivered_to,omitempty"` // Connection IDs it was delivered to
// TTL for automatic cleanup (Unix timestamp)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
StreamingEvent represents a queued streaming event in DynamoDB These events are picked up by DynamoDB Streams and processed by the stream-router Lambda
func (*StreamingEvent) GetPrimaryKey ¶
func (e *StreamingEvent) GetPrimaryKey() (string, string)
GetPrimaryKey returns the primary key for this model
func (*StreamingEvent) GetTableName ¶
func (e *StreamingEvent) GetTableName() string
GetTableName returns the table name for this model
func (*StreamingEvent) TableName ¶
func (e *StreamingEvent) TableName() string
TableName returns the DynamoDB table backing StreamingEvent.
func (*StreamingEvent) UpdateKeys ¶
func (e *StreamingEvent) UpdateKeys()
UpdateKeys updates the GSI keys based on the event data
type StreamingPerformanceMetrics ¶
type StreamingPerformanceMetrics struct {
OverallLatencyMs int64 `json:"overall_latency_ms"` // Overall CDN latency
OverallErrorRate float64 `json:"overall_error_rate"` // Overall error rate across all qualities
OverallBufferingRate float64 `json:"overall_buffering_rate"` // Overall buffering rate
ThroughputMbps float64 `json:"throughput_mbps"` // Current throughput
CDNHitRate float64 `json:"cdn_hit_rate"` // Overall CDN cache hit rate
EdgeLocations int `json:"edge_locations"` // Number of active edge locations
AutoQualityEvents int64 `json:"auto_quality_events"` // Number of quality switches in last hour
StartupLatencyMs int64 `json:"startup_latency_ms"` // Average startup latency across all qualities
}
StreamingPerformanceMetrics represents overall streaming performance
func (StreamingPerformanceMetrics) TableName ¶
func (StreamingPerformanceMetrics) TableName() string
TableName returns the DynamoDB table backing StreamingPerformanceMetrics.
type StreamingPreferences ¶
type StreamingPreferences struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // STREAMING_PREFS#{username}
SK string `theorydb:"sk,attr:SK" json:"sk"` // CURRENT or VERSION#{version}#{timestamp} or DEVICE#{deviceID}
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // USER#{username}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // STREAMING_PREFS#{timestamp}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk"` // DEVICE#{deviceID}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk"` // STREAMING_PREFS#{username}
// Business fields
Username string `theorydb:"attr:username" json:"username"`
DeviceID string `theorydb:"attr:deviceID" json:"device_id,omitempty"`
DefaultQuality string `theorydb:"attr:defaultQuality" json:"default_quality"` // auto/4k/1080p/720p/480p
AutoQuality bool `theorydb:"attr:autoQuality" json:"auto_quality"`
PreloadNext bool `theorydb:"attr:preloadNext" json:"preload_next"`
DataSaverMode bool `theorydb:"attr:dataSaverMode" json:"data_saver_mode"`
PreferredCodec string `theorydb:"attr:preferredCodec" json:"preferred_codec"` // h264/h265/av1/vp9
MaxBandwidthMbps int64 `theorydb:"attr:maxBandwidthMbps" json:"max_bandwidth_mbps"` // 0 means unlimited
BufferSizeSeconds int `theorydb:"attr:bufferSizeSeconds" json:"buffer_size_seconds"`
// Version control
Version int `theorydb:"attr:version" json:"version"`
SchemaVersion int `theorydb:"attr:schemaVersion" json:"schema_version"`
// Optional features - using pointers to detect nil vs false
HDREnabled *bool `theorydb:"attr:hdrEnabled" json:"hdr_enabled,omitempty"`
ColorSpace string `theorydb:"attr:colorSpace" json:"color_space,omitempty"`
SubtitleEnabled *bool `theorydb:"attr:subtitleEnabled" json:"subtitle_enabled,omitempty"`
SubtitleLanguage string `theorydb:"attr:subtitleLanguage" json:"subtitle_language,omitempty"`
AudioDescriptionEnabled *bool `theorydb:"attr:audioDescriptionEnabled" json:"audio_description_enabled,omitempty"`
ClosedCaptionsEnabled *bool `theorydb:"attr:closedCaptionsEnabled" json:"closed_captions_enabled,omitempty"`
// Timestamps
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup of old versions
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
StreamingPreferences model for DynamORM
func GetDefaultStreamingPreferences ¶
func GetDefaultStreamingPreferences(username string) *StreamingPreferences
GetDefaultStreamingPreferences returns default streaming preferences for a user
func (*StreamingPreferences) GetPK ¶
func (s *StreamingPreferences) GetPK() string
GetPK returns the partition key
func (*StreamingPreferences) GetSK ¶
func (s *StreamingPreferences) GetSK() string
GetSK returns the sort key
func (*StreamingPreferences) SetBackupPreference ¶
func (s *StreamingPreferences) SetBackupPreference()
SetBackupPreference sets this as a backup before migration
func (*StreamingPreferences) SetCurrentPreference ¶
func (s *StreamingPreferences) SetCurrentPreference()
SetCurrentPreference sets this as the current preference for a user
func (*StreamingPreferences) SetDevicePreference ¶
func (s *StreamingPreferences) SetDevicePreference(deviceID string)
SetDevicePreference sets this as a device-specific preference
func (*StreamingPreferences) SetVersionedPreference ¶
func (s *StreamingPreferences) SetVersionedPreference()
SetVersionedPreference sets this as a versioned preference in history
func (StreamingPreferences) TableName ¶
func (StreamingPreferences) TableName() string
TableName returns the DynamoDB table backing StreamingPreferences.
func (*StreamingPreferences) UpdateKeys ¶
func (s *StreamingPreferences) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type TOCEntry ¶
type TOCEntry struct {
ID string `json:"id"`
Level int `json:"level"` // 1-6 for h1-h6
Text string `json:"text"`
}
TOCEntry represents a table of contents entry
type ThreadContext ¶
type ThreadContext struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // THREAD#{rootStatusID}
SK string `theorydb:"sk,attr:SK" json:"-"` // CONTEXT#{statusID}
// GSI for querying by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{statusID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // THREAD
// Thread data
RootStatusID string `theorydb:"attr:rootStatusID" json:"root_status_id"` // The root/original status ID
StatusID string `theorydb:"attr:statusID" json:"status_id"` // The status this context is for
ParentID string `theorydb:"attr:parentID" json:"parent_id"` // Direct parent status ID
Depth int `theorydb:"attr:depth" json:"depth"` // Depth in the thread (0 for root)
Path string `theorydb:"attr:path" json:"path"` // Path from root (e.g., "root/reply1/reply2")
AuthorID string `theorydb:"attr:authorID" json:"author_id"` // Author of this status
AuthorHandle string `theorydb:"attr:authorHandle" json:"author_handle"` // For quick display
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When the status was created
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update
ReplyCount int `theorydb:"attr:replyCount" json:"reply_count"` // Number of direct replies
TotalReplies int `theorydb:"attr:totalReplies" json:"total_replies"` // Total replies in subtree
Participants []string `theorydb:"attr:participants" json:"participants"` // Unique participants in this branch
LastReplyAt *time.Time `theorydb:"attr:lastReplyAt" json:"last_reply_at,omitempty"` // When the last reply was made
Visibility string `theorydb:"attr:visibility" json:"visibility"` // Visibility of this status
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"` // Content warning flag
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id,omitempty"` // Associated conversation ID
// TTL for auto-cleanup (7 days after last activity)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ThreadContext represents the context of a status thread stored in DynamoDB
func (*ThreadContext) AddParticipant ¶
func (t *ThreadContext) AddParticipant(participantID string)
AddParticipant adds a participant if not already in the list
func (*ThreadContext) GetPathElements ¶
func (t *ThreadContext) GetPathElements() []string
GetPathElements returns the path split into elements
func (*ThreadContext) IncrementReplyCount ¶
func (t *ThreadContext) IncrementReplyCount()
IncrementReplyCount increments the reply count and updates last reply time
func (*ThreadContext) IsRoot ¶
func (t *ThreadContext) IsRoot() bool
IsRoot checks if this is the root of the thread
func (ThreadContext) TableName ¶
func (ThreadContext) TableName() string
TableName returns the DynamoDB table backing ThreadContext.
func (*ThreadContext) UpdateKeys ¶
func (t *ThreadContext) UpdateKeys()
UpdateKeys updates the GSI keys based on the thread context data
type ThreadNode ¶
type ThreadNode struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // THREAD#{rootStatusID}
SK string `theorydb:"sk,attr:SK" json:"-"` // NODE#{statusID}
// GSI for querying by status
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // STATUS#{statusID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // THREAD_NODE
// Node data
RootStatusID string `theorydb:"attr:rootStatusID" json:"root_status_id"` // The root of the thread
StatusID string `theorydb:"attr:statusID" json:"status_id"` // This status ID
ParentID string `theorydb:"attr:parentID" json:"parent_id,omitempty"` // Direct parent (empty for root)
Depth int `theorydb:"attr:depth" json:"depth"` // Depth in tree (0 for root)
Path string `theorydb:"attr:path" json:"path"` // Path from root (e.g., "root.reply1.reply2")
ChildIDs []string `theorydb:"attr:childIDs" json:"child_ids"` // Direct child status IDs
AuthorID string `theorydb:"attr:authorID" json:"author_id"` // Author of this status
AuthorHandle string `theorydb:"attr:authorHandle" json:"author_handle"` // For quick display
Content string `theorydb:"attr:content" json:"content"` // Preview of content
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When status was created
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"` // Has content warning
ReplyCount int `theorydb:"attr:replyCount" json:"reply_count"` // Number of direct replies
DescendantCount int `theorydb:"attr:descendantCount" json:"descendant_count"` // Total descendants in subtree
LastReplyAt *time.Time `theorydb:"attr:lastReplyAt" json:"last_reply_at,omitempty"` // Most recent reply in subtree
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"` // Last update
FetchedAt time.Time `theorydb:"attr:fetchedAt" json:"fetched_at"` // When we last fetched this node
IsLocal bool `theorydb:"attr:isLocal" json:"is_local"` // Whether this is a local status
RemoteURL string `theorydb:"attr:remoteURL" json:"remote_url,omitempty"` // URL if remote
// TTL for auto-cleanup (30 days after last activity)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ThreadNode represents a single node in a conversation thread tree Used for building and traversing thread hierarchies
func NewThreadNode ¶
func NewThreadNode(rootStatusID, statusID, parentID string, depth int, authorID string) *ThreadNode
NewThreadNode creates a new thread node
func (*ThreadNode) AddChild ¶
func (n *ThreadNode) AddChild(childID string)
AddChild adds a child status ID to the node
func (*ThreadNode) IncrementDescendantCount ¶
func (n *ThreadNode) IncrementDescendantCount(count int)
IncrementDescendantCount increments the descendant count
func (*ThreadNode) IsLeaf ¶
func (n *ThreadNode) IsLeaf() bool
IsLeaf checks if this node has no children
func (*ThreadNode) IsRoot ¶
func (n *ThreadNode) IsRoot() bool
IsRoot checks if this is the root of the thread
func (ThreadNode) TableName ¶
func (ThreadNode) TableName() string
TableName returns the DynamoDB table backing ThreadNode.
func (*ThreadNode) UpdateKeys ¶
func (n *ThreadNode) UpdateKeys() error
UpdateKeys updates the primary and GSI keys
func (*ThreadNode) UpdatePath ¶
func (n *ThreadNode) UpdatePath(parentPath string)
UpdatePath updates the path string
type ThreadSync ¶
type ThreadSync struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // THREAD_SYNC#{statusID}
SK string `theorydb:"sk,attr:SK" json:"-"` // METADATA
// Thread sync data
StatusID string `theorydb:"attr:statusID" json:"status_id"`
LastSyncAt time.Time `theorydb:"attr:lastSyncAt" json:"last_sync_at"`
SyncStatus string `theorydb:"attr:syncStatus" json:"sync_status"` // "pending", "syncing", "completed", "failed"
MissingReplies []string `theorydb:"attr:missingReplies" json:"missing_replies"` // List of missing reply IDs
RemoteFetched bool `theorydb:"attr:remoteFetched" json:"remote_fetched"` // Whether we've attempted remote fetch
ThreadDepth int `theorydb:"attr:threadDepth" json:"thread_depth"` // Current thread depth known
LastErrorMessage string `theorydb:"attr:lastErrorMessage" json:"last_error_message,omitempty"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for auto-cleanup (30 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ThreadSync represents thread synchronization metadata
func NewThreadSync ¶
func NewThreadSync(statusID string) *ThreadSync
NewThreadSync creates a new thread sync record
func (*ThreadSync) AddMissingReply ¶
func (t *ThreadSync) AddMissingReply(replyID string)
AddMissingReply adds a reply ID to the missing replies list
func (*ThreadSync) IsRecentlyCompleted ¶
func (t *ThreadSync) IsRecentlyCompleted() bool
IsRecentlyCompleted checks if the sync was completed recently (within 30 minutes)
func (*ThreadSync) MarkCompleted ¶
func (t *ThreadSync) MarkCompleted()
MarkCompleted updates the sync status to "completed"
func (*ThreadSync) MarkFailed ¶
func (t *ThreadSync) MarkFailed(errorMessage string)
MarkFailed updates the sync status to "failed" with an error message
func (*ThreadSync) MarkSyncing ¶
func (t *ThreadSync) MarkSyncing()
MarkSyncing updates the sync status to "syncing"
func (*ThreadSync) RemoveMissingReply ¶
func (t *ThreadSync) RemoveMissingReply(replyID string)
RemoveMissingReply removes a reply ID from the missing replies list
func (ThreadSync) TableName ¶
func (ThreadSync) TableName() string
TableName returns the DynamoDB table backing ThreadSync.
func (*ThreadSync) UpdateKeys ¶
func (t *ThreadSync) UpdateKeys() error
UpdateKeys updates the primary key fields
type ThreatIndicator ¶
type ThreatIndicator struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// Indicator data
ThreatID string `theorydb:"attr:threatID" json:"threat_id"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ThreatIndicator represents an indicator mapping for fast lookup
func (*ThreatIndicator) GetPK ¶
func (ti *ThreatIndicator) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*ThreatIndicator) GetSK ¶
func (ti *ThreatIndicator) GetSK() string
GetSK returns the sort key for BaseModel interface
func (ThreatIndicator) TableName ¶
func (ThreatIndicator) TableName() string
TableName returns the DynamoDB table backing ThreatIndicator.
func (*ThreatIndicator) UpdateKeys ¶
func (ti *ThreatIndicator) UpdateKeys(indicator, threatID string) error
UpdateKeys updates the PK and SK for indicator lookup
type ThreatIntel ¶
type ThreatIntel struct {
// Primary key fields - EXACT pattern from legacy
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
// Threat data fields
ID string `theorydb:"attr:id" json:"id"`
ThreatType string `theorydb:"attr:threatType" json:"threat_type"`
Severity string `theorydb:"attr:severity" json:"severity"`
Description string `theorydb:"attr:description" json:"description"`
Indicators []string `theorydb:"attr:indicators" json:"indicators"`
FirstSeen time.Time `theorydb:"attr:firstSeen" json:"first_seen"`
LastSeen time.Time `theorydb:"attr:lastSeen" json:"last_seen"`
HitCount int64 `theorydb:"attr:hitCount" json:"hit_count"`
Confidence float64 `theorydb:"attr:confidence" json:"confidence"`
// Source tracking
SourceDomain string `theorydb:"attr:sourceDomain" json:"source_domain"`
// TTL for automatic expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
ThreatIntel represents threat intelligence data in DynamoDB
func (*ThreatIntel) GetPK ¶
func (t *ThreatIntel) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*ThreatIntel) GetSK ¶
func (t *ThreatIntel) GetSK() string
GetSK returns the sort key for BaseModel interface
func (ThreatIntel) TableName ¶
func (ThreatIntel) TableName() string
TableName returns the DynamoDB table backing ThreatIntel.
func (*ThreatIntel) UpdateKeys ¶
func (t *ThreatIntel) UpdateKeys() error
UpdateKeys updates the PK, SK, and GSI keys based on threat data
type Timeline ¶
type Timeline struct {
// Primary key - using composite key for timeline entries
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "timeline#{timeline_type}#{timeline_id}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "{timeline_at_timestamp}#{entry_id}"
// GSI1 - Post timeline (all timeline entries for a specific post)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "POST#{post_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timeline_at_timestamp}#{entry_id}"
// GSI2 - Actor timeline (all timeline entries by an actor)
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "ACTOR#{actor_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timeline_at_timestamp}#{entry_id}"
// GSI3 - Visibility timeline (entries by visibility level)
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk,omitempty"` // Format: "VISIBILITY#{visibility}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk,omitempty"` // Format: "{timeline_at_timestamp}#{entry_id}"
// GSI4 - Language timeline (entries by language)
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk,omitempty"` // Format: "LANGUAGE#{language}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk,omitempty"` // Format: "{timeline_at_timestamp}#{entry_id}"
// Core timeline data
TimelineType string `theorydb:"attr:timelineType" json:"timeline_type"` // HOME, PUBLIC, LIST, DIRECT, HASHTAG
TimelineID string `theorydb:"attr:timelineID" json:"timeline_id"` // Username for HOME, LOCAL/FEDERATED for PUBLIC, list ID for LIST, hashtag for HASHTAG
EntryID string `theorydb:"attr:entryID" json:"entry_id"` // Unique ID for this entry (usually timestamp + post ID)
PostID string `theorydb:"attr:postID" json:"post_id"` // The actual post/object ID
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // Who created the post
ActorHandle string `theorydb:"attr:actorHandle" json:"actor_handle"` // Actor's handle for quick display
// Content preview for performance
Content string `theorydb:"attr:content" json:"content"` // First 500 chars for preview
ContentType string `theorydb:"attr:contentType" json:"content_type"` // Note, Article, etc.
// Quick flags for filtering
HasMedia bool `theorydb:"attr:hasMedia" json:"has_media"` // Quick flag for media
IsReply bool `theorydb:"attr:isReply" json:"is_reply"` // Is this a reply?
InReplyTo string `theorydb:"attr:inReplyTo" json:"in_reply_to"` // ID of post being replied to
IsBoost bool `theorydb:"attr:isBoost" json:"is_boost"` // Is this a boost/announce?
BoostedBy string `theorydb:"attr:boostedBy" json:"boosted_by"` // Who boosted it (if applicable)
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Language string `theorydb:"attr:language" json:"language"` // Language code
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"` // Content warning flag
SpoilerText string `theorydb:"attr:spoilerText" json:"spoiler_text"` // Content warning text
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When the post was created
TimelineAt time.Time `theorydb:"attr:timelineAt" json:"timeline_at"` // When it was added to timeline (for sorting)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // DynamoDB TTL (Unix timestamp)
// DynamORM metadata
ModifiedAt time.Time `theorydb:"attr:modifiedAt" json:"modified_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
Timeline represents an entry in a user's timeline stored in DynamoDB using DynamORM
func (*Timeline) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*Timeline) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*Timeline) GetPK ¶
GetPK returns the partition key for this timeline entry (required by BaseModel interface)
func (*Timeline) GetSK ¶
GetSK returns the sort key for this timeline entry (required by BaseModel interface)
func (*Timeline) GetSortKey ¶
GetSortKey returns the sort key for this entry
func (*Timeline) GetTimelineKey ¶
GetTimelineKey returns the timeline key for this entry
func (*Timeline) IsDirectTimeline ¶
IsDirectTimeline returns true if this is a direct timeline entry
func (*Timeline) IsHashtagTimeline ¶
IsHashtagTimeline returns true if this is a hashtag timeline entry
func (*Timeline) IsHomeTimeline ¶
IsHomeTimeline returns true if this is a home timeline entry
func (*Timeline) IsListTimeline ¶
IsListTimeline returns true if this is a list timeline entry
func (*Timeline) IsPublicTimeline ¶
IsPublicTimeline returns true if this is a public timeline entry
func (*Timeline) IsUnlisted ¶
IsUnlisted returns true if the timeline entry is unlisted
func (*Timeline) UpdateKeys ¶
UpdateKeys updates the GSI keys for this timeline entry (required by DynamORM)
type TimelineEntry ¶
type TimelineEntry struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // TIMELINE#{type}#{id}
SK string `theorydb:"sk,attr:SK" json:"-"` // {timestamp}#{entryID}
// GSI for public timeline queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // TIMELINE#PUBLIC#{local/federated}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // {timestamp}#{entryID}
// Entry data
TimelineType string `theorydb:"attr:timelineType" json:"timeline_type"` // HOME, PUBLIC, LIST, DIRECT
TimelineID string `theorydb:"attr:timelineID" json:"timeline_id"` // Username for HOME, LOCAL/FEDERATED for PUBLIC, list ID for LIST
EntryID string `theorydb:"attr:entryID" json:"entry_id"` // Unique ID for this entry (usually timestamp + post ID)
PostID string `theorydb:"attr:postID" json:"post_id"` // The actual post/object ID
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // Who created the post
ActorHandle string `theorydb:"attr:actorHandle" json:"actor_handle"` // Actor's handle for quick display
Content string `theorydb:"attr:content" json:"content"` // First 500 chars for preview
ContentType string `theorydb:"attr:contentType" json:"content_type"` // Note, Article, etc.
HasMedia bool `theorydb:"attr:hasMedia" json:"has_media"` // Quick flag for media
IsReply bool `theorydb:"attr:isReply" json:"is_reply"` // Is this a reply?
InReplyTo string `theorydb:"attr:inReplyTo" json:"in_reply_to"` // ID of post being replied to
IsBoost bool `theorydb:"attr:isBoost" json:"is_boost"` // Is this a boost/announce?
BoostedBy string `theorydb:"attr:boostedBy" json:"boosted_by"` // Who boosted it (if applicable)
Visibility string `theorydb:"attr:visibility" json:"visibility"` // public, unlisted, private, direct
Language string `theorydb:"attr:language" json:"language"` // Language code
Sensitive bool `theorydb:"attr:sensitive" json:"sensitive"` // Content warning flag
SpoilerText string `theorydb:"attr:spoilerText" json:"spoiler_text"` // Content warning text
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When the post was created
TimelineAt time.Time `theorydb:"attr:timelineAt" json:"timeline_at"` // When it was added to timeline (for sorting)
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"` // TTL for auto-deletion
// TTL for DynamoDB auto-deletion
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
TimelineEntry represents an entry in a user's timeline stored in DynamoDB
func (*TimelineEntry) IsExpired ¶
func (e *TimelineEntry) IsExpired() bool
IsExpired checks if the timeline entry has expired
func (*TimelineEntry) SetEntryID ¶
func (e *TimelineEntry) SetEntryID()
SetEntryID generates a unique entry ID if not already set
func (TimelineEntry) TableName ¶
func (TimelineEntry) TableName() string
TableName returns the DynamoDB table backing TimelineEntry.
func (*TimelineEntry) UpdateKeys ¶
func (e *TimelineEntry) UpdateKeys()
UpdateKeys updates the GSI keys based on the timeline entry data
type TimelineMarker ¶
type TimelineMarker struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // USER#{username}
SK string `theorydb:"sk,attr:SK" json:"sk"` // MARKER#{timeline}
Username string `theorydb:"attr:username" json:"username"`
Timeline string `theorydb:"attr:timeline" json:"timeline"` // home, notifications, etc.
LastReadID string `theorydb:"attr:lastReadID" json:"last_read_id"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
TimelineMarker represents a user's position in a timeline
func (*TimelineMarker) BeforeCreate ¶
func (m *TimelineMarker) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*TimelineMarker) BeforeUpdate ¶
func (m *TimelineMarker) BeforeUpdate() error
BeforeUpdate updates the timestamp
func (*TimelineMarker) GetPK ¶
func (m *TimelineMarker) GetPK() string
GetPK returns the partition key
func (TimelineMarker) TableName ¶
func (TimelineMarker) TableName() string
TableName returns the DynamoDB table name
func (*TimelineMarker) UpdateKeys ¶
func (m *TimelineMarker) UpdateKeys() error
UpdateKeys updates the keys
type Tombstone ¶
type Tombstone struct {
// Primary keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"PK"` // OBJECT#{object_id}
SK string `theorydb:"sk,attr:SK" json:"SK"` // TOMBSTONE
// GSI keys for querying tombstones by actor and type
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK"` // ACTOR#{actor_id}#TOMBSTONES
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK"` // DELETED#{timestamp}
// GSI for querying tombstones by type
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2PK"` // TOMBSTONE#{former_type}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2SK"` // DELETED#{timestamp}
// Core fields from legacy
ID string `theorydb:"attr:id" json:"id"` // Original object ID
Type string `theorydb:"attr:type" json:"type"` // Always "Tombstone"
FormerType string `theorydb:"attr:formerType" json:"formerType"` // Original object type
Deleted time.Time `theorydb:"attr:deleted" json:"deleted"` // When it was deleted
DeletedBy string `theorydb:"attr:deletedBy" json:"deletedBy"` // Actor who deleted it
AttributedTo string `theorydb:"attr:attributedTo,omitempty" json:"attributedTo,omitempty"` // Original object's author actor ID
IsPublic bool `theorydb:"attr:isPublic" json:"isPublic"` // Whether the original object was publicly addressed
Summary string `theorydb:"attr:summary" json:"summary,omitempty"` // Optional deletion reason
CreatedAt time.Time `theorydb:"attr:createdAt" json:"CreatedAt"` // When the tombstone was created
// TTL field for automatic cleanup after 30 days
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl"`
// contains filtered or unexported fields
}
Tombstone represents a deleted object marker
func (*Tombstone) BeforeCreate ¶
BeforeCreate prepares the Tombstone for creation
func (*Tombstone) GetDeletedBy ¶
GetDeletedBy returns the actor who deleted the object
func (*Tombstone) GetFormerType ¶
GetFormerType returns the type of the original object
func (*Tombstone) GetOriginalID ¶
GetOriginalID returns the ID of the original object
func (*Tombstone) IsTombstone ¶
IsTombstone always returns true for tombstone objects
func (*Tombstone) ShouldCleanup ¶
ShouldCleanup returns true if the tombstone is past its TTL
func (*Tombstone) UpdateKeys ¶
UpdateKeys updates GSI keys for the tombstone
type TrainingMetrics ¶
type TrainingMetrics struct {
Accuracy float64 `json:"accuracy"`
Precision float64 `json:"precision"`
Recall float64 `json:"recall"`
F1Score float64 `json:"f1_score"`
TrainingTime int `json:"training_time"` // seconds
}
TrainingMetrics holds training job metrics
func (TrainingMetrics) TableName ¶
func (TrainingMetrics) TableName() string
TableName returns the DynamoDB table backing TrainingMetrics.
type TranscodingJob ¶
type TranscodingJob struct {
// Primary key - using job ID as partition key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "TRANSCODING_JOB#{jobID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "JOB_METRICS"
// GSI1 - User-based queries for transcoding jobs
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USER_TRANSCODING#{userID}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{jobID}"
// GSI2 - Media-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"` // Format: "MEDIA_TRANSCODING#{mediaID}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"` // Format: "{timestamp}#{jobID}"
// Core job data
JobID string `theorydb:"attr:jobID" json:"job_id"`
MediaID string `theorydb:"attr:mediaID" json:"media_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
JobType string `theorydb:"attr:jobType" json:"job_type"` // "video", "audio", "image"
Status string `theorydb:"attr:status" json:"status"` // "processing", "completed", "failed"
// Input details
InputFormat string `theorydb:"attr:inputFormat" json:"input_format"` // "video/mp4", "audio/mpeg", etc.
InputSize int64 `theorydb:"attr:inputSize" json:"input_size"` // bytes
InputDuration int64 `theorydb:"attr:inputDuration" json:"input_duration"` // milliseconds (for video/audio)
InputResolution string `theorydb:"attr:inputResolution" json:"input_resolution"` // "1920x1080" (for video)
// Output details
OutputVariants map[string]string `theorydb:"attr:outputVariants" json:"output_variants"` // quality -> format mapping
OutputSizes map[string]int64 `theorydb:"attr:outputSizes" json:"output_sizes"` // quality -> size in bytes
TotalOutputSize int64 `theorydb:"attr:totalOutputSize" json:"total_output_size"` // sum of all output sizes
// Processing metrics
ProcessingTimeMs int64 `theorydb:"attr:processingTimeMs" json:"processing_time_ms"`
StartedAt time.Time `theorydb:"attr:startedAt" json:"started_at"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
// Cost breakdown (in microdollars)
TotalCostMicros int64 `theorydb:"attr:totalCostMicros" json:"total_cost_micros"`
CostBreakdown map[string]int64 `theorydb:"attr:costBreakdown" json:"cost_breakdown"` // service -> cost
MediaConvertCostMicros int64 `theorydb:"attr:mediaConvertCostMicros" json:"mediaconvert_cost_micros"`
S3StorageCostMicros int64 `theorydb:"attr:s3StorageCostMicros" json:"s3_storage_cost_micros"`
S3RequestCostMicros int64 `theorydb:"attr:s3RequestCostMicros" json:"s3_request_cost_micros"`
LambdaCostMicros int64 `theorydb:"attr:lambdaCostMicros" json:"lambda_cost_micros"`
RekognitionCostMicros int64 `theorydb:"attr:rekognitionCostMicros" json:"rekognition_cost_micros"`
// Quality and transcoding settings
QualityLevels []string `theorydb:"attr:qualityLevels" json:"quality_levels"` // ["480p", "720p", "1080p"]
ThumbnailCount int `theorydb:"attr:thumbnailCount" json:"thumbnail_count"` // number of thumbnails generated
AnalysisEnabled bool `theorydb:"attr:analysisEnabled" json:"analysis_enabled"` // whether content analysis was performed
// AWS service job IDs for tracking
MediaConvertJobID string `theorydb:"attr:mediaConvertJobID" json:"mediaconvert_job_id,omitempty"`
S3Keys []string `theorydb:"attr:s3Keys" json:"s3_keys"` // all S3 keys created by this job
// Efficiency metrics
CompressionRatio float64 `theorydb:"attr:compressionRatio" json:"compression_ratio"` // output_size / input_size
CostPerMB float64 `theorydb:"attr:costPerMB" json:"cost_per_mb"` // cost per MB processed
ProcessingSpeedMBps float64 `theorydb:"attr:processingSpeedMBps" json:"processing_speed_mbps"` // MB/second processing speed
// Budget tracking
EstimatedCostMicros int64 `theorydb:"attr:estimatedCostMicros" json:"estimated_cost_micros"` // initial cost estimate
CostVariance int64 `theorydb:"attr:costVariance" json:"cost_variance"` // actual - estimated cost
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for old transcoding jobs (keep for 1 year)
ExpiresAt *int64 `theorydb:"ttl,attr:ttl" json:"expires_at,omitempty"` // Unix timestamp
// Version for optimistic locking
ModelVersion int `theorydb:"version,attr:modelVersion" json:"model_version"`
// contains filtered or unexported fields
}
TranscodingJob tracks detailed metrics and costs for individual transcoding operations
func (*TranscodingJob) AddCost ¶
func (tj *TranscodingJob) AddCost(service string, costMicros int64)
AddCost adds a cost component to the job's cost breakdown
func (*TranscodingJob) AddOutputVariant ¶
func (tj *TranscodingJob) AddOutputVariant(quality, format string, size int64, s3Key string)
AddOutputVariant adds a new output variant to the job
func (*TranscodingJob) BeforeCreate ¶
func (tj *TranscodingJob) BeforeCreate() error
BeforeCreate sets up the TranscodingJob model before creation
func (*TranscodingJob) BeforeUpdate ¶
func (tj *TranscodingJob) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*TranscodingJob) Duration ¶
func (tj *TranscodingJob) Duration() time.Duration
Duration returns the total processing duration
func (*TranscodingJob) GetCostEfficiency ¶
func (tj *TranscodingJob) GetCostEfficiency() map[string]float64
GetCostEfficiency returns cost efficiency metrics
func (*TranscodingJob) GetPK ¶
func (tj *TranscodingJob) GetPK() string
GetPK returns the partition key for this transcoding job
func (*TranscodingJob) GetQualityBreakdown ¶
func (tj *TranscodingJob) GetQualityBreakdown() map[string]map[string]interface{}
GetQualityBreakdown returns a breakdown of costs by quality level
func (*TranscodingJob) GetSK ¶
func (tj *TranscodingJob) GetSK() string
GetSK returns the sort key for this transcoding job
func (*TranscodingJob) GetServiceCostBreakdown ¶
func (tj *TranscodingJob) GetServiceCostBreakdown() map[string]int64
GetServiceCostBreakdown returns costs broken down by AWS service
func (*TranscodingJob) IsCompleted ¶
func (tj *TranscodingJob) IsCompleted() bool
IsCompleted checks if the job has completed (successfully or with failure)
func (*TranscodingJob) SetCompleted ¶
func (tj *TranscodingJob) SetCompleted()
SetCompleted marks the job as completed and sets completion time
func (*TranscodingJob) SetFailed ¶
func (tj *TranscodingJob) SetFailed(errorMessage string)
SetFailed marks the job as failed with an error message
func (TranscodingJob) TableName ¶
func (TranscodingJob) TableName() string
TableName returns the DynamoDB table name for TranscodingJob
func (*TranscodingJob) UpdateKeys ¶
func (tj *TranscodingJob) UpdateKeys() error
UpdateKeys ensures all key fields are properly set
func (*TranscodingJob) Validate ¶
func (tj *TranscodingJob) Validate() error
Validate performs validation on the TranscodingJob
type TrendingHashtag ¶
type TrendingHashtag struct {
// Key fields - EXACT pattern from legacy: PK=`TRENDING#date`, SK=`HASHTAG#score#tag`
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI fields for trending queries
GSI8PK string `theorydb:"index:gsi8,pk,attr:gsi8PK,omitempty"`
GSI8SK string `theorydb:"index:gsi8,sk,attr:gsi8SK,omitempty"`
// Business fields from legacy
Hashtag string `theorydb:"attr:hashtag" json:"hashtag"`
Date string `theorydb:"attr:date" json:"date"` // YYYY-MM-DD format
Score float64 `theorydb:"attr:score" json:"score"` // trending score
UseCount int64 `theorydb:"attr:useCount" json:"use_count"`
UserCount int64 `theorydb:"attr:userCount" json:"user_count"` // unique users
History []float64 `theorydb:"attr:history" json:"history"` // 7-day trend
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL field - 30 days as per legacy
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
TrendingHashtag tracks trending hashtags with usage statistics
func (*TrendingHashtag) GetPK ¶
func (t *TrendingHashtag) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*TrendingHashtag) GetSK ¶
func (t *TrendingHashtag) GetSK() string
GetSK returns the sort key for BaseModel interface
func (TrendingHashtag) TableName ¶
func (TrendingHashtag) TableName() string
TableName returns the DynamoDB table backing TrendingHashtag.
func (*TrendingHashtag) UpdateKeys ¶
func (t *TrendingHashtag) UpdateKeys() error
UpdateKeys updates the GSI keys when the primary keys change
type TrendingLink ¶
type TrendingLink struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // TRENDING#{date}
SK string `theorydb:"sk,attr:SK" json:"-"` // LINK#{score}#{linkID}
// Attributes from interface
URL string `theorydb:"attr:url" json:"url"`
Title string `theorydb:"attr:title" json:"title"`
Description string `theorydb:"attr:description" json:"description"`
Type string `theorydb:"attr:type" json:"type"` // link, photo, video
AuthorName string `theorydb:"attr:authorName" json:"author_name"`
Image string `theorydb:"attr:image" json:"image"`
ImageURL string `theorydb:"attr:imageURL" json:"image_url"` // Additional field for image URL
UserID string `theorydb:"attr:userID" json:"user_id"` // User who shared the link
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When this share was recorded
// Additional fields for trending
Date string `theorydb:"attr:date" json:"date"` // Date for trending (YYYY-MM-DD)
LinkID string `theorydb:"attr:linkID" json:"link_id"` // Unique ID for this trending entry
TrendingScore float64 `theorydb:"attr:trendingScore" json:"trending_score"` // Calculated trending score
Domain string `theorydb:"attr:domain" json:"domain"` // Extracted domain from URL
Rank int `theorydb:"attr:rank" json:"rank"` // Position in trending list
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 7 days retention
// contains filtered or unexported fields
}
TrendingLink represents a trending link
func NewTrendingLink ¶
func NewTrendingLink(date string, link *TrendingLink) *TrendingLink
NewTrendingLink creates a new trending link
func (*TrendingLink) CalculateTrendingScore ¶
func (t *TrendingLink) CalculateTrendingScore()
CalculateTrendingScore calculates the trending score based on share count and recency
func (*TrendingLink) FormatTrendingSummary ¶
func (t *TrendingLink) FormatTrendingSummary() string
FormatTrendingSummary returns a human-readable summary
func (*TrendingLink) GetDisplayTitle ¶
func (t *TrendingLink) GetDisplayTitle() string
GetDisplayTitle returns a title for display, using URL if title is empty
func (*TrendingLink) IsStillTrending ¶
func (t *TrendingLink) IsStillTrending(minScore float64, maxAge time.Duration) bool
IsStillTrending checks if the link should still be considered trending
func (TrendingLink) TableName ¶
func (TrendingLink) TableName() string
TableName returns the DynamoDB table backing TrendingLink.
func (*TrendingLink) UpdateKeys ¶
func (t *TrendingLink) UpdateKeys()
UpdateKeys updates the partition and sort keys based on date and score
type TrendingStatus ¶
type TrendingStatus struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // TRENDING#{date}
SK string `theorydb:"sk,attr:SK" json:"-"` // STATUS#{score}#{statusID}
// Attributes from interface
ID string `theorydb:"attr:id" json:"id"`
URL string `theorydb:"attr:url" json:"url"`
AuthorID string `theorydb:"attr:authorID" json:"author_id"`
Content string `theorydb:"attr:content" json:"content"`
Engagements int64 `theorydb:"attr:engagements" json:"engagements"`
PublishedAt time.Time `theorydb:"attr:publishedAt" json:"published_at"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"` // When this trend record was created
Likes int `theorydb:"attr:likes" json:"likes"` // Number of likes
Boosts int `theorydb:"attr:boosts" json:"boosts"` // Number of boosts
Replies int `theorydb:"attr:replies" json:"replies"` // Number of replies
// Additional fields for trending
Date string `theorydb:"attr:date" json:"date"` // Date for trending (YYYY-MM-DD)
TrendingScore float64 `theorydb:"attr:trendingScore" json:"trending_score"` // Calculated trending score
Rank int `theorydb:"attr:rank" json:"rank"` // Position in trending list
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"` // 7 days retention
// contains filtered or unexported fields
}
TrendingStatus represents a trending status/post
func NewTrendingStatus ¶
func NewTrendingStatus(date string, status *TrendingStatus) *TrendingStatus
NewTrendingStatus creates a new trending status
func (*TrendingStatus) CalculateTrendingScore ¶
func (t *TrendingStatus) CalculateTrendingScore()
CalculateTrendingScore calculates the trending score based on engagement metrics
func (*TrendingStatus) FormatTrendingSummary ¶
func (t *TrendingStatus) FormatTrendingSummary() string
FormatTrendingSummary returns a human-readable summary
func (*TrendingStatus) IsStillTrending ¶
func (t *TrendingStatus) IsStillTrending(minScore float64, maxAge time.Duration) bool
IsStillTrending checks if the status should still be considered trending
func (TrendingStatus) TableName ¶
func (TrendingStatus) TableName() string
TableName returns the DynamoDB table backing TrendingStatus.
func (*TrendingStatus) UpdateKeys ¶
func (t *TrendingStatus) UpdateKeys()
UpdateKeys updates the partition and sort keys based on date and score
type TrustCategory ¶
type TrustCategory string
TrustCategory represents the category of trust
const ( // TrustCategoryContent represents trust category for content TrustCategoryContent TrustCategory = "content" // Trust in content moderation // TrustCategoryBehavior represents trust category for behavior TrustCategoryBehavior TrustCategory = "behavior" // Trust in behavior assessment // TrustCategoryTechnical represents trust category for technical aspects TrustCategoryTechnical TrustCategory = "technical" // Trust in technical decisions // TrustCategoryGeneral represents general trust category TrustCategoryGeneral TrustCategory = "general" // General trust )
type TrustEvidence ¶
type TrustEvidence struct {
Type string `json:"type"` // consensus_agreement, direct_interaction, etc.
Score float64 `json:"score"` // Impact on trust score
Description string `json:"description"`
Timestamp time.Time `json:"timestamp"`
}
TrustEvidence represents evidence supporting a trust relationship
func (TrustEvidence) TableName ¶
func (TrustEvidence) TableName() string
TableName returns the DynamoDB table backing TrustEvidence.
type TrustRelationship ¶
type TrustRelationship struct {
// Primary keys - exact patterns from legacy
PK string `theorydb:"pk,attr:PK"` // TRUST#trusterID#category
SK string `theorydb:"sk,attr:SK"` // TRUSTEE#trusteeID
// GSI1 - for reverse lookups (who trusts this trustee)
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"` // TRUSTED#trusteeID#category
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"` // TRUSTER#trusterID
// GSI2 - for domain-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"` // DOMAIN#domain
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"` // TRUST#category#score
// Business fields
ID string `theorydb:"attr:id" json:"id"`
TrusterID string `theorydb:"attr:trusterID" json:"truster_id"`
TrusteeID string `theorydb:"attr:trusteeID" json:"trustee_id"`
Category TrustCategory `theorydb:"attr:category" json:"category"`
Score float64 `theorydb:"attr:score" json:"score"` // -1.0 to 1.0
Confidence float64 `theorydb:"attr:confidence" json:"confidence"` // 0.0 to 1.0
Evidence []TrustEvidence `theorydb:"attr:evidence" json:"evidence,omitempty"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
Created time.Time `theorydb:"attr:created" json:"created"`
Updated time.Time `theorydb:"attr:updated" json:"updated"`
// Type marker for filtering
Type string `theorydb:"attr:type" json:"type"` // Always "RELATIONSHIP"
// contains filtered or unexported fields
}
TrustRelationship represents a trust relationship between two actors
func (*TrustRelationship) GetPK ¶
func (tr *TrustRelationship) GetPK() string
GetPK returns the partition key for this trust relationship
func (*TrustRelationship) GetSK ¶
func (tr *TrustRelationship) GetSK() string
GetSK returns the sort key for this trust relationship
func (TrustRelationship) TableName ¶
func (TrustRelationship) TableName() string
TableName returns the DynamoDB table backing TrustRelationship.
func (*TrustRelationship) UpdateKeys ¶
func (tr *TrustRelationship) UpdateKeys() error
UpdateKeys sets all the DynamoDB keys based on the relationship data
type TrustScore ¶
type TrustScore struct {
// Primary keys for cached scores
PK string `theorydb:"pk,attr:PK"` // SCORE#actorID#category
SK string `theorydb:"sk,attr:SK"` // CURRENT
// Business fields
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
Category TrustCategory `theorydb:"attr:category" json:"category"`
Score float64 `theorydb:"attr:score" json:"score"` // Aggregated score
DirectScore float64 `theorydb:"attr:directScore" json:"direct_score"` // Score from direct relationships
PropagatedScore float64 `theorydb:"attr:propagatedScore" json:"propagated_score"` // Score from network propagation
Confidence float64 `theorydb:"attr:confidence" json:"confidence"` // Confidence in score
TrusterCount int `theorydb:"attr:trusterCount" json:"truster_count"` // Number of direct trusters
CategoryScores map[string]float64 `theorydb:"attr:categoryScores" json:"category_scores"` // Scores by category
LastCalculated time.Time `theorydb:"attr:lastCalculated" json:"last_calculated"`
CacheTTL time.Time `theorydb:"attr:cacheTTL" json:"cache_ttl"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Type marker
Type string `theorydb:"attr:type" json:"type"` // Always "SCORE"
// contains filtered or unexported fields
}
TrustScore represents a cached trust score for an actor
func (*TrustScore) GetPK ¶
func (ts *TrustScore) GetPK() string
GetPK returns the partition key for this trust score
func (*TrustScore) GetSK ¶
func (ts *TrustScore) GetSK() string
GetSK returns the sort key for this trust score
func (TrustScore) TableName ¶
func (TrustScore) TableName() string
TableName returns the DynamoDB table backing TrustScore.
func (*TrustScore) UpdateKeys ¶
func (ts *TrustScore) UpdateKeys() error
UpdateKeys sets all the DynamoDB keys for the trust score
type TrustUpdate ¶
type TrustUpdate struct {
// Primary keys for update history
PK string `theorydb:"pk,attr:PK"` // UPDATES#actorID
SK string `theorydb:"sk,attr:SK"` // TIME#timestamp#eventID
// Business fields
ActorID string `theorydb:"attr:actorID" json:"actor_id"`
EventID string `theorydb:"attr:eventID" json:"event_id"`
Category TrustCategory `theorydb:"attr:category" json:"category"`
Delta float64 `theorydb:"attr:delta" json:"delta"` // Change in trust score
Reason string `theorydb:"attr:reason" json:"reason"` // Why the update occurred
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// Type marker
Type string `theorydb:"attr:type" json:"type"` // Always "UPDATE"
// contains filtered or unexported fields
}
TrustUpdate represents a trust score update event
func (*TrustUpdate) GetPK ¶
func (tu *TrustUpdate) GetPK() string
GetPK returns the partition key for this trust update
func (*TrustUpdate) GetSK ¶
func (tu *TrustUpdate) GetSK() string
GetSK returns the sort key for this trust update
func (TrustUpdate) TableName ¶
func (TrustUpdate) TableName() string
TableName returns the DynamoDB table backing TrustUpdate.
func (*TrustUpdate) UpdateKeys ¶
func (tu *TrustUpdate) UpdateKeys() error
UpdateKeys sets all the DynamoDB keys for the trust update
type Trustee ¶
type Trustee struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"` // USER#username
SK string `theorydb:"sk,attr:SK"` // TRUSTEE#actorID
// Business fields
Username string `theorydb:"attr:username" json:"username"` // Who owns this trustee relationship
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // @friend@mastodon.social
AddedAt time.Time `theorydb:"attr:addedAt" json:"added_at"`
Confirmed bool `theorydb:"attr:confirmed" json:"confirmed"`
// contains filtered or unexported fields
}
Trustee represents a trusted contact for social recovery
func (*Trustee) UpdateKeys ¶
UpdateKeys updates the primary and GSI keys based on the model's business fields
type TrusteeConfig ¶
type TrusteeConfig struct {
// Keys
PK string `theorydb:"pk,attr:PK" json:"-"` // TRUSTEE#CONFIG
SK string `theorydb:"sk,attr:SK" json:"-"` // {category} (e.g., recovery#{username}, moderation#{username})
// Attributes from interface
Username string `theorydb:"attr:username" json:"username"` // Who owns this trustee relationship
ActorID string `theorydb:"attr:actorID" json:"actor_id"` // @friend@mastodon.social
AddedAt time.Time `theorydb:"attr:addedAt" json:"added_at"`
Confirmed bool `theorydb:"attr:confirmed" json:"confirmed"`
// Additional attributes
Category string `theorydb:"attr:category" json:"category"` // recovery, moderation, emergency
TrustLevel string `theorydb:"attr:trustLevel" json:"trust_level"` // full, limited, emergency_only
ConfirmedAt *time.Time `theorydb:"attr:confirmedAt" json:"confirmed_at,omitempty"`
LastUsed *time.Time `theorydb:"attr:lastUsed" json:"last_used,omitempty"`
UsageCount int `theorydb:"attr:usageCount" json:"usage_count"`
RecoveryPriority int `theorydb:"attr:recoveryPriority" json:"recovery_priority"` // Order in recovery process (1 = first)
Permissions []string `theorydb:"attr:permissions" json:"permissions,omitempty"` // Specific permissions granted
Notes string `theorydb:"attr:notes" json:"notes,omitempty"` // User notes about this trustee
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
TrusteeConfig represents a trusted contact for social recovery
func NewTrusteeConfig ¶
func NewTrusteeConfig(username, actorID, category string) *TrusteeConfig
NewTrusteeConfig creates a new trustee configuration
func (*TrusteeConfig) AddPermission ¶
func (t *TrusteeConfig) AddPermission(permission string) bool
AddPermission adds a permission if not already present
func (*TrusteeConfig) CanPerformAction ¶
func (t *TrusteeConfig) CanPerformAction(action string) bool
CanPerformAction checks if trustee has permission for an action
func (*TrusteeConfig) Confirm ¶
func (t *TrusteeConfig) Confirm()
Confirm marks the trustee relationship as confirmed
func (*TrusteeConfig) FormatDisplayName ¶
func (t *TrusteeConfig) FormatDisplayName() string
FormatDisplayName returns a display-friendly name
func (*TrusteeConfig) GetTrustLevelPriority ¶
func (t *TrusteeConfig) GetTrustLevelPriority() int
GetTrustLevelPriority returns numeric priority for trust levels
func (*TrusteeConfig) IsActive ¶
func (t *TrusteeConfig) IsActive() bool
IsActive checks if the trustee is active and confirmed
func (*TrusteeConfig) IsModerationTrustee ¶
func (t *TrusteeConfig) IsModerationTrustee() bool
IsModerationTrustee checks if this is a moderation trustee
func (*TrusteeConfig) IsRecoveryTrustee ¶
func (t *TrusteeConfig) IsRecoveryTrustee() bool
IsRecoveryTrustee checks if this is a recovery trustee
func (*TrusteeConfig) RecordUsage ¶
func (t *TrusteeConfig) RecordUsage()
RecordUsage updates usage tracking
func (*TrusteeConfig) RemovePermission ¶
func (t *TrusteeConfig) RemovePermission(permission string) bool
RemovePermission removes a permission
func (*TrusteeConfig) SetPermissions ¶
func (t *TrusteeConfig) SetPermissions(permissions []string)
SetPermissions sets the permissions list
func (TrusteeConfig) TableName ¶
func (TrusteeConfig) TableName() string
TableName returns the DynamoDB table backing TrusteeConfig.
func (*TrusteeConfig) UpdateKeys ¶
func (t *TrusteeConfig) UpdateKeys()
UpdateKeys updates the partition and sort keys
type UpdateHistory ¶
type UpdateHistory struct {
// Primary Key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // OBJECT#<objectID>#HISTORY
SK string `theorydb:"sk,attr:SK" json:"-"` // VERSION#00001 (padded for sorting)
// Business fields matching storage.UpdateHistory
ObjectID string `theorydb:"attr:objectID" json:"objectId"` // The object that was updated
Version int `theorydb:"attr:version" json:"version"` // Version number (1 is original)
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updatedAt"` // When the update occurred
UpdatedBy string `theorydb:"attr:updatedBy" json:"updatedBy"` // Actor who made the update
PreviousState string `theorydb:"attr:previousState" json:"previousState"` // JSON of previous state
Summary string `theorydb:"attr:summary" json:"summary,omitempty"` // Edit summary
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"-"` // When this history record was created
TTL int64 `theorydb:"ttl,attr:ttl,omitempty" json:"-"` // Optional TTL for automatic cleanup
// contains filtered or unexported fields
}
UpdateHistory represents the edit history of an object
func (UpdateHistory) TableName ¶
func (UpdateHistory) TableName() string
TableName returns the DynamoDB table backing UpdateHistory.
func (*UpdateHistory) UpdateKeys ¶
func (h *UpdateHistory) UpdateKeys()
UpdateKeys updates the primary key fields based on the business fields
type UploadGrant ¶ added in v1.6.23
type UploadGrant struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Owner string `theorydb:"attr:owner"`
// GrantID is an unguessable opaque identifier returned to the owner at mint.
GrantID string `theorydb:"attr:grantID"`
// ContentType is the declared media type; the presigned PUT signs it so S3
// rejects a request carrying a different Content-Type header.
ContentType string `theorydb:"attr:contentType"`
// MaxSizeBytes is the declared size cap; finalize fails closed when the
// stored object exceeds it.
MaxSizeBytes int64 `theorydb:"attr:maxSizeBytes"`
// ContentSHA256 is the hex-encoded sha256 of the exact bytes the caller
// will PUT. Finalize computes the stored object's digest and admits the
// asset only when it matches.
ContentSHA256 string `theorydb:"attr:contentSHA256"`
// S3Bucket/S3Key locate the presigned PUT target. The key embeds the minted
// MediaID, is unguessable, and is scoped to exactly this grant.
S3Bucket string `theorydb:"attr:s3Bucket"`
S3Key string `theorydb:"attr:s3Key"`
// MediaID is minted with the grant so the object key and the final media
// record share one identity; finalize creates the record under this ID.
MediaID string `theorydb:"attr:mediaID,omitempty"`
// FileName is the record-level filename derived from the declared type.
FileName string `theorydb:"attr:fileName"`
// Status is UploadGrantStatusMinted/Used/FailedDigest.
Status string `theorydb:"attr:status"`
// GrantedAt and ExpiresAt bound the grant. A grant past ExpiresAt fails
// closed everywhere; ExpiresAtTTL lets DynamoDB self-clean the row.
GrantedAt time.Time `theorydb:"attr:grantedAt"`
ExpiresAt time.Time `theorydb:"attr:expiresAt"`
ExpiresAtTTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// UsedAt records the successful consume; FailedAt/FailureReason record a
// digest-failure consume so the owner can inspect why an upload was not
// admitted.
UsedAt *time.Time `theorydb:"attr:usedAt,omitempty"`
FailedAt *time.Time `theorydb:"attr:failedAt,omitempty"`
FailureReason string `theorydb:"attr:failureReason,omitempty"`
// Version guards the single-use consume: finalize transitions MINTED under
// the observed version, so a concurrent finalize cannot double-consume.
Version int `theorydb:"version,attr:version"`
}
UploadGrant authorizes one actor to PUT the exact declared bytes to one presigned S3 object and finalize them into an internal editorial media record. The grant is actor-scoped (owner partition), one-time (version- conditioned atomic consume), hash-bound (declared sha256 of the intended bytes), size-capped, and short-lived (DynamoDB TTL + fail-closed expiry).
func (*UploadGrant) Expired ¶ added in v1.6.23
func (g *UploadGrant) Expired(now time.Time) bool
Expired classifies a still-minted grant that has passed its bounded expiry. Consumed grants are never reported expired; the terminal state dominates.
func (*UploadGrant) GetPK ¶ added in v1.6.23
func (g *UploadGrant) GetPK() string
GetPK returns the partition key for this upload grant.
func (*UploadGrant) GetSK ¶ added in v1.6.23
func (g *UploadGrant) GetSK() string
GetSK returns the sort key for this upload grant.
func (*UploadGrant) IsFailedDigest ¶ added in v1.6.23
func (g *UploadGrant) IsFailedDigest() bool
IsFailedDigest reports whether a finalize consumed the grant because the uploaded bytes did not match the declared hash.
func (*UploadGrant) IsMinted ¶ added in v1.6.23
func (g *UploadGrant) IsMinted() bool
IsMinted reports whether the grant is in its initial consumable state.
func (*UploadGrant) IsUsed ¶ added in v1.6.23
func (g *UploadGrant) IsUsed() bool
IsUsed reports whether a finalize already consumed the grant successfully.
func (*UploadGrant) StatusClassification ¶ added in v1.6.23
func (g *UploadGrant) StatusClassification(now time.Time) string
StatusClassification returns the inspectable grant status for a query time: the stored terminal states plus the derived EXPIRED classification.
func (UploadGrant) TableName ¶ added in v1.6.23
func (UploadGrant) TableName() string
TableName returns the table backing an upload grant.
func (*UploadGrant) UpdateKeys ¶ added in v1.6.23
func (g *UploadGrant) UpdateKeys() error
UpdateKeys derives grant primary keys and the DynamoDB TTL attribute. A zero expiry is rejected: an upload grant without a bounded expiry must never authorize a PUT or finalize indefinitely (fail-closed, mirroring the review grant).
type User ¶
type User struct {
// Primary key - using username as the primary identifier
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "USER#{username}"`
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "METADATA"`
// GSI1 - User listing and pagination
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "USERS"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{created_at}#{username}"`
// GSI3 - Role-based queries
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3_pk"` // Format: "ROLE#{role}"
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3_sk"` // Format: "{username}"
// GSI4 - Status-based queries (approved, suspended, etc.)
GSI4PK string `theorydb:"index:gsi4,pk,attr:gsi4PK,omitempty" json:"gsi4_pk"` // Format: "STATUS#{status}"
GSI4SK string `theorydb:"index:gsi4,sk,attr:gsi4SK,omitempty" json:"gsi4_sk"` // Format: "{username}"
// GSI5 - Handle prefix search (optimized begins_with queries)
GSI5PK string `theorydb:"index:gsi5,pk,attr:gsi5PK,omitempty" json:"gsi5_pk"`
GSI5SK string `theorydb:"index:gsi5,sk,attr:gsi5SK,omitempty" json:"gsi5_sk"`
// GSI6 - Agent directory listing
GSI6PK string `theorydb:"index:gsi6,pk,attr:gsi6PK,omitempty" json:"gsi6_pk"`
GSI6SK string `theorydb:"index:gsi6,sk,attr:gsi6SK,omitempty" json:"gsi6_sk"`
// Core user data
Username string `theorydb:"attr:username" json:"username"`
Email string `theorydb:"attr:email" json:"email,omitempty"` // Optional - not required for email-free auth
PasswordHash string `theorydb:"attr:passwordHash" json:"password_hash,omitempty"` // Optional - not required for passkey/wallet auth
DisplayName string `theorydb:"attr:displayName" json:"display_name,omitempty"` // Display name for the user
Note string `theorydb:"attr:note" json:"note,omitempty"` // Profile bio / summary
Avatar string `theorydb:"attr:avatar" json:"avatar,omitempty"` // Avatar image URL
Header string `theorydb:"attr:header" json:"header,omitempty"` // Header image URL
URL string `theorydb:"attr:url" json:"url,omitempty"` // Profile URL
Locked bool `theorydb:"attr:locked" json:"locked"`
Discoverable bool `theorydb:"attr:discoverable" json:"discoverable"`
Fields []map[string]string `theorydb:"attr:fields" json:"fields,omitempty"` // Custom profile metadata fields
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
Approved bool `theorydb:"attr:approved" json:"approved"`
Suspended bool `theorydb:"attr:suspended" json:"suspended"`
Silenced bool `theorydb:"attr:silenced" json:"silenced"`
Role string `theorydb:"attr:role" json:"role"` // user, moderator, admin
Locale string `theorydb:"attr:locale" json:"locale,omitempty"`
// Recovery options (email-free)
RecoveryMethods []string `theorydb:"attr:recoveryMethods" json:"recovery_methods,omitempty"` // ["passkey", "wallet", "social", "recovery_code"]
// NSFW Content Preferences
AllowNSFW bool `theorydb:"attr:allowNSFW" json:"allow_nsfw"` // Whether user allows viewing NSFW content
RequireNSFWWarning bool `theorydb:"attr:requireNSFWWarning" json:"require_nsfw_warning"` // Whether user wants warnings before showing NSFW content
Metadata map[string]interface{} `theorydb:"attr:metadata" json:"metadata,omitempty"`
// Agent fields (LLM agents)
IsAgent bool `theorydb:"attr:isAgent" json:"is_agent"`
AgentType string `theorydb:"attr:agentType" json:"agent_type,omitempty"`
AgentCapabilities *agents.Capabilities `theorydb:"json,attr:agentCapabilities" json:"agent_capabilities,omitempty"`
AgentVersion string `theorydb:"attr:agentVersion" json:"agent_version,omitempty"`
AgentOwner string `theorydb:"attr:agentOwner" json:"agent_owner,omitempty"`
AgentCreatedBy string `theorydb:"attr:agentCreatedBy" json:"agent_created_by,omitempty"`
AgentPublicKey string `theorydb:"attr:agentPublicKey" json:"agent_public_key,omitempty"`
AgentKeyType string `theorydb:"attr:agentKeyType" json:"agent_key_type,omitempty"`
// Version for optimistic locking
Version int `theorydb:"version,attr:version" json:"version"`
// contains filtered or unexported fields
}
User represents a user account stored in DynamoDB using DynamORM
func (*User) BeforeCreate ¶
BeforeCreate sets up the model before creation
func (*User) BeforeUpdate ¶
BeforeUpdate sets up the model before update
func (*User) HasPassword ¶
HasPassword returns true if the user has a password hash
func (*User) IsActive ¶
IsActive returns true if the user is active (approved and not suspended/silenced)
func (*User) IsModerator ¶
IsModerator returns true if the user has moderator or admin role
func (*User) UpdateKeys ¶
UpdateKeys updates the GSI keys for this user (required by DynamORM)
type UserAppConsent ¶
type UserAppConsent struct {
// Primary key fields
PK string `theorydb:"pk,attr:PK" json:"-"` // USER#userID
SK string `theorydb:"sk,attr:SK" json:"-"` // CONSENT#appID
// GSI for querying by app
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"` // APP#appID
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"` // USER#userID
// Consent data
UserID string `theorydb:"attr:userID" json:"user_id"`
AppID string `theorydb:"attr:appID" json:"app_id"` // OAuth app client ID
Resource string `theorydb:"attr:resource,omitempty" json:"resource,omitempty"`
Scopes []string `theorydb:"attr:scopes" json:"scopes"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
RevokedAt *time.Time `theorydb:"attr:revokedAt" json:"revoked_at,omitempty"`
Active bool `theorydb:"attr:active" json:"active"`
// contains filtered or unexported fields
}
UserAppConsent represents user consent for an OAuth app stored in DynamoDB
func (*UserAppConsent) GetPK ¶
func (c *UserAppConsent) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*UserAppConsent) GetSK ¶
func (c *UserAppConsent) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*UserAppConsent) HasScope ¶
func (c *UserAppConsent) HasScope(scope string) bool
HasScope checks if the consent includes a specific scope
func (*UserAppConsent) IsValid ¶
func (c *UserAppConsent) IsValid() bool
IsValid checks if the consent is still valid
func (*UserAppConsent) Revoke ¶
func (c *UserAppConsent) Revoke()
Revoke marks the consent as revoked
func (UserAppConsent) TableName ¶
func (UserAppConsent) TableName() string
TableName returns the DynamoDB table backing UserAppConsent.
func (*UserAppConsent) UpdateKeys ¶
func (c *UserAppConsent) UpdateKeys() error
UpdateKeys implements BaseModel interface and updates the GSI keys based on the consent data
type UserConversationFolder ¶ added in v1.1.73
type UserConversationFolder string
UserConversationFolder identifies the viewer-visible placement of a DM thread.
const ( // UserConversationFolderInbox is the normal visible inbox placement for a DM thread. UserConversationFolderInbox UserConversationFolder = "INBOX" // UserConversationFolderRequests is the visible folder for inbound DM requests. UserConversationFolderRequests UserConversationFolder = "REQUESTS" // UserConversationFolderDeclined is the visible folder for declined DM requests. UserConversationFolderDeclined UserConversationFolder = "DECLINED" // UserConversationFolderHidden is the hidden/tombstoned viewer-specific folder. UserConversationFolderHidden UserConversationFolder = "HIDDEN" )
type UserConversationState ¶ added in v1.1.73
type UserConversationState struct {
PK string `theorydb:"pk,attr:PK" json:"PK"`
SK string `theorydb:"sk,attr:SK" json:"SK"`
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1SK,omitempty"`
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2SK,omitempty"`
GSI3PK string `theorydb:"index:gsi3,pk,attr:gsi3PK,omitempty" json:"gsi3PK,omitempty"`
GSI3SK string `theorydb:"index:gsi3,sk,attr:gsi3SK,omitempty" json:"gsi3SK,omitempty"`
ViewerID string `theorydb:"attr:viewerID" json:"viewer_id"`
ConversationID string `theorydb:"attr:conversationID" json:"conversation_id"`
CounterpartID string `theorydb:"attr:counterpartID" json:"counterpart_id"`
CounterpartType ConversationParticipantType `theorydb:"attr:counterpartType,omitempty" json:"counterpart_type,omitempty"`
CounterpartAcct string `theorydb:"attr:counterpartAcct,omitempty" json:"counterpart_acct,omitempty"`
CounterpartDomain string `theorydb:"attr:counterpartDomain,omitempty" json:"counterpart_domain,omitempty"`
CounterpartResolvedAt *time.Time `theorydb:"attr:counterpartResolvedAt,omitempty" json:"counterpart_resolved_at,omitempty"`
Folder UserConversationFolder `theorydb:"attr:folder" json:"folder"`
RequestState DmRequestState `theorydb:"attr:requestState,omitempty" json:"request_state,omitempty"`
PreviewStatusID string `theorydb:"attr:previewStatusID,omitempty" json:"preview_status_id,omitempty"`
PreviewStatusPublishedAt time.Time `theorydb:"attr:previewStatusPublishedAt,omitempty" json:"preview_status_published_at,omitempty"`
SortAt time.Time `theorydb:"attr:sortAt" json:"sort_at"`
Unread bool `theorydb:"attr:unread" json:"unread"`
UnreadCount int `theorydb:"attr:unreadCount" json:"unread_count"`
LastReadAt *time.Time `theorydb:"attr:lastReadAt" json:"last_read_at,omitempty"`
DeletedAt *time.Time `theorydb:"attr:deletedAt" json:"deleted_at,omitempty"`
RequestedAt *time.Time `theorydb:"attr:requestedAt" json:"requested_at,omitempty"`
AcceptedAt *time.Time `theorydb:"attr:acceptedAt" json:"accepted_at,omitempty"`
DeclinedAt *time.Time `theorydb:"attr:declinedAt" json:"declined_at,omitempty"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
UserConversationState is the canonical per-user DM state row.
func (*UserConversationState) BeforeCreate ¶ added in v1.1.73
func (s *UserConversationState) BeforeCreate() error
BeforeCreate initializes keys and timestamps before create.
func (*UserConversationState) BeforeUpdate ¶ added in v1.1.73
func (s *UserConversationState) BeforeUpdate() error
BeforeUpdate refreshes keys and timestamps before update.
func (*UserConversationState) GetPK ¶ added in v1.1.73
func (s *UserConversationState) GetPK() string
GetPK returns the partition key.
func (*UserConversationState) GetSK ¶ added in v1.1.73
func (s *UserConversationState) GetSK() string
GetSK returns the sort key.
func (*UserConversationState) LegacyListCursor ¶ added in v1.1.73
func (s *UserConversationState) LegacyListCursor() string
LegacyListCursor returns the sortable cursor shape historically used by conversation list reads.
func (UserConversationState) TableName ¶ added in v1.1.73
func (UserConversationState) TableName() string
TableName returns the DynamoDB table name.
func (*UserConversationState) UnreadQueryVisible ¶ added in v1.1.73
func (s *UserConversationState) UnreadQueryVisible() bool
UnreadQueryVisible reports whether the row should participate in the sparse unread index.
func (*UserConversationState) UpdateKeys ¶ added in v1.1.73
func (s *UserConversationState) UpdateKeys() error
UpdateKeys recalculates the primary and index keys from canonical row fields.
type UserDomainBlock ¶
type UserDomainBlock struct {
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
Username string `theorydb:"attr:username" json:"username"`
Domain string `theorydb:"attr:domain" json:"domain"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// contains filtered or unexported fields
}
UserDomainBlock represents a user-level domain block
func (*UserDomainBlock) GetPK ¶
func (d *UserDomainBlock) GetPK() string
GetPK returns the partition key (required by BaseModel)
func (*UserDomainBlock) GetSK ¶
func (d *UserDomainBlock) GetSK() string
GetSK returns the sort key (required by BaseModel)
func (UserDomainBlock) TableName ¶
func (UserDomainBlock) TableName() string
TableName returns the DynamoDB table backing UserDomainBlock.
func (*UserDomainBlock) UpdateKeys ¶
func (d *UserDomainBlock) UpdateKeys() error
UpdateKeys updates the keys for the user domain block
type UserLogin ¶
type UserLogin struct {
PK string `theorydb:"pk,attr:PK" json:"pk"` // USER#{username}
SK string `theorydb:"sk,attr:SK" json:"sk"` // LOGIN#{timestamp}
Username string `theorydb:"attr:username" json:"username"`
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
Success bool `theorydb:"attr:success" json:"success"`
IPAddress string `theorydb:"attr:ipAddress" json:"ip_address,omitempty"`
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"`
// TTL for automatic cleanup (e.g., 90 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
UserLogin represents a login attempt record
func (*UserLogin) BeforeCreate ¶
BeforeCreate sets up the model before creation
type UserMediaConfig ¶
type UserMediaConfig struct {
// Primary key - using user ID as partition key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "USER_MEDIA_CONFIG#{userID}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "CONFIG"
// Core config data
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
// Processing preferences
VideoProcessingEnabled bool `theorydb:"attr:videoProcessingEnabled" json:"video_processing_enabled"`
AudioProcessingEnabled bool `theorydb:"attr:audioProcessingEnabled" json:"audio_processing_enabled"`
VideoThumbnailsEnabled bool `theorydb:"attr:videoThumbnailsEnabled" json:"video_thumbnails_enabled"`
ContentModerationEnabled bool `theorydb:"attr:contentModerationEnabled" json:"content_moderation_enabled"`
// Limits and quotas
MaxFileSize int64 `theorydb:"attr:maxFileSize" json:"max_file_size"` // bytes
MaxVideoSize int64 `theorydb:"attr:maxVideoSize" json:"max_video_size"` // bytes
MaxAudioSize int64 `theorydb:"attr:maxAudioSize" json:"max_audio_size"` // bytes
MaxImageSize int64 `theorydb:"attr:maxImageSize" json:"max_image_size"` // bytes
MaxVideoDuration int `theorydb:"attr:maxVideoDuration" json:"max_video_duration"` // seconds
MaxDailyUploads int `theorydb:"attr:maxDailyUploads" json:"max_daily_uploads"` // files per day
MaxMonthlyUploads int `theorydb:"attr:maxMonthlyUploads" json:"max_monthly_uploads"` // files per month
MaxStorageUsage int64 `theorydb:"attr:maxStorageUsage" json:"max_storage_usage"` // bytes
MaxBandwidthPerMonth int64 `theorydb:"attr:maxBandwidthPerMonth" json:"max_bandwidth_per_month"` // bytes
// Budget limits (in microdollars - $1 = 1,000,000 microdollars)
MonthlyBudgetMicros int64 `theorydb:"attr:monthlyBudgetMicros" json:"monthly_budget_micros"`
DailyBudgetMicros int64 `theorydb:"attr:dailyBudgetMicros" json:"daily_budget_micros"`
ProcessingBudgetMicros int64 `theorydb:"attr:processingBudgetMicros" json:"processing_budget_micros"` // For MediaConvert, Rekognition, etc.
StorageBudgetMicros int64 `theorydb:"attr:storageBudgetMicros" json:"storage_budget_micros"` // For S3 storage
BandwidthBudgetMicros int64 `theorydb:"attr:bandwidthBudgetMicros" json:"bandwidth_budget_micros"` // For CDN/transfer
// Allowed content types
AllowedImageTypes []string `theorydb:"attr:allowedImageTypes" json:"allowed_image_types"`
AllowedVideoTypes []string `theorydb:"attr:allowedVideoTypes" json:"allowed_video_types"`
AllowedAudioTypes []string `theorydb:"attr:allowedAudioTypes" json:"allowed_audio_types"`
// Processing quality settings
ImageQuality string `theorydb:"attr:imageQuality" json:"image_quality"` // "low", "medium", "high"
VideoQuality string `theorydb:"attr:videoQuality" json:"video_quality"` // "low", "medium", "high"
EnableBlurhash bool `theorydb:"attr:enableBlurhash" json:"enable_blurhash"` // Generate blurhashes for images
EnableThumbnails bool `theorydb:"attr:enableThumbnails" json:"enable_thumbnails"` // Generate thumbnails
// Content moderation settings
ModerationThreshold float64 `theorydb:"attr:moderationThreshold" json:"moderation_threshold"` // 0.0-1.0, above this is flagged
AutoRejectNSFW bool `theorydb:"attr:autoRejectNSFW" json:"auto_reject_nsfw"`
RequiredLabels []string `theorydb:"attr:requiredLabels" json:"required_labels"` // Required content labels
BlockedLabels []string `theorydb:"attr:blockedLabels" json:"blocked_labels"` // Automatically blocked labels
// Plan/tier information
PlanTier string `theorydb:"attr:planTier" json:"plan_tier"` // "free", "basic", "premium", "enterprise"
PlanExpiresAt *time.Time `theorydb:"attr:planExpiresAt" json:"plan_expires_at,omitempty"`
IsTrialUser bool `theorydb:"attr:isTrialUser" json:"is_trial_user"`
TrialExpiresAt *time.Time `theorydb:"attr:trialExpiresAt" json:"trial_expires_at,omitempty"`
// Usage tracking references
CurrentStorageUsage int64 `theorydb:"attr:currentStorageUsage" json:"current_storage_usage"` // bytes
CurrentMonthlyUsage int64 `theorydb:"attr:currentMonthlyUsage" json:"current_monthly_usage"` // bytes processed this month
LastResetAt time.Time `theorydb:"attr:lastResetAt" json:"last_reset_at"` // When monthly counters were last reset
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Version for optimistic locking
ModelVersion int `theorydb:"version,attr:modelVersion" json:"model_version"`
// contains filtered or unexported fields
}
UserMediaConfig represents a user's media processing configuration and limits
func (*UserMediaConfig) AddMonthlyUsage ¶
func (umc *UserMediaConfig) AddMonthlyUsage(bytes int64)
AddMonthlyUsage adds to the monthly usage counter
func (*UserMediaConfig) BeforeCreate ¶
func (umc *UserMediaConfig) BeforeCreate() error
BeforeCreate sets up the model before creation
func (*UserMediaConfig) BeforeUpdate ¶
func (umc *UserMediaConfig) BeforeUpdate() error
BeforeUpdate sets up the model before update
func (*UserMediaConfig) CanAfford ¶
func (umc *UserMediaConfig) CanAfford(costMicros int64, costType string) bool
CanAfford checks if the user can afford a given cost in microdollars
func (*UserMediaConfig) GetMaxSizeForType ¶
func (umc *UserMediaConfig) GetMaxSizeForType(contentType string) int64
GetMaxSizeForType returns the maximum allowed size for a content type
func (*UserMediaConfig) GetPK ¶
func (umc *UserMediaConfig) GetPK() string
GetPK returns the partition key for this user media config
func (*UserMediaConfig) GetSK ¶
func (umc *UserMediaConfig) GetSK() string
GetSK returns the sort key for this user media config
func (*UserMediaConfig) IsAllowedContentType ¶
func (umc *UserMediaConfig) IsAllowedContentType(contentType string) bool
IsAllowedContentType checks if a content type is allowed for this user
func (*UserMediaConfig) IsExpired ¶
func (umc *UserMediaConfig) IsExpired() bool
IsExpired checks if the user's plan has expired
func (*UserMediaConfig) IsTrialExpired ¶
func (umc *UserMediaConfig) IsTrialExpired() bool
IsTrialExpired checks if the user's trial has expired
func (*UserMediaConfig) IsWithinStorageLimit ¶
func (umc *UserMediaConfig) IsWithinStorageLimit(additionalBytes int64) bool
IsWithinStorageLimit checks if adding bytes would exceed storage limit
func (*UserMediaConfig) ResetMonthlyCounters ¶
func (umc *UserMediaConfig) ResetMonthlyCounters()
ResetMonthlyCounters resets monthly usage counters
func (*UserMediaConfig) ShouldResetCounters ¶
func (umc *UserMediaConfig) ShouldResetCounters() bool
ShouldResetCounters checks if monthly counters need to be reset
func (UserMediaConfig) TableName ¶
func (UserMediaConfig) TableName() string
TableName returns the DynamoDB table name for the UserMediaConfig model
func (*UserMediaConfig) UpdateKeys ¶
func (umc *UserMediaConfig) UpdateKeys() error
UpdateKeys ensures all key fields are properly set
func (*UserMediaConfig) UpdateStorageUsage ¶
func (umc *UserMediaConfig) UpdateStorageUsage(deltaBytes int64)
UpdateStorageUsage updates the current storage usage
func (*UserMediaConfig) UpgradePlan ¶
func (umc *UserMediaConfig) UpgradePlan(newTier string, expiresAt *time.Time) error
UpgradePlan upgrades the user to a higher plan tier
func (*UserMediaConfig) Validate ¶
func (umc *UserMediaConfig) Validate() error
Validate performs validation on the UserMediaConfig
type UserPreference ¶
type UserPreference struct {
// Primary key components
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "USER#{username}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "PREFERENCE#{key}"
// Preference data
Username string `theorydb:"attr:username" json:"username"` // Who owns the preference
Key string `theorydb:"attr:key" json:"key"` // Preference key (e.g., "language", "theme")
Value string `theorydb:"attr:value" json:"value"` // Preference value (JSON encoded)
// Metadata
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
UserPreference represents a single user preference key-value pair Key pattern: PK=USER#{username}, SK=PREFERENCE#{key}
func (*UserPreference) BeforeCreate ¶
func (p *UserPreference) BeforeCreate() error
BeforeCreate prepares the UserPreference for creation
func (UserPreference) TableName ¶
func (UserPreference) TableName() string
TableName returns the DynamoDB table name
func (*UserPreference) UpdateKeys ¶
func (p *UserPreference) UpdateKeys()
UpdateKeys updates the primary key fields based on the current data
type UserPreferences ¶
type UserPreferences struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"pk"`
SK string `theorydb:"sk,attr:SK" json:"sk"`
// User preferences fields (matching storage.UserPreferences exactly)
Language string `theorydb:"attr:language" json:"language"`
DefaultPostingVisibility string `theorydb:"attr:defaultPostingVisibility" json:"default_posting_visibility"`
DefaultMediaSensitive bool `theorydb:"attr:defaultMediaSensitive" json:"default_media_sensitive"`
DirectMessagesFrom string `theorydb:"attr:directMessagesFrom" json:"direct_messages_from"`
ExpandSpoilers bool `theorydb:"attr:expandSpoilers" json:"expand_spoilers"`
ExpandMedia string `theorydb:"attr:expandMedia" json:"expand_media"`
AutoplayGifs bool `theorydb:"attr:autoplayGifs" json:"autoplay_gifs"`
ShowFollowCounts bool `theorydb:"attr:showFollowCounts" json:"show_follow_counts"`
PreferredTimelineOrder string `theorydb:"attr:preferredTimelineOrder" json:"preferred_timeline_order"`
SearchSuggestionsEnabled bool `theorydb:"attr:searchSuggestionsEnabled" json:"search_suggestions_enabled"`
PersonalizedSearchEnabled bool `theorydb:"attr:personalizedSearchEnabled" json:"personalized_search_enabled"`
ReblogFilters map[string]bool `theorydb:"attr:reblogFilters" json:"reblog_filters,omitempty"`
StreamingDefaultQuality string `theorydb:"attr:streamingDefaultQuality" json:"streaming_default_quality"`
StreamingAutoQuality bool `theorydb:"attr:streamingAutoQuality" json:"streaming_auto_quality"`
StreamingPreloadNext bool `theorydb:"attr:streamingPreloadNext" json:"streaming_preload_next"`
StreamingDataSaver bool `theorydb:"attr:streamingDataSaver" json:"streaming_data_saver"`
// Metadata
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// Username for key generation
Username string `json:"-"`
// contains filtered or unexported fields
}
UserPreferences represents user preferences in DynamoDB
func (*UserPreferences) FromStorage ¶
func (up *UserPreferences) FromStorage(username string, prefs *UserPreferencesStorage)
FromStorage populates the DynamORM model from UserPreferencesStorage
func (UserPreferences) TableName ¶
func (UserPreferences) TableName() string
TableName returns the DynamoDB table name for user preferences.
func (*UserPreferences) ToStorage ¶
func (up *UserPreferences) ToStorage() *UserPreferencesStorage
ToStorage converts the DynamORM model to UserPreferencesStorage
func (*UserPreferences) UpdateKeys ¶
func (up *UserPreferences) UpdateKeys()
UpdateKeys sets the DynamoDB keys for user preferences
type UserPreferencesStorage ¶
type UserPreferencesStorage struct {
Language string `json:"language"`
DefaultPostingVisibility string `json:"default_posting_visibility"`
DefaultMediaSensitive bool `json:"default_media_sensitive"`
DirectMessagesFrom string `json:"direct_messages_from"`
ExpandSpoilers bool `json:"expand_spoilers"`
ExpandMedia string `json:"expand_media"`
AutoplayGifs bool `json:"autoplay_gifs"`
ShowFollowCounts bool `json:"show_follow_counts"`
PreferredTimelineOrder string `json:"preferred_timeline_order"`
SearchSuggestionsEnabled bool `json:"search_suggestions_enabled"`
PersonalizedSearchEnabled bool `json:"personalized_search_enabled"`
ReblogFilters map[string]bool `json:"reblog_filters,omitempty"`
StreamingDefaultQuality string `json:"streaming_default_quality"`
StreamingAutoQuality bool `json:"streaming_auto_quality"`
StreamingPreloadNext bool `json:"streaming_preload_next"`
StreamingDataSaver bool `json:"streaming_data_saver"`
}
UserPreferencesStorage represents the data structure for user preferences This mirrors storage.UserPreferences but avoids circular dependencies
func GetDefaultPreferences ¶
func GetDefaultPreferences() *UserPreferencesStorage
GetDefaultPreferences returns the default user preferences
func (UserPreferencesStorage) TableName ¶
func (UserPreferencesStorage) TableName() string
TableName returns the DynamoDB table backing UserPreferencesStorage.
type VAPIDKeyRecord ¶
type VAPIDKeyRecord struct {
PK string `theorydb:"pk,attr:PK"` // INSTANCE#CONFIG
SK string `theorydb:"sk,attr:SK"` // VAPID_KEYS
Data map[string]any `theorydb:"attr:data" json:"data"` // The actual VAPID keys data (storage.VAPIDKeys-compatible)
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// contains filtered or unexported fields
}
VAPIDKeyRecord represents VAPID keys stored in DynamoDB
func (*VAPIDKeyRecord) GetPK ¶
func (v *VAPIDKeyRecord) GetPK() string
GetPK returns the partition key
func (VAPIDKeyRecord) TableName ¶
func (VAPIDKeyRecord) TableName() string
TableName returns the DynamoDB table backing VAPIDKeyRecord.
func (*VAPIDKeyRecord) UpdateKeys ¶
func (v *VAPIDKeyRecord) UpdateKeys() error
UpdateKeys updates any GSI keys - VAPID doesn't use GSIs so this is no-op
type Vouch ¶
type Vouch struct {
// Primary keys
PK string `theorydb:"pk,attr:PK"`
SK string `theorydb:"sk,attr:SK"`
// GSI1 for vouches given by an actor
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty"`
// GSI2 for vouches received by an actor
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty"`
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty"`
// Data fields
VouchData string `theorydb:"attr:vouchData" json:"vouch_data"` // JSON encoded vouch
Active bool `theorydb:"attr:active" json:"active"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"ttl"` // Unix timestamp for TTL
// contains filtered or unexported fields
}
Vouch represents a reputation vouch between actors
type WalletChallenge ¶
type WalletChallenge struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// Business fields matching storage.WalletChallenge
ID string `theorydb:"attr:id" json:"id"`
Username string `theorydb:"attr:username" json:"username,omitempty"`
Address string `theorydb:"attr:address" json:"address"`
ChainID int `theorydb:"attr:chainID" json:"chain_id"`
Nonce string `theorydb:"attr:nonce" json:"nonce"`
Message string `theorydb:"attr:message" json:"message"`
IssuedAt time.Time `theorydb:"attr:issuedAt" json:"issued_at"`
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Used bool `theorydb:"attr:used" json:"used"` // Set after first verification (wallet/verify)
Spent bool `theorydb:"attr:spent" json:"spent"` // Set after second verification (wallet/link)
RegistrationCompleted bool `theorydb:"attr:registrationCompleted" json:"registration_completed,omitempty"` // Set after account registration succeeds.
// contains filtered or unexported fields
}
WalletChallenge represents a challenge for wallet authentication
func (*WalletChallenge) BeforeCreate ¶
func (w *WalletChallenge) BeforeCreate() error
BeforeCreate sets up the keys and TTL before creating
func (*WalletChallenge) GetPK ¶
func (w *WalletChallenge) GetPK() string
GetPK returns the partition key
func (WalletChallenge) TableName ¶
func (WalletChallenge) TableName() string
TableName returns the DynamoDB table name
func (*WalletChallenge) UpdateKeys ¶
func (w *WalletChallenge) UpdateKeys() error
UpdateKeys updates the primary and sort keys based on the model data
type WalletCredential ¶
type WalletCredential struct {
// DynamoDB keys - Primary key is user's credentials
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Business fields matching storage.WalletCredential
Username string `theorydb:"attr:username" json:"username"`
Address string `theorydb:"attr:address" json:"address"`
ChainID int `theorydb:"attr:chainID" json:"chain_id"`
Type string `theorydb:"attr:type" json:"type"` // ethereum, solana, etc.
ENS string `theorydb:"attr:ens" json:"ens,omitempty"`
LinkedAt time.Time `theorydb:"attr:linkedAt" json:"linked_at"`
LastUsed time.Time `theorydb:"attr:lastUsed" json:"last_used"`
// contains filtered or unexported fields
}
WalletCredential represents a linked wallet
func (*WalletCredential) BeforeCreate ¶
func (w *WalletCredential) BeforeCreate() error
BeforeCreate sets up the keys before creating
func (*WalletCredential) BeforeUpdate ¶
func (w *WalletCredential) BeforeUpdate() error
BeforeUpdate updates the last used timestamp
func (*WalletCredential) GetPK ¶
func (w *WalletCredential) GetPK() string
GetPK returns the partition key
func (*WalletCredential) GetSK ¶
func (w *WalletCredential) GetSK() string
GetSK returns the sort key
func (WalletCredential) TableName ¶
func (WalletCredential) TableName() string
TableName returns the DynamoDB table name
func (*WalletCredential) UpdateKeys ¶
func (w *WalletCredential) UpdateKeys() error
UpdateKeys updates the primary and sort keys based on the model data
type WalletIndex ¶
type WalletIndex struct {
// DynamoDB keys
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
// Business fields
Username string `theorydb:"attr:username" json:"username"`
WalletType string `theorydb:"attr:walletType" json:"wallet_type"` // Need to store these for BeforeCreate
Address string `theorydb:"attr:address" json:"address"`
// contains filtered or unexported fields
}
WalletIndex represents a reverse index for wallet->user lookup
func (*WalletIndex) BeforeCreate ¶
func (w *WalletIndex) BeforeCreate() error
BeforeCreate sets up the keys before creation
func (WalletIndex) TableName ¶
func (WalletIndex) TableName() string
TableName returns the DynamoDB table backing WalletIndex.
func (*WalletIndex) UpdateKeys ¶
func (w *WalletIndex) UpdateKeys(walletType, address, username string)
UpdateKeys updates the primary and sort keys based on the model data
type WebAuthnChallenge ¶
type WebAuthnChallenge struct {
// DynamoDB keys - MUST match legacy exactly
PK string `theorydb:"pk,attr:PK" json:"-"` // CHALLENGE#challenge
SK string `theorydb:"sk,attr:SK" json:"-"` // WEBAUTHN
// Core fields from legacy storage.WebAuthnChallenge
Challenge string `theorydb:"attr:challenge" json:"challenge"`
UserID string `theorydb:"attr:userID" json:"user_id"`
SessionData []byte `theorydb:"attr:sessionData" json:"session_data"` // Serialized session data
ExpiresAt time.Time `theorydb:"attr:expiresAt" json:"expires_at"`
Type string `theorydb:"attr:type" json:"type"` // "registration" or "authentication"
// Additional fields for DynamoDB
ItemType string `theorydb:"attr:itemType" json:"ItemType"` // "WebAuthnChallenge"
// TTL field for automatic expiration
TTL int64 `theorydb:"ttl,attr:ttl" json:"-"`
// contains filtered or unexported fields
}
WebAuthnChallenge represents a temporary challenge for WebAuthn registration/authentication
func (*WebAuthnChallenge) BeforeCreate ¶
func (w *WebAuthnChallenge) BeforeCreate() error
BeforeCreate sets up the keys and TTL before creating
func (*WebAuthnChallenge) GetPK ¶
func (w *WebAuthnChallenge) GetPK() string
GetPK returns the partition key
func (*WebAuthnChallenge) GetSK ¶
func (w *WebAuthnChallenge) GetSK() string
GetSK returns the sort key
func (WebAuthnChallenge) TableName ¶
func (WebAuthnChallenge) TableName() string
TableName returns the DynamoDB table name
func (*WebAuthnChallenge) UpdateKeys ¶
func (w *WebAuthnChallenge) UpdateKeys() error
UpdateKeys updates the primary and sort keys based on the model data
type WebAuthnCredential ¶
type WebAuthnCredential struct {
// Canonical DynamoDB keys for the account-scoped WebAuthn credential row.
PK string `theorydb:"pk,attr:PK" json:"-"` // USER#username
SK string `theorydb:"sk,attr:SK" json:"-"` // WEBAUTHN_CRED#credentialID
// GSI for credential lookup by ID
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"-"`
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"-"`
// Persisted WebAuthn credential fields.
ID string `theorydb:"attr:id" json:"id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
PublicKey []byte `theorydb:"attr:publicKey" json:"public_key"`
AttestationType string `theorydb:"attr:attestationType" json:"attestation_type"`
AAGUID []byte `theorydb:"attr:aaguid" json:"aaguid"`
SignCount uint32 `theorydb:"attr:signCount" json:"sign_count"`
CloneWarning bool `theorydb:"attr:cloneWarning" json:"clone_warning"`
BackupEligible bool `theorydb:"attr:backupEligible" json:"backup_eligible"`
BackupState bool `theorydb:"attr:backupState" json:"backup_state"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
LastUsedAt time.Time `theorydb:"attr:lastUsedAt" json:"last_used_at"`
Name string `theorydb:"attr:name" json:"name"` // User-friendly name
// Additional fields for DynamoDB queries
Type string `theorydb:"attr:type" json:"Type"` // "WebAuthnCredential"
// contains filtered or unexported fields
}
WebAuthnCredential represents a WebAuthn credential for passwordless authentication
func (*WebAuthnCredential) BeforeCreate ¶
func (w *WebAuthnCredential) BeforeCreate() error
BeforeCreate sets up the keys before creating
func (*WebAuthnCredential) BeforeUpdate ¶
func (w *WebAuthnCredential) BeforeUpdate() error
BeforeUpdate updates the last used timestamp
func (*WebAuthnCredential) GetPK ¶
func (w *WebAuthnCredential) GetPK() string
GetPK returns the partition key
func (*WebAuthnCredential) GetSK ¶
func (w *WebAuthnCredential) GetSK() string
GetSK returns the sort key
func (WebAuthnCredential) TableName ¶
func (WebAuthnCredential) TableName() string
TableName returns the DynamoDB table name
func (*WebAuthnCredential) UpdateKeys ¶
func (w *WebAuthnCredential) UpdateKeys() error
UpdateKeys updates the primary and sort keys based on the model data
type WebSocketConnection ¶
type WebSocketConnection struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // CONN#{connectionID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // CONN#{connectionID}
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk,omitempty"` // USER#{userID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk,omitempty"` // CONN#{timestamp}
// GSI2 for state-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2pk"` // STATE#{state}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2sk"` // CONN#{connectionID}
// Business fields
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"`
UserID string `theorydb:"attr:userID,omitempty" json:"user_id,omitempty"`
Username string `theorydb:"attr:username,omitempty" json:"username,omitempty"`
Streams []string `theorydb:"attr:streams" json:"streams"` // subscribed streams
Established time.Time `theorydb:"attr:established" json:"established"`
LastActivity time.Time `theorydb:"attr:lastActivity" json:"last_activity"`
// Connection lifecycle fields
State ConnectionState `theorydb:"attr:state" json:"state"`
StateChangedAt time.Time `theorydb:"attr:stateChangedAt" json:"state_changed_at"`
CloseReason string `theorydb:"attr:closeReason" json:"close_reason,omitempty"`
CloseCode int `theorydb:"attr:closeCode" json:"close_code,omitempty"`
RetryCount int `theorydb:"attr:retryCount" json:"retry_count"`
MaxRetries int `theorydb:"attr:maxRetries" json:"max_retries"`
// Connection metadata and metrics
Metrics ConnectionMetrics `theorydb:"attr:metrics" json:"metrics"`
Info ConnectionInfo `theorydb:"attr:info" json:"info"`
// Resource management
IdleTimeout time.Duration `theorydb:"attr:idleTimeout" json:"idle_timeout"`
MaxMessageSize int64 `theorydb:"attr:maxMessageSize" json:"max_message_size"`
RateLimit int `theorydb:"attr:rateLimit" json:"rate_limit"` // messages per minute
CurrentRate int `theorydb:"attr:currentRate" json:"current_rate"`
RateLimitReset time.Time `theorydb:"attr:rateLimitReset" json:"rate_limit_reset"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
WebSocketConnection represents a WebSocket connection with complete lifecycle management
func (*WebSocketConnection) CalculateConnectionQuality ¶
func (w *WebSocketConnection) CalculateConnectionQuality() float64
CalculateConnectionQuality computes a quality score based on metrics
func (*WebSocketConnection) GetPK ¶
func (w *WebSocketConnection) GetPK() string
GetPK returns the partition key
func (*WebSocketConnection) GetSK ¶
func (w *WebSocketConnection) GetSK() string
GetSK returns the sort key
func (*WebSocketConnection) IncrementError ¶
func (w *WebSocketConnection) IncrementError(errorMsg string)
IncrementError increments the error counter and updates the last error
func (*WebSocketConnection) IsActive ¶
func (w *WebSocketConnection) IsActive(threshold time.Duration) bool
IsActive returns true if the connection has been active recently
func (*WebSocketConnection) IsHealthy ¶
func (w *WebSocketConnection) IsHealthy() bool
IsHealthy returns true if the connection is in a healthy state
func (*WebSocketConnection) RecordMessage ¶
func (w *WebSocketConnection) RecordMessage(sent bool, bytes int64)
RecordMessage records statistics for sent/received messages
func (*WebSocketConnection) RecordPing ¶
func (w *WebSocketConnection) RecordPing()
RecordPing records a ping timestamp
func (*WebSocketConnection) RecordPong ¶
func (w *WebSocketConnection) RecordPong()
RecordPong records a pong timestamp and calculates latency
func (*WebSocketConnection) ShouldRetry ¶
func (w *WebSocketConnection) ShouldRetry() bool
ShouldRetry returns true if the connection should attempt to reconnect
func (*WebSocketConnection) TableName ¶
func (w *WebSocketConnection) TableName() string
TableName returns the DynamoDB table backing WebSocketConnection.
func (*WebSocketConnection) UpdateKeys ¶
func (w *WebSocketConnection) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
func (*WebSocketConnection) UpdateState ¶
func (w *WebSocketConnection) UpdateState(newState ConnectionState)
UpdateState changes the connection state and records the timestamp
type WebSocketCostAggregation ¶
type WebSocketCostAggregation struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "WS_AGG#{period}#{operation_type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "window#{windowStart}"
// GSI1 - User aggregation queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "WS_USER_AGG#{user_id}#{period}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{operation_type}"
// Aggregation details
Period string `theorydb:"attr:period" json:"period"` // minute, hour, day, week, month
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // Same as WebSocketCostRecord.OperationType
UserID string `theorydb:"attr:userID" json:"user_id,omitempty"` // Specific user or empty for global
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"` // Start of aggregation window
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"` // End of aggregation window
// Connection metrics
TotalConnections int64 `theorydb:"attr:totalConnections" json:"total_connections"` // Total connections in period
UniqueUsers int64 `theorydb:"attr:uniqueUsers" json:"unique_users"` // Unique users connected
AverageConnectionDuration float64 `theorydb:"attr:averageConnectionDuration" json:"average_connection_duration"` // Average connection time in minutes
MaxConcurrentConnections int `theorydb:"attr:maxConcurrentConnections" json:"max_concurrent_connections"` // Peak concurrent connections
TotalConnectionMinutes int64 `theorydb:"attr:totalConnectionMinutes" json:"total_connection_minutes"` // Total connection time
// Message metrics
TotalMessagesIn int64 `theorydb:"attr:totalMessagesIn" json:"total_messages_in"` // Messages received from clients
TotalMessagesOut int64 `theorydb:"attr:totalMessagesOut" json:"total_messages_out"` // Messages sent to clients
TotalMessageBytes int64 `theorydb:"attr:totalMessageBytes" json:"total_message_bytes"` // Total message data transferred
AverageMessageSize float64 `theorydb:"attr:averageMessageSize" json:"average_message_size"` // Average message size
MessageThroughputPerSec float64 `theorydb:"attr:messageThroughputPerSec" json:"message_throughput_per_sec"` // Messages per second
// Stream metrics
TotalStreamSubscriptions int64 `theorydb:"attr:totalStreamSubscriptions" json:"total_stream_subscriptions"` // Stream subscriptions created
UniqueStreamsUsed int64 `theorydb:"attr:uniqueStreamsUsed" json:"unique_streams_used"` // Number of unique streams
StreamPopularity map[string]int64 `theorydb:"attr:streamPopularity" json:"stream_popularity"` // Stream name -> subscription count
StreamTypeBreakdown map[string]int64 `theorydb:"attr:streamTypeBreakdown" json:"stream_type_breakdown"` // Stream type -> count
// Cost aggregations (in microcents)
TotalAPIGatewayConnectionCost int64 `theorydb:"attr:totalAPIGatewayConnectionCost" json:"total_api_gateway_connection_cost"`
TotalAPIGatewayMessageCost int64 `theorydb:"attr:totalAPIGatewayMessageCost" json:"total_api_gateway_message_cost"`
TotalLambdaExecutionCost int64 `theorydb:"attr:totalLambdaExecutionCost" json:"total_lambda_execution_cost"`
TotalDynamoDBCost int64 `theorydb:"attr:totalDynamoDBCost" json:"total_dynamodb_cost"`
TotalDataTransferCost int64 `theorydb:"attr:totalDataTransferCost" json:"total_data_transfer_cost"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
// Performance metrics
AverageProcessingTime float64 `theorydb:"attr:averageProcessingTime" json:"average_processing_time"` // Average processing time in ms
AverageResponseLatency float64 `theorydb:"attr:averageResponseLatency" json:"average_response_latency"` // Average response latency in ms
AverageMemoryUsage float64 `theorydb:"attr:averageMemoryUsage" json:"average_memory_usage"` // Average memory usage in MB
// Cost efficiency metrics
CostPerConnection float64 `theorydb:"attr:costPerConnection" json:"cost_per_connection"` // Average cost per connection
CostPerMessage float64 `theorydb:"attr:costPerMessage" json:"cost_per_message"` // Average cost per message
CostPerMinute float64 `theorydb:"attr:costPerMinute" json:"cost_per_minute"` // Average cost per connection minute
CostPerUser float64 `theorydb:"attr:costPerUser" json:"cost_per_user"` // Average cost per unique user
// Error and reliability metrics
FailedConnections int64 `theorydb:"attr:failedConnections" json:"failed_connections"` // Connections that failed to establish
DroppedConnections int64 `theorydb:"attr:droppedConnections" json:"dropped_connections"` // Connections dropped unexpectedly
MessageDeliveryFailures int64 `theorydb:"attr:messageDeliveryFailures" json:"message_delivery_failures"` // Failed message deliveries
ErrorRate float64 `theorydb:"attr:errorRate" json:"error_rate"` // Percentage of operations that failed
// User behavior metrics
UserEngagementScore float64 `theorydb:"attr:userEngagementScore" json:"user_engagement_score"` // Engagement score based on activity
TopUsers []string `theorydb:"attr:topUsers" json:"top_users"` // Most active users by cost/usage
UserBehaviorPatterns map[string]float64 `theorydb:"attr:userBehaviorPatterns" json:"user_behavior_patterns"` // Usage patterns by behavior type
// Cost breakdown by user tier
CostByTier map[string]*WebSocketTierCostStats `theorydb:"attr:costByTier" json:"cost_by_tier,omitempty"`
// Percentiles for cost and performance distribution
CostPercentiles map[string]float64 `theorydb:"attr:costPercentiles" json:"cost_percentiles,omitempty"` // p50, p90, p95, p99
LatencyPercentiles map[string]float64 `theorydb:"attr:latencyPercentiles" json:"latency_percentiles,omitempty"` // p50, p90, p95, p99
ConnectionDurationPercentiles map[string]float64 `theorydb:"attr:connectionDurationPercentiles" json:"connection_duration_percentiles,omitempty"` // p50, p90, p95, p99
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL (longer for aggregated data)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"`
// contains filtered or unexported fields
}
WebSocketCostAggregation represents pre-computed WebSocket cost aggregations
func (*WebSocketCostAggregation) BeforeCreate ¶
func (w *WebSocketCostAggregation) BeforeCreate() error
BeforeCreate for WebSocketCostAggregation
func (*WebSocketCostAggregation) BeforeUpdate ¶
func (w *WebSocketCostAggregation) BeforeUpdate() error
BeforeUpdate for WebSocketCostAggregation
func (*WebSocketCostAggregation) GetPK ¶
func (w *WebSocketCostAggregation) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*WebSocketCostAggregation) GetSK ¶
func (w *WebSocketCostAggregation) GetSK() string
GetSK returns the sort key for BaseModel interface
func (WebSocketCostAggregation) TableName ¶
func (WebSocketCostAggregation) TableName() string
TableName returns the DynamoDB table backing WebSocketCostAggregation.
func (*WebSocketCostAggregation) UpdateKeys ¶
func (w *WebSocketCostAggregation) UpdateKeys() error
UpdateKeys sets up all keys (PK, SK, GSI keys) for the WebSocketCostAggregation
func (*WebSocketCostAggregation) Validate ¶
func (w *WebSocketCostAggregation) Validate() error
Validate for WebSocketCostAggregation
type WebSocketCostBreakdown ¶
type WebSocketCostBreakdown struct {
OperationType string
APIGatewayConnectionCost int64
APIGatewayMessageCost int64
LambdaExecutionCost int64
DataTransferCost int64
TotalCostMicroCents int64
}
WebSocketCostBreakdown represents a cost calculation result
func CalculateWebSocketCosts ¶
func CalculateWebSocketCosts(operationType string, connectionMinutes, messageCount int64, dataMB float64, lambdaDurationMs int64) *WebSocketCostBreakdown
CalculateWebSocketCosts calculates costs for WebSocket operations
func (WebSocketCostBreakdown) TableName ¶
func (WebSocketCostBreakdown) TableName() string
TableName returns the DynamoDB table backing WebSocketCostBreakdown.
type WebSocketCostBudget ¶
type WebSocketCostBudget struct {
// Primary key
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "WS_BUDGET#{user_id}#{period}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "BUDGET#{period}"
// GSI1 - User budget queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "WS_USER_BUDGET#{user_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{period}#{status}"
// Budget configuration
UserID string `theorydb:"attr:userID" json:"user_id"`
Username string `theorydb:"attr:username" json:"username"`
Period string `theorydb:"attr:period" json:"period"` // daily, weekly, monthly
BudgetMicroCents int64 `theorydb:"attr:budgetMicroCents" json:"budget_micro_cents"` // Budget limit in microcents
WindowStart time.Time `theorydb:"attr:windowStart" json:"window_start"` // Budget period start
WindowEnd time.Time `theorydb:"attr:windowEnd" json:"window_end"` // Budget period end
// Current usage tracking
UsedMicroCents int64 `theorydb:"attr:usedMicroCents" json:"used_micro_cents"` // Currently used amount
RemainingMicroCents int64 `theorydb:"attr:remainingMicroCents" json:"remaining_micro_cents"` // Remaining budget
ConnectionMinutesUsed int64 `theorydb:"attr:connectionMinutesUsed" json:"connection_minutes_used"` // Total connection time used
MessagesUsed int64 `theorydb:"attr:messagesUsed" json:"messages_used"` // Total messages sent/received
ActiveConnections int `theorydb:"attr:activeConnections" json:"active_connections"` // Current active connections
MaxConcurrentConnections int `theorydb:"attr:maxConcurrentConnections" json:"max_concurrent_connections"` // Max concurrent connections allowed
// Budget status
Status string `theorydb:"attr:status" json:"status"` // active, warning, exceeded, suspended
UsagePercent float64 `theorydb:"attr:usagePercent" json:"usage_percent"` // Percentage of budget used
// Alerts and limits
AlertThresholds []int `theorydb:"attr:alertThresholds" json:"alert_thresholds"` // Alert at these usage percentages (e.g., [50, 75, 90])
AlertsSent []string `theorydb:"attr:alertsSent" json:"alerts_sent,omitempty"` // Track which alerts have been sent
SuspendAt int `theorydb:"attr:suspendAt" json:"suspend_at"` // Suspend connections at this usage percentage
LastAlertSent time.Time `theorydb:"attr:lastAlertSent" json:"last_alert_sent,omitempty"` // Last time an alert was sent
// Rate limiting
ConnectionsPerMinute int `theorydb:"attr:connectionsPerMinute" json:"connections_per_minute"` // Max new connections per minute
MessagesPerMinute int `theorydb:"attr:messagesPerMinute" json:"messages_per_minute"` // Max messages per minute
// Billing tier
BillingTier string `theorydb:"attr:billingTier" json:"billing_tier"` // free, basic, premium, enterprise
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL - refresh budgets periodically
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
WebSocketCostBudget represents per-user WebSocket usage budgets
func (*WebSocketCostBudget) BeforeCreate ¶
func (w *WebSocketCostBudget) BeforeCreate() error
BeforeCreate for WebSocketCostBudget
func (*WebSocketCostBudget) BeforeUpdate ¶
func (w *WebSocketCostBudget) BeforeUpdate() error
BeforeUpdate for WebSocketCostBudget
func (*WebSocketCostBudget) GetPK ¶
func (w *WebSocketCostBudget) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*WebSocketCostBudget) GetSK ¶
func (w *WebSocketCostBudget) GetSK() string
GetSK returns the sort key for BaseModel interface
func (WebSocketCostBudget) TableName ¶
func (WebSocketCostBudget) TableName() string
TableName returns the DynamoDB table backing WebSocketCostBudget.
func (*WebSocketCostBudget) UpdateKeys ¶
func (w *WebSocketCostBudget) UpdateKeys() error
UpdateKeys sets up all keys (PK, SK, GSI keys) for the WebSocketCostBudget
func (*WebSocketCostBudget) Validate ¶
func (w *WebSocketCostBudget) Validate() error
Validate for WebSocketCostBudget
type WebSocketCostRecord ¶
type WebSocketCostRecord struct {
// Primary key - using operation type and timestamp for optimal access patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // Format: "WS_COST#{operation_type}"
SK string `theorydb:"sk,attr:SK" json:"sk"` // Format: "ts#{timestamp}#{id}"
// GSI1 - Connection-based queries
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"` // Format: "WS_CONN#{connection_id}"
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"` // Format: "{timestamp}#{operation_type}#{id}"
// GSI2 - User-based queries
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk,omitempty"` // Format: "WS_USER#{user_id}"
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk,omitempty"` // Format: "{timestamp}#{operation_type}#{id}"
// Core cost tracking data
ID string `theorydb:"attr:id" json:"id"`
OperationType string `theorydb:"attr:operationType" json:"operation_type"` // connect, disconnect, message_in, message_out, idle_time
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"` // API Gateway connection ID
UserID string `theorydb:"attr:userID,omitempty" json:"user_id,omitempty"` // User associated with connection
Username string `theorydb:"attr:username,omitempty" json:"username,omitempty"` // Username for easier queries
Timestamp time.Time `theorydb:"attr:timestamp" json:"timestamp"`
// Connection details
ConnectionDurationMs int64 `theorydb:"attr:connectionDurationMs" json:"connection_duration_ms,omitempty"` // For connection lifecycle tracking
IdleTimeMs int64 `theorydb:"attr:idleTimeMs" json:"idle_time_ms,omitempty"` // Time connection was idle
MessageCount int `theorydb:"attr:messageCount" json:"message_count,omitempty"` // Number of messages (for message operations)
MessageSizeBytes int64 `theorydb:"attr:messageSizeBytes" json:"message_size_bytes,omitempty"` // Size of messages sent/received
StreamCount int `theorydb:"attr:streamCount" json:"stream_count,omitempty"` // Number of streams subscribed
// AWS costs in microcents for precision
// API Gateway WebSocket costs: $0.25 per million connection minutes, $1.00 per million messages
APIGatewayConnectionCost int64 `theorydb:"attr:apiGatewayConnectionCost" json:"api_gateway_connection_cost"` // Connection time cost in microcents
APIGatewayMessageCost int64 `theorydb:"attr:apiGatewayMessageCost" json:"api_gateway_message_cost"` // Message sending cost in microcents
LambdaExecutionCost int64 `theorydb:"attr:lambdaExecutionCost" json:"lambda_execution_cost"` // Lambda execution cost in microcents
DynamoDBCost int64 `theorydb:"attr:dynamoDBCost" json:"dynamodb_cost"` // DynamoDB operations cost in microcents
DataTransferCost int64 `theorydb:"attr:dataTransferCost" json:"data_transfer_cost"` // Data transfer cost in microcents
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"` // Total cost in microcents
// Cost breakdown by category
ConnectionMinuteCost int64 `theorydb:"attr:connectionMinuteCost" json:"connection_minute_cost"` // Cost per minute of connection
MessageProcessingCost int64 `theorydb:"attr:messageProcessingCost" json:"message_processing_cost"` // Cost per message processed
SubscriptionCost int64 `theorydb:"attr:subscriptionCost" json:"subscription_cost"` // Cost for managing subscriptions
// Performance metrics
ProcessingTimeMs int64 `theorydb:"attr:processingTimeMs" json:"processing_time_ms"` // Time to process the operation
ResponseLatencyMs int64 `theorydb:"attr:responseLatencyMs" json:"response_latency_ms,omitempty"` // Response latency for messages
MemoryUsedMB float64 `theorydb:"attr:memoryUsedMB" json:"memory_used_mb,omitempty"` // Lambda memory usage
// Service information
ServiceName string `theorydb:"attr:serviceName" json:"service_name"` // streaming or stream-router
RequestID string `theorydb:"attr:requestID" json:"request_id"` // AWS Request ID
FunctionName string `theorydb:"attr:functionName" json:"function_name"` // Lambda function name
FunctionVersion string `theorydb:"attr:functionVersion" json:"function_version"` // Lambda function version
// Connection context
ClientIP string `theorydb:"attr:clientIP" json:"client_ip,omitempty"` // Client IP address
UserAgent string `theorydb:"attr:userAgent" json:"user_agent,omitempty"` // User agent string
ConnectionSource string `theorydb:"attr:connectionSource" json:"connection_source"` // web, mobile, api
AuthMethod string `theorydb:"attr:authMethod" json:"auth_method,omitempty"` // oauth, bearer, anonymous
// Stream information
ActiveStreams []string `theorydb:"attr:activeStreams" json:"active_streams,omitempty"` // Streams active during operation
StreamTypes []string `theorydb:"attr:streamTypes" json:"stream_types,omitempty"` // Types of streams (public, user, notification)
// Additional metadata
Tags map[string]string `theorydb:"attr:tags" json:"tags,omitempty"`
Properties map[string]interface{} `theorydb:"attr:properties" json:"properties,omitempty"`
// Estimated cost in dollars for easy display
EstimatedCostDollars float64 `theorydb:"attr:estimatedCostDollars" json:"estimated_cost_dollars"`
// Timestamps
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for automatic cleanup (30 days for detailed records)
ExpiresAt int64 `theorydb:"ttl,attr:ttl" json:"expires_at"` // Unix timestamp
// contains filtered or unexported fields
}
WebSocketCostRecord represents detailed cost tracking for WebSocket operations
func (*WebSocketCostRecord) AddTag ¶
func (w *WebSocketCostRecord) AddTag(key, value string)
AddTag adds a tag to the cost tracking
func (*WebSocketCostRecord) BeforeCreate ¶
func (w *WebSocketCostRecord) BeforeCreate() error
BeforeCreate sets up the WebSocketCostRecord model before creation
func (*WebSocketCostRecord) BeforeUpdate ¶
func (w *WebSocketCostRecord) BeforeUpdate() error
BeforeUpdate sets up the WebSocketCostRecord model before update
func (*WebSocketCostRecord) GetPK ¶
func (w *WebSocketCostRecord) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*WebSocketCostRecord) GetProperty ¶
func (w *WebSocketCostRecord) GetProperty(key string) (interface{}, bool)
GetProperty gets a custom property
func (*WebSocketCostRecord) GetSK ¶
func (w *WebSocketCostRecord) GetSK() string
GetSK returns the sort key for BaseModel interface
func (*WebSocketCostRecord) SetProperty ¶
func (w *WebSocketCostRecord) SetProperty(key string, value interface{})
SetProperty sets a custom property
func (WebSocketCostRecord) TableName ¶
func (WebSocketCostRecord) TableName() string
TableName returns the DynamoDB table backing WebSocketCostRecord.
func (*WebSocketCostRecord) UpdateKeys ¶
func (w *WebSocketCostRecord) UpdateKeys() error
UpdateKeys sets up all keys (PK, SK, GSI keys) for the WebSocketCostRecord
func (*WebSocketCostRecord) Validate ¶
func (w *WebSocketCostRecord) Validate() error
Validate performs validation on the WebSocketCostRecord
type WebSocketCostRecordBuilder ¶
type WebSocketCostRecordBuilder struct {
// contains filtered or unexported fields
}
WebSocketCostRecordBuilder helps create WebSocket cost tracking records
func NewWebSocketCostRecordBuilder ¶
func NewWebSocketCostRecordBuilder() *WebSocketCostRecordBuilder
NewWebSocketCostRecordBuilder creates a new WebSocket cost tracking builder
func (*WebSocketCostRecordBuilder) Build ¶
func (b *WebSocketCostRecordBuilder) Build() *WebSocketCostRecord
Build creates the WebSocket cost tracking record
func (*WebSocketCostRecordBuilder) ForOperation ¶
func (b *WebSocketCostRecordBuilder) ForOperation(operationType string) *WebSocketCostRecordBuilder
ForOperation sets the operation type
func (WebSocketCostRecordBuilder) TableName ¶
func (WebSocketCostRecordBuilder) TableName() string
TableName returns the DynamoDB table backing WebSocketCostRecordBuilder.
func (*WebSocketCostRecordBuilder) WithClient ¶
func (b *WebSocketCostRecordBuilder) WithClient(clientIP, userAgent, source, authMethod string) *WebSocketCostRecordBuilder
WithClient sets the client information
func (*WebSocketCostRecordBuilder) WithConnection ¶
func (b *WebSocketCostRecordBuilder) WithConnection(connectionID, userID, username string) *WebSocketCostRecordBuilder
WithConnection sets the connection details
func (*WebSocketCostRecordBuilder) WithCosts ¶
func (b *WebSocketCostRecordBuilder) WithCosts(breakdown *WebSocketCostBreakdown) *WebSocketCostRecordBuilder
WithCosts sets the cost breakdown
func (*WebSocketCostRecordBuilder) WithDuration ¶
func (b *WebSocketCostRecordBuilder) WithDuration(durationMs int64) *WebSocketCostRecordBuilder
WithDuration sets the connection duration
func (*WebSocketCostRecordBuilder) WithMessages ¶
func (b *WebSocketCostRecordBuilder) WithMessages(count int, sizeBytes int64) *WebSocketCostRecordBuilder
WithMessages sets the message details
func (*WebSocketCostRecordBuilder) WithPerformance ¶
func (b *WebSocketCostRecordBuilder) WithPerformance(processingTimeMs, responseLatencyMs int64, memoryMB float64) *WebSocketCostRecordBuilder
WithPerformance sets the performance metrics
func (*WebSocketCostRecordBuilder) WithProperty ¶
func (b *WebSocketCostRecordBuilder) WithProperty(key string, value interface{}) *WebSocketCostRecordBuilder
WithProperty adds a property
func (*WebSocketCostRecordBuilder) WithService ¶
func (b *WebSocketCostRecordBuilder) WithService(serviceName, functionName, requestID string) *WebSocketCostRecordBuilder
WithService sets the service information
func (*WebSocketCostRecordBuilder) WithStreams ¶
func (b *WebSocketCostRecordBuilder) WithStreams(activeStreams, streamTypes []string) *WebSocketCostRecordBuilder
WithStreams sets the stream information
func (*WebSocketCostRecordBuilder) WithTag ¶
func (b *WebSocketCostRecordBuilder) WithTag(key, value string) *WebSocketCostRecordBuilder
WithTag adds a tag
type WebSocketEventConnection ¶
type WebSocketEventConnection struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // CONNECTION#{connectionID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // METADATA
// GSI keys for querying by user
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // USER#{userID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // CONNECTION#{connectionID}
// Business fields
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Role string `theorydb:"attr:role,omitempty" json:"role,omitempty"`
ConnectedAt time.Time `theorydb:"attr:connectedAt" json:"connected_at"`
LastSeen time.Time `theorydb:"attr:lastSeen" json:"last_seen"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
WebSocketEventConnection represents a WebSocket connection for event subscriptions
func (*WebSocketEventConnection) GetPK ¶
func (w *WebSocketEventConnection) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*WebSocketEventConnection) GetSK ¶
func (w *WebSocketEventConnection) GetSK() string
GetSK returns the sort key for BaseModel interface
func (WebSocketEventConnection) TableName ¶
func (WebSocketEventConnection) TableName() string
TableName returns the DynamoDB table backing WebSocketEventConnection.
func (*WebSocketEventConnection) UpdateKeys ¶
func (w *WebSocketEventConnection) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type WebSocketEventSubscription ¶
type WebSocketEventSubscription struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // CONNECTION#{connectionID}
SK string `theorydb:"sk,attr:SK" json:"sk"` // SUBSCRIPTION#{subscriptionType}
// GSI keys for querying by subscription type
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // SUBSCRIPTION#{subscriptionType}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // CONNECTION#{connectionID}
// Business fields
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"`
SubscriptionType string `theorydb:"attr:subscriptionType" json:"subscription_type"`
Filter map[string]any `theorydb:"attr:filter" json:"filter"`
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
WebSocketEventSubscription represents a subscription to events
func (*WebSocketEventSubscription) GetPK ¶
func (w *WebSocketEventSubscription) GetPK() string
GetPK returns the partition key for BaseModel interface
func (*WebSocketEventSubscription) GetSK ¶
func (w *WebSocketEventSubscription) GetSK() string
GetSK returns the sort key for BaseModel interface
func (WebSocketEventSubscription) TableName ¶
func (WebSocketEventSubscription) TableName() string
TableName returns the DynamoDB table backing WebSocketEventSubscription.
func (*WebSocketEventSubscription) UpdateKeys ¶
func (w *WebSocketEventSubscription) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type WebSocketSubscription ¶
type WebSocketSubscription struct {
// DynamoDB Keys - preserving legacy patterns
PK string `theorydb:"pk,attr:PK" json:"pk"` // SUB#{stream}
SK string `theorydb:"sk,attr:SK" json:"sk"` // CONN#{connectionID}
// GSI keys for querying
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1pk"` // CONN#{connectionID}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1sk"` // STREAM#{stream}
// Business fields
ConnectionID string `theorydb:"attr:connectionID" json:"connection_id"`
UserID string `theorydb:"attr:userID" json:"user_id"`
Stream string `theorydb:"attr:stream" json:"stream"`
SubscribedAt time.Time `theorydb:"attr:subscribedAt" json:"subscribed_at"`
// TTL for automatic cleanup
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
WebSocketSubscription represents a stream subscription for a WebSocket connection
func (*WebSocketSubscription) GetPK ¶
func (w *WebSocketSubscription) GetPK() string
GetPK returns the partition key
func (*WebSocketSubscription) GetSK ¶
func (w *WebSocketSubscription) GetSK() string
GetSK returns the sort key
func (*WebSocketSubscription) TableName ¶
func (w *WebSocketSubscription) TableName() string
TableName returns the DynamoDB table name for this model This is REQUIRED by DynamORM to route operations to the correct table
func (*WebSocketSubscription) UpdateKeys ¶
func (w *WebSocketSubscription) UpdateKeys() error
UpdateKeys sets the GSI keys based on the current values
type WebSocketTierCostStats ¶
type WebSocketTierCostStats struct {
TierName string `theorydb:"attr:tierName" json:"tier_name"`
UserCount int64 `theorydb:"attr:userCount" json:"user_count"`
TotalCostMicroCents int64 `theorydb:"attr:totalCostMicroCents" json:"total_cost_micro_cents"`
TotalCostDollars float64 `theorydb:"attr:totalCostDollars" json:"total_cost_dollars"`
AverageCostPerUser float64 `theorydb:"attr:averageCostPerUser" json:"average_cost_per_user"`
ConnectionMinutes int64 `theorydb:"attr:connectionMinutes" json:"connection_minutes"`
MessageCount int64 `theorydb:"attr:messageCount" json:"message_count"`
// contains filtered or unexported fields
}
WebSocketTierCostStats represents cost statistics for a billing tier
func (WebSocketTierCostStats) TableName ¶
func (WebSocketTierCostStats) TableName() string
TableName returns the DynamoDB table backing WebSocketTierCostStats.
type WebhookDelivery ¶
type WebhookDelivery struct {
// Primary key: WEBHOOK#{webhook_id}
PK string `theorydb:"pk,attr:PK" json:"pk"`
// Sort key: DELIVERY#{delivery_id}
SK string `theorydb:"sk,attr:SK" json:"sk"`
// GSI1: Alert index for querying deliveries by alert
// GSI1PK: ALERT#{alert_id}
GSI1PK string `theorydb:"index:gsi1,pk,attr:gsi1PK,omitempty" json:"gsi1_pk"`
// GSI1SK: STATUS#{status}#TIMESTAMP#{timestamp}
GSI1SK string `theorydb:"index:gsi1,sk,attr:gsi1SK,omitempty" json:"gsi1_sk"`
// GSI2: Status index for querying by delivery status
// GSI2PK: STATUS#{status}
GSI2PK string `theorydb:"index:gsi2,pk,attr:gsi2PK,omitempty" json:"gsi2_pk"`
// GSI2SK: TIMESTAMP#{timestamp}
GSI2SK string `theorydb:"index:gsi2,sk,attr:gsi2SK,omitempty" json:"gsi2_sk"`
// Delivery identification
DeliveryID string `theorydb:"attr:deliveryID" json:"delivery_id"`
AlertID string `theorydb:"attr:alertID" json:"alert_id"`
WebhookID string `theorydb:"attr:webhookID" json:"webhook_id"`
// Webhook configuration
URL string `theorydb:"attr:url" json:"url"`
Headers map[string]string `theorydb:"attr:headers" json:"headers"`
SecretToken string `theorydb:"attr:secretToken" json:"secret_token,omitempty"`
Timeout int `theorydb:"attr:timeoutSeconds" json:"timeout_seconds"`
// InsecureSkipTLSVerify disables TLS certificate verification when delivering the webhook (debug-only).
InsecureSkipTLSVerify bool `theorydb:"attr:insecureSkipTLSVerify" json:"insecure_skip_tls_verify,omitempty"`
// Delivery details
Status string `theorydb:"attr:status" json:"status"` // pending, success, failed, retrying
AttemptNumber int `theorydb:"attr:attemptNumber" json:"attempt_number"`
MaxAttempts int `theorydb:"attr:maxAttempts" json:"max_attempts"`
// Request/Response data
RequestBody string `theorydb:"attr:requestBody" json:"request_body"`
ResponseCode int `theorydb:"attr:responseCode" json:"response_code,omitempty"`
ResponseBody string `theorydb:"attr:responseBody" json:"response_body,omitempty"`
ResponseHeaders map[string]string `theorydb:"attr:responseHeaders" json:"response_headers,omitempty"`
// Error information
ErrorMessage string `theorydb:"attr:errorMessage" json:"error_message,omitempty"`
ErrorType string `theorydb:"attr:errorType" json:"error_type,omitempty"` // network, timeout, server_error, client_error
// Timing information
ScheduledAt time.Time `theorydb:"attr:scheduledAt" json:"scheduled_at"`
StartedAt *time.Time `theorydb:"attr:startedAt" json:"started_at,omitempty"`
CompletedAt *time.Time `theorydb:"attr:completedAt" json:"completed_at,omitempty"`
Duration int64 `theorydb:"attr:durationMs" json:"duration_ms,omitempty"` // Duration in milliseconds
// Retry configuration
NextRetryAt *time.Time `theorydb:"attr:nextRetryAt" json:"next_retry_at,omitempty"`
RetryInterval int `theorydb:"attr:retryIntervalSeconds" json:"retry_interval_seconds"`
// Metadata
CreatedAt time.Time `theorydb:"attr:createdAt" json:"created_at"`
UpdatedAt time.Time `theorydb:"attr:updatedAt" json:"updated_at"`
// TTL for cleanup (deliveries older than 7 days)
TTL int64 `theorydb:"ttl,attr:ttl" json:"ttl,omitempty"`
// contains filtered or unexported fields
}
WebhookDelivery represents a webhook delivery attempt for an alert
func (*WebhookDelivery) CanRetry ¶
func (w *WebhookDelivery) CanRetry() bool
CanRetry returns true if the delivery can be retried
func (*WebhookDelivery) GetPK ¶
func (w *WebhookDelivery) GetPK() string
GetPK returns the partition key
func (*WebhookDelivery) IsComplete ¶
func (w *WebhookDelivery) IsComplete() bool
IsComplete returns true if the delivery is complete (success or failed with no retries)
func (*WebhookDelivery) MarkFailed ¶
func (w *WebhookDelivery) MarkFailed(errorMessage, errorType string, responseCode int, responseBody string, duration time.Duration)
MarkFailed marks the delivery as failed
func (*WebhookDelivery) MarkStarted ¶
func (w *WebhookDelivery) MarkStarted()
MarkStarted marks the delivery as started
func (*WebhookDelivery) MarkSuccess ¶
func (w *WebhookDelivery) MarkSuccess(responseCode int, responseBody string, responseHeaders map[string]string, duration time.Duration)
MarkSuccess marks the delivery as successful
func (*WebhookDelivery) ShouldRetry ¶
func (w *WebhookDelivery) ShouldRetry() bool
ShouldRetry returns true if the delivery should be retried now
func (WebhookDelivery) TableName ¶
func (WebhookDelivery) TableName() string
TableName returns the DynamoDB table backing WebhookDelivery.
func (*WebhookDelivery) UpdateKeys ¶
func (w *WebhookDelivery) UpdateKeys() error
UpdateKeys sets the partition and sort keys based on delivery data
type WeeklyActivity ¶
type WeeklyActivity struct {
PK string `theorydb:"pk,attr:PK" json:"-"`
SK string `theorydb:"sk,attr:SK" json:"-"`
UserID string `theorydb:"attr:userID" json:"user_id,omitempty"` // Optional: for user-specific activity
Week int64 `theorydb:"attr:week" json:"week"` // Unix timestamp of week start
Statuses int64 `theorydb:"attr:statuses" json:"statuses"` // Number of statuses created
Logins int64 `theorydb:"attr:logins" json:"logins"` // Number of unique logins
Registrations int64 `theorydb:"attr:registrations" json:"registrations"` // Number of new registrations
// contains filtered or unexported fields
}
WeeklyActivity represents activity metrics for a specific week Stored in DynamoDB with pattern: PK: USER#username SK: ACTIVITY#WEEK#{weekStartDate}
func NewUserWeeklyActivity ¶
func NewUserWeeklyActivity(userID string, week time.Time) *WeeklyActivity
NewUserWeeklyActivity creates a new user-specific weekly activity entry
func NewWeeklyActivity ¶
func NewWeeklyActivity(week time.Time) *WeeklyActivity
NewWeeklyActivity creates a new weekly activity entry
func (*WeeklyActivity) GetAverageDaily ¶
func (w *WeeklyActivity) GetAverageDaily() float64
GetAverageDaily returns the average daily activity for the week
func (*WeeklyActivity) GetPK ¶
func (w *WeeklyActivity) GetPK() string
GetPK returns the partition key
func (*WeeklyActivity) GetTotalActivity ¶
func (w *WeeklyActivity) GetTotalActivity() int64
GetTotalActivity returns the sum of all activity metrics
func (*WeeklyActivity) GetWeekEnd ¶
func (w *WeeklyActivity) GetWeekEnd() time.Time
GetWeekEnd returns the week end time
func (*WeeklyActivity) GetWeekStart ¶
func (w *WeeklyActivity) GetWeekStart() time.Time
GetWeekStart returns the week start time
func (*WeeklyActivity) IncrementLogins ¶
func (w *WeeklyActivity) IncrementLogins(count int64)
IncrementLogins increments the login count
func (*WeeklyActivity) IncrementRegistrations ¶
func (w *WeeklyActivity) IncrementRegistrations(count int64)
IncrementRegistrations increments the registration count
func (*WeeklyActivity) IncrementStatuses ¶
func (w *WeeklyActivity) IncrementStatuses(count int64)
IncrementStatuses increments the status count
func (*WeeklyActivity) IsActive ¶
func (w *WeeklyActivity) IsActive() bool
IsActive returns true if there was any activity during the week
func (*WeeklyActivity) Merge ¶
func (w *WeeklyActivity) Merge(other *WeeklyActivity)
Merge combines another WeeklyActivity into this one
func (WeeklyActivity) TableName ¶
func (WeeklyActivity) TableName() string
TableName returns the DynamoDB table backing WeeklyActivity.
func (*WeeklyActivity) UpdateKeys ¶
func (w *WeeklyActivity) UpdateKeys() error
UpdateKeys updates the DynamoDB keys based on the activity data
Source Files
¶
- account_features.go
- activity.go
- activity_metric.go
- actor.go
- agent_access_lease.go
- agent_concurrency_slot.go
- agent_governance_state.go
- agent_instance_config.go
- agent_key_challenge.go
- agent_memory_event.go
- agent_share_grant.go
- ai_analysis.go
- ai_cost.go
- alert.go
- analytics.go
- announce.go
- announcement.go
- article.go
- audit_log.go
- auth_refresh_token.go
- authorization_code.go
- background_fetch_job.go
- block.go
- bookmark.go
- category.go
- circuit_breaker.go
- cloudwatch_metrics.go
- cms_article_index.go
- cms_series_slug_index.go
- cms_slug_index.go
- collection_item.go
- community_note.go
- constants.go
- conversation.go
- conversation_mute.go
- conversation_status.go
- cost_driver.go
- cost_projection.go
- cost_tracking.go
- csrf_token.go
- custom_emoji.go
- delivery_status.go
- device.go
- direct_message_migration_state.go
- direct_message_send_transition.go
- direct_message_tombstone.go
- dlq_message.go
- dns_cache.go
- domain_block.go
- draft.go
- draft_review.go
- editorial_media.go
- enhanced_patterns.go
- errors.go
- export.go
- export_cost_tracking.go
- featured_tag.go
- federation.go
- federation_activity.go
- federation_cost_tracking.go
- federation_instance.go
- federation_instance_config.go
- federation_instance_health.go
- federation_metrics.go
- federation_relationship.go
- federation_route_metrics.go
- federation_severance.go
- federation_stats.go
- filter.go
- flag.go
- follow.go
- graphql_stream_subscription.go
- gsi_registry.go
- hashtag.go
- hashtag_follow.go
- hashtag_history_entry.go
- hashtag_mute.go
- hashtag_notification_settings.go
- hashtag_search_result.go
- hashtag_stats.go
- hashtag_status_index.go
- health_check_result.go
- import.go
- import_budget.go
- import_cost_tracking.go
- inbox_item.go
- inbox_processing_receipt.go
- instance_config.go
- instance_counts.go
- instance_feature_config.go
- instance_health.go
- instance_health_report.go
- instance_history.go
- instance_keys.go
- instance_metrics.go
- instance_rule.go
- instance_soul_binding_idempotency_receipt.go
- instance_soul_body_binding.go
- instance_soul_body_binding_username.go
- instance_soul_ens_channel.go
- instance_state.go
- instance_tips_config.go
- instance_translation_config.go
- instance_trust_config.go
- instance_well_known_lesser_soul_agent.go
- like.go
- link_metadata.go
- list.go
- list_member.go
- marker.go
- media.go
- media_analytics.go
- media_attachment.go
- media_job.go
- media_metadata.go
- media_popularity.go
- media_session.go
- media_spending.go
- metrics.go
- missing_reply.go
- moderation.go
- moderation_analytics.go
- moderation_metrics.go
- moderation_ml.go
- move.go
- mute.go
- notification.go
- notification_cost_tracking.go
- notification_delivery.go
- notification_legacy.go
- notification_preferences.go
- numeric_id.go
- oauth_app.go
- oauth_client.go
- oauth_device_session.go
- oauth_refresh_authority.go
- oauth_session.go
- oauth_state.go
- object.go
- outbox_item.go
- passkey_registration_proof.go
- password_reset.go
- pattern_feedback.go
- poll.go
- promo_package.go
- provider_account.go
- public_key_cache.go
- publication.go
- push_subscription.go
- query_cache.go
- quote_permissions.go
- quote_relationship.go
- rate_limit.go
- recovery.go
- refresh_token.go
- relationship.go
- relay.go
- relay_cost.go
- relay_info.go
- remote_actor.go
- reply_sync_record.go
- report.go
- reputation.go
- reviewer_stats.go
- revision.go
- revoked_access_token.go
- route_optimizer.go
- routing_metrics.go
- scheduled_job_cost_tracking.go
- scheduled_status.go
- search_analytics.go
- search_cache.go
- search_click_rate.go
- search_cost_tracking.go
- search_embedding.go
- search_history_entry.go
- search_results.go
- search_suggestion.go
- series.go
- session.go
- setup_session.go
- severed_relationship.go
- skill.go
- social_recovery_request.go
- sortable_time.go
- status.go
- status_identity.go
- status_metadata.go
- status_pin.go
- status_search_options.go
- status_search_result.go
- streaming.go
- streaming_cloudwatch_metrics.go
- streaming_event.go
- thread_context.go
- thread_node.go
- thread_sync.go
- threat_intel.go
- timeline.go
- timeline_entry.go
- timeline_marker.go
- tombstone.go
- transcoding_job.go
- trending_hashtag.go
- trending_link.go
- trending_status.go
- trends.go
- trust.go
- trustee_config.go
- update_history.go
- upload_grant.go
- user.go
- user_app_consent.go
- user_conversation_state.go
- user_features.go
- user_login.go
- user_media_config.go
- user_preferences.go
- vapid.go
- vouch.go
- wallet.go
- webauthn_challenge.go
- webauthn_credential.go
- websocket_connection.go
- websocket_cost_tracking.go
- websocket_subscription_manager.go
- weekly_activity.go