common

package
v1.1.7 Latest Latest
Warning

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

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

Documentation

Overview

Package common provides shared authentication helper functions and types for the Lesser project. These helpers consolidate common authentication patterns found across all services.

Package common provides centralized business logic utilities for the Lesser project. This consolidates common business logic patterns found across all services to eliminate duplication and ensure consistency in business rule enforcement.

Package common provides ActivityPub-specific business logic utilities for the Lesser project. This consolidates ActivityPub federation business patterns found across services to eliminate duplication and ensure consistency in federation behavior.

Package common provides Mastodon API-specific business logic utilities for the Lesser project. This consolidates Mastodon API business patterns found across the API layer to eliminate duplication and ensure consistency with Mastodon API specifications.

Package common provides centralized constants to comply with goconst linting requirements. This consolidates frequently used string literals found throughout the codebase.

Package common provides secure cookie configuration and utilities for HTTP session management. revive:disable-next-line:var-naming - package name is a longstanding public import path

Package common provides shared utilities consumed across services. revive:disable:var-naming - package name is part of the public API surface

Package common provides shared error constants for the Lesser application. revive:disable-next-line var-naming // historical package name kept for backwards compatibility

Package common provides standardized error response functions for HTTP APIs. It consolidates error handling patterns to maintain consistency across the application.

Package common provides common utilities and helpers for the Lesser application. revive:disable-next-line:var-naming - package name is a longstanding public import path

Package common provides shared JSON utilities for ActivityPub operations.

Package common provides shared utilities for key operations.

Package common provides Lambda-specific helper utilities for standardized initialization

Package common provides Lambda initialization helpers and patterns.

Package common provides shared logging utilities for the Lesser application. revive:disable:var-naming - package name retained for backwards-compatible imports.

Package common provides shared helpers across the Lesser codebase. revive:disable-next-line var-naming // package name is a longstanding public import path

Package common provides centralized pagination functionality for consistent pagination handling across all Lesser APIs and services.

Package common provides shared utilities for the Lesser application. revive:disable-next-line var-naming // legacy package name used across public APIs

Package common provides additional standardized response functions that extend the existing error_responses.go with more convenience functions and Mastodon-specific patterns

Package common provides runtime environment helpers for AWS Lambda functions.

Package common exposes helpers shared across tests. revive:disable:var-naming - package name retained for backwards-compatible imports.

Package common provides shared time formatting utilities for the Lesser application.

Index

Constants

View Source
const (
	ScopeRead    = "read"
	ScopeWrite   = "write"
	WriteFollows = "write:follows"
	ReadFollows  = "read:follows"
	AdminRead    = "admin:read"
	AdminWrite   = "admin:write"
)

Common scope constants to avoid import cycles

View Source
const (
	ScopeFollow        = "write:follows"
	ScopeReadAccounts  = "read:accounts"
	ScopeWriteMedia    = "write:media"
	ScopeReadStatuses  = "read:statuses"
	ScopeWriteStatuses = "write:statuses"
	ScopePush          = "push"
)

Additional OAuth scopes beyond the existing ones

View Source
const (
	// Entity status states
	StatusActive     = "active"
	StatusInactive   = "inactive"
	StatusPending    = "pending"
	StatusProcessing = "processing"
	StatusCompleted  = "completed"
	StatusFailed     = "failed"
	StatusCancelled  = "cancelled"
	StatusExpired    = "expired"
	StatusSuspended  = "suspended"
	StatusDeleted    = "deleted"

	// Account/Actor states
	AccountStatusActive    = "active"
	AccountStatusSuspended = "suspended"
	AccountStatusPending   = "pending"
	AccountStatusDeleted   = "deleted"
)

Status constants - used across multiple services for consistent status tracking

View Source
const (
	// CRUD operations
	OperationCreate = "create"
	OperationRead   = "read"
	OperationUpdate = "update"
	OperationDelete = "delete"

	// ActivityPub activities
	ActivityCreate   = "Create"
	ActivityUpdate   = "Update"
	ActivityDelete   = "Delete"
	ActivityFollow   = "Follow"
	ActivityAccept   = "Accept"
	ActivityReject   = "Reject"
	ActivityAnnounce = "Announce"
	ActivityLike     = "Like"
	ActivityUndo     = "Undo"
	ActivityBlock    = "Block"
	ActivityFlag     = "Flag"
	ActivityMove     = "Move"
	ActivityAdd      = "Add"
	ActivityRemove   = "Remove"
)

Operation type constants - used in ActivityPub and audit logging

View Source
const (
	ContentTypeActivityPub = "application/activity+json"
	ContentTypePlain       = "text/plain"
	ContentTypeForm        = "application/x-www-form-urlencoded"
	ContentTypeMultipart   = "multipart/form-data"
)

Content type constants - additional to http_constants.go

View Source
const (
	// Specific image MIME types
	MediaTypeJPEG     = "image/jpeg"
	MediaTypePNG      = "image/png"
	MediaTypeWebP     = "image/webp"
	MediaTypeGIFImage = "image/gif"

	// Specific video MIME types
	MediaTypeMP4  = "video/mp4"
	MediaTypeWebM = "video/webm"
	MediaTypeMOV  = "video/quicktime"

	// Specific audio MIME types
	MediaTypeMP3  = "audio/mpeg"
	MediaTypeOGG  = "audio/ogg"
	MediaTypeWAV  = "audio/wav"
	MediaTypeFLAC = "audio/flac"
)

Specific MIME type constants (complementary to business_mastodon.go MediaType)

View Source
const (
	// Actor types
	ActorTypePerson  = "Person"
	ActorTypeService = "Service"
	ActorTypeGroup   = "Group"

	// Object types
	ObjectTypeNote      = "Note"
	ObjectTypeArticle   = "Article"
	ObjectTypeImage     = "Image"
	ObjectTypeVideo     = "Video"
	ObjectTypeAudio     = "Audio"
	ObjectTypeDocument  = "Document"
	ObjectTypePage      = "Page"
	ObjectTypeEvent     = "Event"
	ObjectTypePlace     = "Place"
	ObjectTypeProfile   = "Profile"
	ObjectTypeTombstone = "Tombstone"

	// Collection types
	CollectionTypeOrderedCollection     = "OrderedCollection"
	CollectionTypeOrderedCollectionPage = "OrderedCollectionPage"
	CollectionTypeCollection            = "Collection"
	CollectionTypeCollectionPage        = "CollectionPage"
)

Federation constants

View Source
const (
	TimelineHome      = "home"
	TimelinePublic    = "public"
	TimelineLocal     = "local"
	TimelineFederated = "federated"
	TimelineUser      = "user"
	TimelineHashtag   = "hashtag"
	TimelineList      = "list"

	// Stream event types
	StreamEventUpdate       = "update"
	StreamEventDelete       = "delete"
	StreamEventNotification = "notification"
	StreamEventFilters      = "filters_changed"
	StreamEventConversation = "conversation"
	StreamEventAnnouncement = "announcement"
	StreamEventStatusUpdate = "status.update"
)

Timeline and stream constants

View Source
const (
	NotificationTypeMention       = "mention"
	NotificationTypeReblog        = "reblog"
	NotificationTypeFavourite     = "favourite"
	NotificationTypeFollow        = "follow"
	NotificationTypeFollowRequest = "follow_request"
	NotificationTypePoll          = "poll"
	NotificationTypeStatus        = "status"
	NotificationTypeUpdate        = "update"
	NotificationTypeAdminSignUp   = "admin.sign_up"
	NotificationTypeAdminReport   = "admin.report"
)

Notification types

View Source
const (
	// Job types
	JobTypeImport       = "import"
	JobTypeExport       = "export"
	JobTypeMedia        = "media"
	JobTypeFederation   = "federation"
	JobTypeModeration   = "moderation"
	JobTypeNotification = "notification"
	JobTypeSearch       = "search"
	JobTypeAnalytics    = "analytics"

	// Job priorities
	JobPriorityLow      = "low"
	JobPriorityNormal   = "normal"
	JobPriorityHigh     = "high"
	JobPriorityCritical = "critical"

	// Queue names
	QueueDefault      = "default"
	QueueImport       = "import"
	QueueExport       = "export"
	QueueMedia        = "media"
	QueueFederation   = "federation"
	QueueModeration   = "moderation"
	QueueNotification = "notification"
	QueueSearch       = "search"
	QueueAnalytics    = "analytics"
	QueueDLQ          = "dlq" // Dead letter queue
)

Job processing constants

View Source
const (
	RelationshipFollowing     = "following"
	RelationshipFollowed      = "followed_by"
	RelationshipBlocked       = "blocked"
	RelationshipBlocking      = "blocking"
	RelationshipMuted         = "muted"
	RelationshipMuting        = "muting"
	RelationshipRequested     = "requested"
	RelationshipDomainBlocked = "domain_blocked"
	RelationshipEndorsed      = "endorsed"
)

Relationship constants

View Source
const (
	ReportCategorySpam      = "spam"
	ReportCategoryViolation = "violation"
	ReportCategoryOther     = "other"
	ReportCategoryLegal     = "legal"

	ReportStatusOpen     = "open"
	ReportStatusResolved = "resolved"
	ReportStatusRejected = "rejected"
)

Report constants

View Source
const (
	ModerationActionNone      = "none"
	ModerationActionWarn      = "warn"
	ModerationActionSilence   = "silence"
	ModerationActionSuspend   = "suspend"
	ModerationActionSensitive = "mark_as_sensitive"
	ModerationActionDelete    = "delete"

	ModerationSeverityInfo     = "info"
	ModerationSeverityWarning  = "warning"
	ModerationSeverityError    = "error"
	ModerationSeverityCritical = "critical"
)

Moderation constants

View Source
const (
	SearchTypeAccount = "accounts"
	SearchTypeStatus  = "statuses"
	SearchTypeHashtag = "hashtags"
	SearchTypeAll     = "all"

	SearchScopeLocal  = "local"
	SearchScopeRemote = "remote"
	SearchScopeAll    = "all"
)

Search constants

View Source
const (
	ProcessingStatusQueued     = "queued"
	ProcessingStatusProcessing = "processing"
	ProcessingStatusCompleted  = "completed"
	ProcessingStatusFailed     = "failed"

	// File categories
	FileCategoryAvatar     = "avatar"
	FileCategoryHeader     = "header"
	FileCategoryAttachment = "attachment"
	FileCategoryEmoji      = "emoji"
	FileCategoryPreview    = "preview"
)

File processing constants

View Source
const (
	CacheKeyUser         = "user:"
	CacheKeyActor        = "actor:"
	CacheKeyStatus       = "status:"
	CacheKeyAccount      = "account:"
	CacheKeyTimeline     = "timeline:"
	CacheKeyNotification = "notification:"
	CacheKeySearch       = "search:"
	CacheKeyMedia        = "media:"
	CacheKeyFederation   = "federation:"

	// Cache durations (used as string constants for configuration)
	CacheDurationShort    = "5m"
	CacheDurationMedium   = "30m"
	CacheDurationLong     = "2h"
	CacheDurationExtended = "24h"
)

Cache constants

View Source
const (
	DBOperationCreate = "create"
	DBOperationRead   = "read"
	DBOperationUpdate = "update"
	DBOperationDelete = "delete"
	DBOperationScan   = "scan"
	DBOperationQuery  = "query"
	DBOperationBatch  = "batch"

	// DynamoDB specific operations
	DynamoOperationPutItem            = "PutItem"
	DynamoOperationGetItem            = "GetItem"
	DynamoOperationUpdateItem         = "UpdateItem"
	DynamoOperationDeleteItem         = "DeleteItem"
	DynamoOperationQuery              = "Query"
	DynamoOperationScan               = "Scan"
	DynamoOperationBatchGetItem       = "BatchGetItem"
	DynamoOperationBatchWriteItem     = "BatchWriteItem"
	DynamoOperationTransactWriteItems = "TransactWriteItems"
	DynamoOperationTransactGetItems   = "TransactGetItems"
)

Database operation constants

View Source
const (
	LogLevelDebug = "debug"
	LogLevelInfo  = "info"
	LogLevelWarn  = "warn"
	LogLevelError = "error"
	LogLevelFatal = "fatal"

	LogFieldComponent = "component"
	LogFieldOperation = "operation"
	LogFieldUserID    = "user_id"
	LogFieldStatusID  = "status_id"
	LogFieldDomain    = "domain"
	LogFieldError     = "error"
	LogFieldDuration  = "duration"
	LogFieldSize      = "size"
)

Logging constants

View Source
const (
	HeaderAuthorization = "Authorization"
	HeaderContentType   = "Content-Type"
	HeaderAccept        = "Accept"
	HeaderUserAgent     = "User-Agent"
	HeaderSignature     = "Signature"
	HeaderDigest        = "Digest"
	HeaderDate          = "Date"
	HeaderHost          = "Host"
	HeaderActivityPub   = "activity+json"

	// CORS headers
	HeaderCORSOrigin      = "Access-Control-Allow-Origin"
	HeaderCORSMethods     = "Access-Control-Allow-Methods"
	HeaderCORSHeaders     = "Access-Control-Allow-Headers"
	HeaderCORSCredentials = "Access-Control-Allow-Credentials"
	HeaderCORSMaxAge      = "Access-Control-Max-Age"

	// Security headers
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderReferrerPolicy          = "Referrer-Policy"
)

HTTP header constants

View Source
const (
	EnvProduction  = "production"
	EnvStaging     = "staging"
	EnvDevelopment = "development"
	EnvTesting     = "testing"
	EnvLocal       = "local"
)

Environment constants

View Source
const (
	ConfigKeyDBHost     = "db.host"
	ConfigKeyDBPort     = "db.port"
	ConfigKeyDBName     = "db.name"
	ConfigKeyDBUser     = "db.user"
	ConfigKeyDBPassword = "db.password"

	ConfigKeyRedisHost     = "redis.host"
	ConfigKeyRedisPort     = "redis.port"
	ConfigKeyRedisPassword = "redis.password"

	ConfigKeyS3Bucket    = "s3.bucket"
	ConfigKeyS3Region    = "s3.region"
	ConfigKeyS3AccessKey = "s3.access_key"
	ConfigKeyS3SecretKey = "s3.secret_key" // #nosec G101 -- configuration key name, not a credential

	ConfigKeyDomainName = "domain.name"
	ConfigKeyBaseURL    = "base.url"
	ConfigKeyAPIVersion = "api.version"

	ConfigKeyJWTSecret     = "jwt.secret"
	ConfigKeyOAuthSecret   = "oauth.secret"
	ConfigKeyEncryptionKey = "encryption.key"

	ConfigKeyLogLevel  = "log.level"
	ConfigKeyLogFormat = "log.format"
	ConfigKeyLogOutput = "log.output"

	ConfigKeyRateLimitEnabled  = "ratelimit.enabled"
	ConfigKeyRateLimitRequests = "ratelimit.requests"
	ConfigKeyRateLimitWindow   = "ratelimit.window"

	ConfigKeyCacheEnabled = "cache.enabled"
	ConfigKeyCacheTTL     = "cache.ttl"
	ConfigKeyCacheSize    = "cache.size"
)

Configuration keys (used in configuration files and environment variables)

View Source
const (
	DefaultMaxFileSize = 10 * 1024 * 1024 // 10MB
	DefaultTimeout     = 30               // seconds
	DefaultRetryCount  = 3
	DefaultBatchSize   = 100

	// Default TTL values (in seconds)
	DefaultCacheTTL   = 300    // 5 minutes
	DefaultSessionTTL = 3600   // 1 hour
	DefaultTokenTTL   = 900    // 15 minutes
	DefaultRefreshTTL = 604800 // 7 days
)

Default values as constants (excluding DefaultPaginationLimit which exists in pagination.go)

View Source
const (
	PatternUsername = `^[a-zA-Z0-9_]{1,30}$`
	PatternEmail    = `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`
	PatternURL      = `^https?://[^\s/$.?#].[^\s]*$`
	PatternHashtag  = `#[a-zA-Z0-9_]+`
	PatternMention  = `@[a-zA-Z0-9_]+(@[a-zA-Z0-9.-]+)?`
	PatternUUID     = `^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`
)

Regular expression patterns as constants

View Source
const (
	CharSpace     = " "
	CharNewline   = "\n"
	CharTab       = "\t"
	CharEmpty     = ""
	CharDot       = "."
	CharComma     = ","
	CharSemicolon = ";"
	CharColon     = ":"
	CharSlash     = "/"
	CharBackslash = "\\"
	CharHash      = "#"
	CharAt        = "@"
	CharPlus      = "+"
	CharMinus     = "-"
	CharEquals    = "="
	CharQuestion  = "?"
	CharAmpersand = "&"
)

Special character constants

View Source
const (
	// Validation errors
	ValidationMustNotBeNull  = "must not be null"
	ValidationPeriodRequired = "period is required"

	// General error categories
	ErrorGeneral  = "general"
	ErrorExpected = "expected"
	ErrorTimeout  = "timeout"
	ErrorOther    = "other"

	// Access errors
	ErrorAdminAccessRequired = "admin access required"

	// Vote related
	ErrorFailedToStoreVote = "Failed to store vote"

	// Delivery related
	ErrorFailedToDeliverToRecipients = "Failed to deliver to recipients"

	// Subscription related
	ErrorSubscriptionManagerNotRunning = "subscription manager is not running"

	// Import related
	ErrorImportNotFound = "import not found: %s"

	// Export related
	ErrorFailedToGetExportsForUser = "failed to get exports for user: %w"

	// Federation related
	ErrorFailedToRecordCircuitBreakerFailure = "failed to record circuit breaker failure"

	// Collection related
	ErrorFailedToCheckCollectionMembership = "failed to check collection membership"

	// Moderation related
	ErrorFailedToStoreAnalysisResult = "failed to store analysis result"

	// DLQ related
	ErrorFailedToGetQueueURL = "failed to get queue URL for %s: %w"

	// Reputation related
	ErrorInvalidPublicKeyEncoding = "invalid public key encoding: %w"

	// WebSocket related
	ErrorFailedToStoreSubscription = "failed to store subscription: %w"

	// Follow request related
	ErrorFollowRequestNotFound    = "follow request not found"
	ErrorFailedToGetFollowerActor = "failed to get follower actor"
	ErrorFailedToGetFollowedActor = "failed to get followed actor"

	// Search related
	ErrorSearchFailed                   = "search failed: %w"
	ErrorPrivacyAwareSearchFailed       = "privacy-aware search failed: %w"
	ErrorStatusSearchFailed             = "status search failed: %w"
	ErrorPrivacyAwareStatusSearchFailed = "privacy-aware status search failed: %w"

	// Deployment/initialization related
	ErrorFailedToGeneratePrivateKey   = "failed to generate private key: %w"
	ErrorFailedToMarshalPrivateKey    = "failed to marshal private key: %w"
	ErrorFailedToConvertToECDHKey     = "failed to convert to ECDH key: %w"
	ErrorFailedToCreateOrUpdateSecret = "failed to create or update secret: %w"

	// Middleware RBAC related
	ErrorUnauthorizedNoValidClaims  = "unauthorized: no valid claims found"
	ErrorForbiddenAdminRequired     = "forbidden: admin access required"
	ErrorForbiddenModeratorRequired = "forbidden: moderator access required"
	ErrorForbiddenViewerRequired    = "forbidden: viewer access required"
	ErrorForbiddenUnknownPermission = "forbidden: unknown permission level"

	// Translation related
	ErrorInvalidSourceLanguageCode = "invalid source language code: %w"
	ErrorInvalidTargetLanguageCode = "invalid target language code: %w"
)

Common Error Messages

View Source
const (
	// Standard headers
	AuthorizationHeader = "Authorization"
	ContentTypeHeader   = "Content-Type"
	UserAgentHeader     = "User-Agent"
	AcceptHeader        = "Accept"

	// Custom headers
	XTenantIDHeader        = "X-Tenant-ID"
	XRequestIDHeader       = "X-Request-ID"
	XRealIPHeader          = "X-Real-IP"
	XForwardedForHeader    = "X-Forwarded-For"
	XProcessingDelayHeader = "X-Processing-Delay"
	XNextCursorHeader      = "X-Next-Cursor"
	XInboxBacklogHeader    = "X-Inbox-Backlog"

	// Security headers
	XFrameOptionsHeader       = "X-Frame-Options"
	XContentTypeOptionsHeader = "X-Content-Type-Options"
	XXSSProtectionHeader      = "X-XSS-Protection"

	// ActivityPub headers
	DigestHeader    = "Digest"
	SignatureHeader = "Signature"
	DateHeader      = "Date"
	HostHeader      = "Host"
)

HTTP Headers

View Source
const (
	ContentTypeJSON            = "application/json"
	ContentTypeHTML            = "text/html"
	ContentTypeActivityPubJSON = "application/activity+json"
	ContentTypeLDJSON          = "application/ld+json"

	// Media types
	ImageGIF       = "image/gif"
	ImagePNG       = "image/png"
	ImageJPEG      = "image/jpeg"
	ImageJPG       = "image/jpg"
	ImageWEBP      = "image/webp"
	VideoMP4       = "video/mp4"
	VideoWEBM      = "video/webm"
	VideoQuickTime = "video/quicktime"
)

Content Types

View Source
const (
	StringFalse = "false"
	StringTrue  = "true"
)

String literals commonly used in parameter processing

View Source
const (
	SchemeHTTPS = "https"
	SchemeHTTP  = "http"
)

URL schemes

View Source
const (
	// MaxJSONDepth is the maximum JSON depth to prevent deep nesting attacks
	MaxJSONDepth = 10

	// MaxJSONKeys is the maximum number of keys in an object
	MaxJSONKeys = 100

	// MaxJSONArrayLength is the maximum array length
	MaxJSONArrayLength = 1000

	// MaxJSONStringLength is the maximum string length in JSON
	MaxJSONStringLength = 50000

	// MaxJSONSize is the maximum total JSON size (already enforced by request limits)
	MaxJSONSize = 512 * 1024 // 512KB
)
View Source
const (
	DefaultPaginationLimit = 20
	MaxPaginationLimit     = 100
	MinPaginationLimit     = 1
	DefaultPaginationPage  = 1
)

PaginationDefaults holds the default values for pagination

View Source
const (
	// MaxRequestSize is the default maximum size for general requests (1MB)
	MaxRequestSize = 1 * 1024 * 1024 // 1MB

	// MaxActivitySize is the maximum size for ActivityPub activities
	MaxActivitySize = 512 * 1024 // 512KB

	// MaxMediaSize is the maximum size for media uploads (50MB)
	MaxMediaSize = 50 * 1024 * 1024 // 50MB

	// MaxImportSize is the maximum size for import files (100MB)
	MaxImportSize = 100 * 1024 * 1024 // 100MB
)
View Source
const (
	// MaxUntrustedHTTPResponseBodyBytes is the default maximum number of bytes to read from
	// untrusted HTTP responses when the body is only needed for logging/debugging.
	//
	// This is intentionally far smaller than MaxRequestSize: untrusted servers may return
	// arbitrarily large bodies, and we should never allow them to amplify memory/cost.
	MaxUntrustedHTTPResponseBodyBytes = 64 * 1024 // 64KB

	// TruncatedBodyMarker is appended to snippets when the body exceeded the cap.
	TruncatedBodyMarker = "…[truncated]"
)
View Source
const (
	EventAuthFailure        = "auth_failure"
	EventCSRFFailure        = "csrf_failure"
	EventTokenReuse         = "token_reuse"
	EventRateLimitExceed    = "rate_limit_exceed"
	EventSSRFBlocked        = "ssrf_blocked"
	EventSuspiciousActivity = "suspicious_activity"
	EventPasswordFailure    = "password_failure"
	EventAccountLocked      = "account_locked"
	EventTokenRevoked       = "token_revoked"
	EventTokenFamilyRevoked = "token_family_revoked" // #nosec G101 - not a credential
	EventUserTokensRevoked  = "user_tokens_revoked"  // #nosec G101 - not a credential
	EventSecurityAlert      = "security_alert"
)

Security event types

View Source
const (
	// DateFormat represents YYYY-MM-DD format (e.g., 2006-01-02)
	DateFormat = "2006-01-02"

	// MonthFormat represents YYYY-MM format (e.g., 2006-01)
	MonthFormat = "2006-01"

	// CompactDateFormat represents YYYYMMDD format (e.g., 20060102)
	CompactDateFormat = "20060102"

	// CompactTimeFormat represents YYYYMMDDHHMMSS format (e.g., 20060102150405)
	CompactTimeFormat = "20060102150405"

	// DayHourFormat represents YYYYMMDDHH format (e.g., 2006010215)
	DayHourFormat = "2006010215"

	// YearFormat represents YYYY format (e.g., 2006)
	YearFormat = "2006"
)

Time format constants used throughout the application

View Source
const (
	// Status limits
	MaxStatusLength     = 500
	MaxStatusSpoiler    = 200
	MaxStatusAttachment = 4

	// Account limits
	MaxDisplayNameLength = 30
	MaxBioLength         = 500
	MaxFieldNameLength   = 255
	MaxFieldValueLength  = 255
	MaxAccountFields     = 4

	// Media limits
	MaxMediaDescLength = 1500
	MaxMediaFileSize   = 100 * 1024 * 1024 // 100MB

	// Filter limits
	MaxFilterTitleLength   = 200
	MaxFilterKeywordLength = 500
	MaxFilterKeywords      = 50

	// Poll limits
	MaxPollOptions      = 4
	MaxPollOptionLength = 50
	MinPollDuration     = 5 * 60            // 5 minutes
	MaxPollDuration     = 30 * 24 * 60 * 60 // 30 days

	// List limits
	MaxListTitleLength = 100
	MaxListAccounts    = 500

	// Application limits
	MaxAppNameLength    = 100
	MaxAppWebsiteLength = 2000
	MaxAppScopesLength  = 500
)

Mastodon API constants

View Source
const InsecureTLSOverrideEnvVar = "LESSER_ALLOW_INSECURE_TLS"

InsecureTLSOverrideEnvVar enables explicitly allowing insecure TLS in narrowly scoped, debug-only scenarios.

Insecure TLS means certificate verification may be disabled (e.g., tls.Config.InsecureSkipVerify).

View Source
const (
	// OAuthClientSecretHashPrefix marks hashed secrets stored for OAuth clients.
	// Prefixing avoids ambiguity with legacy plaintext values.
	OAuthClientSecretHashPrefix = "bcrypt:"
)
View Source
const (
	VisibilityLocal = "local" // Additional visibility level not in business.go
)

Visibility constants - used for post visibility settings (additional to business.go)

Variables

View Source
var (
	ReadScopes   = []string{ScopeRead, "read:accounts", "read:statuses", "read:follows"}
	WriteScopes  = []string{ScopeWrite, "write:accounts", "write:statuses", "write:follows"}
	FollowScopes = []string{WriteFollows, ScopeWrite, "write:follows"}
	BlockScopes  = []string{ScopeWrite, "write:blocks"}
	AdminScopes  = []string{AdminRead, AdminWrite}
)

Common scope combinations found in the codebase

View Source
var (
	ErrMastodonInvalidToken      = NewMastodonAPIError("invalid_token", "The access token is invalid", 401)
	ErrMastodonInsufficientScope = NewMastodonAPIError("insufficient_scope", "The request requires higher privileges than provided", 403)
	ErrMastodonRateLimited       = NewMastodonAPIError("rate_limited", "Rate limit exceeded", 429)
	ErrMastodonValidation        = NewMastodonAPIError("validation_failed", "Validation failed", 422)
	ErrMastodonNotFound          = NewMastodonAPIError("record_not_found", "Record not found", 404)
)

Common Mastodon API errors

View Source
var (
	// 400 Bad Request variants
	ErrorMissingAccountID = "missing account id"
	ErrorMissingStatusID  = "missing status id"
	ErrorMissingParameter = "missing required parameter"
	ErrorInvalidParameter = "invalid parameter"
	ErrorInvalidRequest   = "invalid request"
	ErrorInvalidFormat    = "invalid format"

	// 401 Unauthorized variants
	ErrorUnauthorized = "Unauthorized"
	ErrorInvalidToken = "invalid token"
	ErrorMissingAuth  = "authentication required"
	ErrorExpiredToken = "token expired"

	// 403 Forbidden variants
	ErrorInsufficientScope = "insufficient scope"
	ErrorNotAuthorized     = "not authorized"
	ErrorAccessDenied      = "access denied"

	// 404 Not Found variants
	ErrorNotFound        = "not found"
	ErrorAccountNotFound = "account not found"
	ErrorStatusNotFound  = "status not found"
	ErrorUserNotFound    = "user not found"
	ErrorActorNotFound   = "actor not found"

	// 422 Unprocessable Entity variants
	ErrorStatusTooLong  = "status text too long"
	ErrorInvalidContent = "invalid content"

	// 500 Internal Server Error variants
	ErrorInternalServer = "internal server error"
	ErrorDatabaseError  = "database error"
	ErrorFailedToCreate = "failed to create"
	ErrorFailedToUpdate = "failed to update"
	ErrorFailedToDelete = "failed to delete"
	ErrorFailedToGet    = "failed to get"
)

Common error status/message combinations found in the codebase

View Source
var (
	ErrTokenNotFound = errors.TokenNotFound()
	ErrTokenExpired  = errors.TokenExpired()
	ErrTokenRevoked  = errors.TokenRevoked()
)

Token-related errors

View Source
var (
	ErrMissingAuthorizationHeader = errors.NewAuthError(errors.CodeAuthFailed, "Missing authorization header")
	ErrAuthHeaderEmpty            = errors.NewAuthError(errors.CodeAuthFailed, "Authorization header is empty")
	ErrAuthHeaderInvalidPrefix    = errors.NewAuthError(errors.CodeAuthFailed, "Authorization header must start with 'Bearer '")
	ErrAuthenticationRequired     = errors.NewAuthError(errors.CodeAuthFailed, "Authentication required for write operations")
	ErrAuthenticationRequiredRead = errors.NewAuthError(errors.CodeAuthFailed, "Authentication required for read operations")
	ErrInsufficientScope          = errors.InsufficientScope("")
	ErrInsufficientScopeWrite     = errors.InsufficientScope("write access required")
	ErrInsufficientScopeRead      = errors.InsufficientScope("read access required")
)

Auth helper errors

View Source
var (
	ErrDataCannotBeNil                         = errors.RequiredFieldMissing("data")
	ErrRequiredFieldMissing                    = errors.RequiredFieldMissing("field")
	ErrFieldExceedsMaxLength                   = errors.FieldTooLong("field", 0, 0)
	ErrFieldBelowMinLength                     = errors.FieldTooShort("field", 0, 0)
	ErrCannotPerformOperationOnSelf            = errors.OperationNotAllowedOnSelf("operation")
	ErrActorAndTargetIDsRequired               = errors.MultipleValidationErrors([]string{"Both actor and target IDs are required for operation"})
	ErrContentExceedsMaxLength                 = errors.ContentTooLong("content", 0)
	ErrContentBelowMinLength                   = errors.ContentEmpty("content")
	ErrContentContainsForbiddenWord            = errors.ContentContainsForbiddenWord("word")
	ErrInvalidVisibilityLevel                  = errors.StatusInvalidVisibility("")
	ErrActorIDRequiredForQuotaValidation       = errors.RequiredFieldMissing("actorID")
	ErrActionTypeRequiredForQuotaValidation    = errors.RequiredFieldMissing("actionType")
	ErrMetricTypeRequired                      = errors.RequiredFieldMissing("metricType")
	ErrActorIDRequiredForMetrics               = errors.RequiredFieldMissing("actorID")
	ErrInvalidCurrentState                     = errors.InvalidStateForOperation("", "operation")
	ErrInvalidStateTransition                  = errors.InvalidStateForOperation("", "state_transition")
	ErrAuthenticationRequiredForAccess         = errors.InsufficientPermissions("access")
	ErrResourceIDRequiredForAccessValidation   = errors.RequiredFieldMissing("resourceID")
	ErrResourceTypeRequiredForAccessValidation = errors.RequiredFieldMissing("resourceType")
	ErrInvalidAccessLevel                      = errors.InvalidValue("access_level", []string{"read", "write", "admin"}, "")
	ErrOperationValidationFailed               = errors.ValidationFailedWithField("operation")
	ErrOperationExecutionFailed                = errors.ProcessingFailed("operation", stdErrors.New("operation execution failed"))
)

Business logic validation errors

View Source
var (
	ErrActorURIEmpty           = errors.ActivityPubActorURIEmpty()
	ErrActivityTypeEmpty       = errors.ActivityPubActivityTypeEmpty()
	ErrSignatureHeaderEmpty    = errors.ActivityPubSignatureHeaderEmpty()
	ErrInvalidSignature        = errors.ActivityPubInvalidSignature()
	ErrActorURIMustUseHTTPS    = errors.ActivityPubActorURIMustUseHTTPS()
	ErrActorDomainBlocked      = errors.ContentNotAllowed("actor_domain", "domain is blocked")
	ErrActorDomainNotAllowed   = errors.ContentNotAllowed("actor_domain", "domain not in allowed list")
	ErrUnsupportedActivityType = errors.ActivityPubUnsupportedActivityType("")
)

ActivityPub-specific errors

View Source
var (
	ErrStatusContentTooLong     = errors.ContentTooLong("status", 500)
	ErrStatusMustHaveContent    = errors.ContentMustHaveContentOrMedia()
	ErrStatusTooManyMedia       = errors.StatusTooManyMedia(4, 0)
	ErrStatusTooManyPollOptions = errors.PollTooManyOptions(4, 0)
)

Status validation errors

View Source
var (
	ErrDisplayNameTooLong             = errors.DisplayNameTooLong(30)
	ErrUsernameEmpty                  = errors.UsernameEmpty()
	ErrUsernameInvalidCharacters      = errors.UsernameInvalidCharacters()
	ErrUsernameConsecutiveUnderscores = errors.UsernameConsecutiveUnderscores()
	ErrUsernameInvalidLength          = errors.UsernameInvalidLength(1, 30)
	ErrUsernameInvalidFormat          = errors.UsernameStartsOrEndsWithUnderscore()
	ErrBioTooLong                     = errors.BioTooLong(160)
)

Account validation errors

View Source
var (
	ErrVideoFileTooLarge    = errors.VideoFileTooLarge(0, 0)
	ErrMediaFileTooLarge    = errors.MediaFileTooLarge(0, 0)
	ErrInvalidImageMimeType = errors.ImageInvalidFormat("")
	ErrInvalidVideoMimeType = errors.VideoInvalidFormat("")
	ErrInvalidAudioMimeType = errors.AudioInvalidFormat("")
)

Media validation errors

View Source
var (
	ErrFilterKeywordEmpty   = errors.FilterKeywordEmpty()
	ErrFilterKeywordTooLong = errors.FilterKeywordTooLong(100)
)

Filter validation errors

View Source
var (
	ErrPollTooFewOptions  = errors.PollTooFewOptions(2)
	ErrPollTooManyOptions = errors.PollTooManyOptions(4, 0)
	ErrPollOptionEmpty    = errors.PollOptionEmpty()
	ErrPollOptionTooLong  = errors.PollOptionTooLong(50)
	ErrPollExpiryInvalid  = errors.PollExpiryInvalid()
	ErrPollExpiryTooLong  = errors.PollExpiryTooLong(604800)
)

Poll validation errors

View Source
var (
	ErrInvalidNotificationType = errors.NotificationTypeInvalid("")
	ErrInvalidOAuthScope       = errors.OAuthScopeInvalid("")
	ErrIDEmpty                 = errors.IDEmpty("")
	ErrInvalidIDFormat         = errors.IDInvalidFormat("")
	ErrInvalidTimestampFormat  = errors.TimestampInvalidFormat("")
)

General validation errors

View Source
var (
	ErrJSONDepthExceedsMaximum    = errors.JSONTooDeep(10)
	ErrJSONObjectTooManyKeys      = errors.JSONTooManyKeys(100)
	ErrJSONKeyTooLong             = errors.JSONKeyTooLong(256)
	ErrJSONArrayTooManyElements   = errors.JSONArrayTooLarge(1000)
	ErrJSONStringTooLong          = errors.JSONStringTooLong(10000)
	ErrUnexpectedJSONType         = errors.JSONInvalid("unexpected type")
	ErrJSONSizeExceedsMaximum     = errors.JSONSizeTooLarge(1048576)
	ErrJSONBombRepetitionDetected = errors.JSONBombDetected("excessive repetition")
	ErrJSONBombNestingDetected    = errors.JSONBombDetected("excessive nesting")
)

JSON safety validation errors

View Source
var (
	ErrDynamoTableRequired             = errors.EnvironmentVariableRequired("DYNAMODB_TABLE")
	ErrDynamORMNotImplemented          = errors.ServiceInitializationFailedGeneric("DynamORM", nil)
	ErrRepositoryFactoryNotImplemented = errors.ServiceInitializationFailedGeneric("repository factory", nil)
	ErrAuthServicesNotImplemented      = errors.ServiceInitializationFailedGeneric("auth services", nil)
)

Lambda helper errors

View Source
var (
	ErrRedirectURLEmpty               = errors.RequiredFieldMissing("redirect_url")
	ErrProtocolRelativeURLsNotAllowed = errors.URLSchemeNotAllowed("", "protocol-relative")
	ErrJavascriptDataURLsNotAllowed   = errors.URLSchemeNotAllowed("", "javascript/data")
	ErrExternalHostNotAllowed         = errors.URLHostNotAllowed("", "external")
)

Redirect validation errors

View Source
var (
	ErrRequestBodyTooLarge              = errors.FileSizeExceedsLimit(0, 0)
	ErrFailedToParseRequestBody         = errors.ParsingFailed("request body", nil)
	ErrFailedToParseWithComplexFallback = errors.ParsingFailed("request with complex fallback", nil)
)

Request handling errors

View Source
var (
	ErrLambdaTimeoutApproaching = errors.TimeoutError("Lambda operation")
	ErrMemoryLimitExceeded      = errors.LambdaMemoryExceeded("", 0)
)

Resource monitoring errors

View Source
var (
	ErrTransformFunctionNotSet       = errors.TransformFunctionNotSet()
	ErrTransformationConditionNotMet = errors.PreConditionFailed("transformation condition")
	ErrUnknownNumber                 = errors.InvalidValue("number", []string{"valid number"}, "unknown")
)

Transformer errors

View Source
var (
	ErrMastodonOperationValidationFailed = errors.ValidationFailedWithField("mastodon operation")
	ErrMastodonOperationExecutionFailed  = errors.ProcessingFailed("mastodon operation", stdErrors.New("mastodon operation execution failed"))
	ErrMastodonAPIIncompatibility        = errors.BusinessRuleViolated("mastodon API compatibility", nil)
	ErrInvalidBusinessRule               = errors.BusinessRuleViolated("business rule", nil)
	ErrBusinessValidationFailed          = errors.ValidationFailedWithField("business rule")
	ErrInvalidRequestFormat              = errors.InvalidFormat("request", "expected format")
	ErrUnsupportedOperation              = errors.FormatNotSupported("operation")
)

Mastodon business logic errors

View Source
var (
	// UsernamePattern is the regex pattern for valid usernames
	// Alphanumeric characters, underscores, and hyphens, 1-30 chars
	UsernamePattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,30}$`)

	// StatusIDPattern is the regex pattern for valid status IDs
	// Should be numeric or UUID-like format
	StatusIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]+$`)
)

Username validation patterns

View Source
var (
	// Standard limits used across the API
	StandardTimelineLimit   = 40
	StandardFollowLimit     = 80
	StandardSearchLimit     = 80
	StandardHashtagLimit    = 200
	StandardAdminLimit      = 100
	StandardFederationLimit = 200
)

Common API limit validators for different endpoint types

View Source
var (
	// ActorTypePattern matches valid ActivityPub actor types
	ActorTypePattern = regexp.MustCompile(`^(Person|Service|Group|Organization|Application)$`)

	// ActivityTypePattern matches valid ActivityPub activity types
	ActivityTypePattern = regexp.MustCompile(`^(Create|Update|Delete|Follow|Accept|Reject|Like|Announce|Undo|Block|Move|Add|Remove)$`)

	// ObjectTypePattern matches valid ActivityPub object types
	ObjectTypePattern = regexp.MustCompile(`^(Note|Article|Video|Image|Audio|Document|Page|Event|Place|Profile|Relationship|Tombstone)$`)

	// PublicAddress is the ActivityPub public addressing URI
	PublicAddress = "https://www.w3.org/ns/activitystreams#Public"

	// WebfingerPattern matches acct: URIs for webfinger
	WebfingerPattern = regexp.MustCompile(`^acct:([^@]+)@([^@]+)$`)

	// ActivityPubMimeTypes are accepted Content-Type headers for ActivityPub
	ActivityPubMimeTypes = []string{
		"application/activity+json",
		"application/ld+json",
		"application/json",
	}
)

ActivityPub validation patterns

View Source
var (
	// StatusIDPattern validates Mastodon status IDs (numeric or alphanumeric)
	MastodonStatusIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_\-]+$`)

	// AccountIDPattern validates Mastodon account IDs
	MastodonAccountIDPattern = regexp.MustCompile(`^[a-zA-Z0-9_\-\.@:\/]+$`)

	// HashtagPattern validates hashtag format
	HashtagPattern = regexp.MustCompile(`^[a-zA-Z0-9_]+$`)

	// LanguageCodePattern validates ISO 639-1 language codes
	LanguageCodePattern = regexp.MustCompile(`^[a-z]{2}$`)

	// MimeTypePattern validates basic MIME type format
	MimeTypePattern = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_]*\/[a-zA-Z0-9][a-zA-Z0-9!#$&\-\^_.]*$`)
)

Mastodon API validation patterns

View Source
var DefaultCookieConfig = CookieConfig{
	Domain:   "",
	Path:     "/",
	Secure:   true,
	HTTPOnly: true,
	SameSite: http.SameSiteStrictMode,
}

DefaultCookieConfig provides secure defaults

View Source
var (
	ErrNoBoundaryInContentType = errors.FormBoundaryMissing()
)

Form parsing errors

View Source
var SecurityLogger *zap.Logger

SecurityLogger is the global logger for security-related events

View Source
var ValidFilterActions = []string{"warn", "hide", "blur"}

ValidFilterActions defines the valid Mastodon filter actions

View Source
var ValidFilterContexts = []string{"home", "notifications", "public", "thread", "account"}

ValidFilterContexts defines the valid Mastodon filter contexts

View Source
var ValidNotificationTypes = []string{"mention", "status", "reblog", "follow", "follow_request", "favourite", "poll", "update", "admin.sign_up", "admin.report"}

ValidNotificationTypes defines the valid Mastodon notification types

View Source
var ValidReportCategories = []string{"spam", "violation", "other"}

ValidReportCategories defines the valid Mastodon report categories

View Source
var ValidVisibilityLevels = []string{"public", "unlisted", "private", "direct"}

ValidVisibilityLevels defines the valid Mastodon visibility levels

Functions

func Accepted

func Accepted(body any) *events.APIGatewayV2HTTPResponse

Accepted returns a 202 Accepted response

func ActivityPubHeaders

func ActivityPubHeaders() map[string]string

ActivityPubHeaders returns headers for ActivityPub responses

func ActivityPubResponse

func ActivityPubResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse

ActivityPubResponse creates a successful ActivityPub response

func AddLinkHeader

func AddLinkHeader(headers map[string]string, baseURL string, endpoint string, cursor string, params map[string]string)

AddLinkHeader adds a Link header for pagination

func AddPaginationHeaders

func AddPaginationHeaders(headers map[string]string, baseURL string, endpoint string, cursor string, params map[string]string, totalCount int)

AddPaginationHeaders adds both Link and custom pagination headers

func BadRequest

func BadRequest(err error) *events.APIGatewayV2HTTPResponse

BadRequest returns a 400 Bad Request response

func BuildLinkHeader

func BuildLinkHeader(baseURL string, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string) string

BuildLinkHeader creates a Link header for pagination following RFC 5988 This consolidates the link header building logic found across multiple handlers

func CalculateHasMore

func CalculateHasMore(itemCount, requestedLimit int) bool

CalculateHasMore determines if there are more results based on the returned items count This helps with pagination logic across different storage backends

func CalculateOffset

func CalculateOffset(page, limit int) int

CalculateOffset calculates the offset from page number and limit

func CalculatePage

func CalculatePage(offset, limit int) int

CalculatePage calculates the page number from offset and limit

func CheckLambdaResources

func CheckLambdaResources(operation string) error

CheckLambdaResources is a convenience function to check resources using the global monitor

func ConfigureAllowedRedirectHosts

func ConfigureAllowedRedirectHosts(hosts []string)

ConfigureAllowedRedirectHosts updates the allowed redirect hosts

func Conflict

func Conflict(err error) *events.APIGatewayV2HTTPResponse

Conflict returns a 409 Conflict response

func CreateAPIErrorMiddleware

func CreateAPIErrorMiddleware(logger *zap.Logger) apptheory.Middleware

CreateAPIErrorMiddleware creates error middleware specifically for API services

func CreateFederationErrorMiddleware

func CreateFederationErrorMiddleware(logger *zap.Logger) apptheory.Middleware

CreateFederationErrorMiddleware creates error middleware specifically for federation services

func CreateGraphQLErrorMiddleware

func CreateGraphQLErrorMiddleware(logger *zap.Logger) apptheory.Middleware

CreateGraphQLErrorMiddleware creates error middleware specifically for GraphQL services

func CreateStandardErrorMiddleware

func CreateStandardErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

CreateStandardErrorMiddleware creates the standard error handling middleware stack

func Created

func Created(body any) *events.APIGatewayV2HTTPResponse

Created returns a 201 Created response

func DeleteSecureCookie

func DeleteSecureCookie(w http.ResponseWriter, name string)

DeleteSecureCookie removes a cookie securely

func DetectJSONBomb

func DetectJSONBomb(data []byte) error

DetectJSONBomb checks for obvious JSON bomb patterns

func DevelopmentErrorMiddleware

func DevelopmentErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

DevelopmentErrorMiddleware creates error middleware optimized for development

func ErrFeatureDisabled

func ErrFeatureDisabled(feature string) error

ErrFeatureDisabled creates an error indicating a feature is disabled

func ErrorFromType

func ErrorFromType(err error) *events.APIGatewayV2HTTPResponse

ErrorFromType returns an appropriate error response based on error type

func ErrorHandlingMiddleware

func ErrorHandlingMiddleware(config ErrorMiddlewareConfig) apptheory.Middleware

ErrorHandlingMiddleware creates centralized error handling middleware for Lift

func ErrorRecoveryMiddleware

func ErrorRecoveryMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

ErrorRecoveryMiddleware provides graceful degradation for critical errors

func ErrorResponseWithCode

func ErrorResponseWithCode(statusCode int, code string, err error) *events.APIGatewayV2HTTPResponse

ErrorResponseWithCode creates an error response with a specific code

func EscapeHTML

func EscapeHTML(s string) string

EscapeHTML escapes HTML special characters

func ExtractAuthHeader

func ExtractAuthHeader(ctx *apptheory.Context) string

ExtractAuthHeader extracts Authorization header with multiple fallback patterns This consolidates the various patterns found across the codebase

func ExtractBearerToken

func ExtractBearerToken(authHeader string) (string, error)

ExtractBearerToken extracts the token from the Authorization header This consolidates auth.ExtractBearerToken to avoid import cycles

func ExtractHashtags

func ExtractHashtags(content string) []string

ExtractHashtags extracts hashtags from content

func ExtractMentions

func ExtractMentions(content string) []string

ExtractMentions extracts mentions from content

func Forbidden

func Forbidden(err error) *events.APIGatewayV2HTTPResponse

Forbidden returns a 403 Forbidden response

func FormatMastodonTimestamp

func FormatMastodonTimestamp(t time.Time) string

FormatMastodonTimestamp formats a time to Mastodon-compatible ISO8601

func FormatUntrustedHTTPBodySnippet

func FormatUntrustedHTTPBodySnippet(body []byte, truncated bool) string

FormatUntrustedHTTPBodySnippet returns a stable string snippet for logs and stored error fields.

func GenerateActivityPubID

func GenerateActivityPubID(domain, objectType, localID string) string

GenerateActivityPubID generates a standard ActivityPub ID

func GenerateActivityPubIDULID

func GenerateActivityPubIDULID(domain, objectType string) string

GenerateActivityPubIDULID generates an ActivityPub ID using the global generator

func GenerateActorID

func GenerateActorID(domain, username string) string

GenerateActorID generates a standard actor ID

func GenerateID

func GenerateID() string

GenerateID generates a ULID using the global generator

func GenerateJobIDULID

func GenerateJobIDULID() string

GenerateJobIDULID generates a job ID using the global generator

func GenerateMediaIDULID

func GenerateMediaIDULID() string

GenerateMediaIDULID generates a media ID using the global generator

func GenerateNoteIDULID

func GenerateNoteIDULID() string

GenerateNoteIDULID generates a note ID using the global generator

func GenerateNumericID

func GenerateNumericID(username string) string

GenerateNumericID generates a stable numeric ID from a username This ensures the same username always generates the same ID

func GenerateNumericIDFromActorID

func GenerateNumericIDFromActorID(actorID string) string

GenerateNumericIDFromActorID generates a stable numeric ID from an ActivityPub actor ID

func GenerateObjectID

func GenerateObjectID(domain, objectType, objectID string) string

GenerateObjectID generates a standard object ID

func GenerateOperationIDULID

func GenerateOperationIDULID() string

GenerateOperationIDULID generates an operation ID using the global generator

func GenerateRequestIDULID

func GenerateRequestIDULID() string

GenerateRequestIDULID generates a request ID using the global generator

func GenerateSessionIDULID

func GenerateSessionIDULID() string

GenerateSessionIDULID generates a session ID using the global generator

func GenerateSnowflakeID

func GenerateSnowflakeID() string

GenerateSnowflakeID generates a Mastodon-compatible snowflake ID

func GenerateStatusID

func GenerateStatusID() string

GenerateStatusID generates a status ID using the global generator

func GetAPIHeaders

func GetAPIHeaders() map[string]string

GetAPIHeaders returns standard headers for API responses including CORS

func GetBaseURL

func GetBaseURL(ctx *apptheory.Context) string

GetBaseURL constructs the base URL for the current request

func GetCORSHeaders

func GetCORSHeaders() map[string]string

GetCORSHeaders returns standard CORS headers for API responses

func GetCookie

func GetCookie(headers map[string]string, name string) string

GetCookie retrieves a specific cookie value from headers

func GetEnvInt

func GetEnvInt(key string, defaultValue int) int

GetEnvInt gets an integer environment variable with a default value DEPRECATED: Use centralized config.Get() for application configuration instead This consolidates the common pattern: strconv.Atoi(os.Getenv(key)); err == nil Only use this for AWS Lambda runtime variables or when config is not available

func GetLambdaFunctionName

func GetLambdaFunctionName() string

GetLambdaFunctionName returns the AWS Lambda function name

func GetLambdaFunctionVersion

func GetLambdaFunctionVersion() string

GetLambdaFunctionVersion returns the AWS Lambda function version

func GetLambdaInitializationType

func GetLambdaInitializationType() string

GetLambdaInitializationType returns the AWS Lambda initialization type

func GetLambdaLogGroupName

func GetLambdaLogGroupName() string

GetLambdaLogGroupName returns the AWS Lambda log group name

func GetLambdaLogStreamName

func GetLambdaLogStreamName() string

GetLambdaLogStreamName returns the AWS Lambda log stream name

func GetLambdaMemorySize

func GetLambdaMemorySize() string

GetLambdaMemorySize returns the AWS Lambda function memory size

func GetLambdaMemorySizeInt

func GetLambdaMemorySizeInt() (int, error)

GetLambdaMemorySizeInt returns the AWS Lambda function memory size as an integer

func GetSafeRedirectURL

func GetSafeRedirectURL(redirectURL, currentHost, defaultPath string) string

GetSafeRedirectURL returns a validated redirect URL or the default

func GetStandardActivityPubContext

func GetStandardActivityPubContext() []interface{}

GetStandardActivityPubContext returns the standard ActivityPub JSON-LD context

func GetXRayTraceID

func GetXRayTraceID() string

GetXRayTraceID returns the X-Ray trace ID

func HandleError

func HandleError(logger *zap.Logger, err error) (int, string)

HandleError processes an error and returns safe HTTP response values

func HasAllScopes

func HasAllScopes(claims Claims, scopes []string) bool

HasAllScopes checks if claims has all of the provided scopes

func HasAnyScope

func HasAnyScope(claims Claims, scopes []string) bool

HasAnyScope checks if claims has any of the provided scopes

func HashOAuthClientSecret

func HashOAuthClientSecret(secret string) (string, error)

HashOAuthClientSecret returns a versioned hash string suitable for storage.

func Headers

func Headers() map[string]string

Headers returns common headers for responses

func IdentityTransformer

func IdentityTransformer[T any](_ context.Context, input T) (T, error)

IdentityTransformer returns the input unchanged (useful for pipeline testing)

func InitGlobalIDGenerator

func InitGlobalIDGenerator(logger *zap.Logger)

InitGlobalIDGenerator initializes the global ID generator

func InitSecurityLogger

func InitSecurityLogger()

InitSecurityLogger initializes the security-specific logger

func InsecureTLSOverrideEnabled

func InsecureTLSOverrideEnabled() bool

InsecureTLSOverrideEnabled reports whether the runtime explicitly allows disabling TLS verification.

This is a defense-in-depth guardrail: callers must opt-in via an environment variable before any "insecure TLS" code path can be activated.

func InternalServerError

func InternalServerError(err error) *events.APIGatewayV2HTTPResponse

InternalServerError returns a 500 Internal Server Error response

func IsAuthentication

func IsAuthentication(err error) bool

IsAuthentication returns true if the error is an authentication error

func IsAuthorization

func IsAuthorization(err error) bool

IsAuthorization returns true if the error is an authorization error

func IsColdStart

func IsColdStart() bool

IsColdStart returns true if this is a cold start

func IsConflict

func IsConflict(err error) bool

IsConflict returns true if the error is a conflict error

func IsFederation

func IsFederation(err error) bool

IsFederation returns true if the error is a federation error

func IsModerationMLEnabled

func IsModerationMLEnabled(_ context.Context, tenantID string) bool

IsModerationMLEnabled checks if ML moderation is enabled for a request. It checks both the global flag and optional tenant allow-list.

func IsNotFound

func IsNotFound(err error) bool

IsNotFound returns true if the error is a not found error

func IsProcessableMediaType

func IsProcessableMediaType(mediaType string) bool

IsProcessableMediaType checks if media type can be processed (Image, Video, Document)

func IsPubliclyVisible

func IsPubliclyVisible(visibility string) bool

IsPubliclyVisible checks if content is visible to public (public or unlisted)

func IsRunningInLambda

func IsRunningInLambda() bool

IsRunningInLambda returns true if running in AWS Lambda environment

func IsValidation

func IsValidation(err error) bool

IsValidation returns true if the error is a validation error

func IsXRayEnabled

func IsXRayEnabled() bool

IsXRayEnabled returns true if X-Ray tracing is enabled

func JSONResponse

func JSONResponse(statusCode int, body any) *events.APIGatewayV2HTTPResponse

JSONResponse creates a successful JSON response

func JoinKey

func JoinKey(parts ...string) string

JoinKey joins parts into a composite key For example, JoinKey("user", "123") becomes "user#123"

func LogAuthFailure

func LogAuthFailure(reason string, username string, ip string, userAgent string, requestID string)

LogAuthFailure logs authentication failures

func LogCSRFFailure

func LogCSRFFailure(reason string, username string, ip string, path string, userAgent string, requestID string)

LogCSRFFailure logs CSRF validation failures

func LogRateLimit

func LogRateLimit(userID string, ip string, endpoint string, limit int, requestID string)

LogRateLimit logs rate limit exceeded events

func LogSecurityEvent

func LogSecurityEvent(event string, fields ...zap.Field)

LogSecurityEvent logs a security-relevant event

func LogSuspiciousActivity

func LogSuspiciousActivity(activity string, userID string, ip string, details map[string]any, requestID string)

LogSuspiciousActivity logs general suspicious activity

func Logger

func Logger() *zap.Logger

Logger returns the global logger instance

func Marshal

func Marshal(v any) ([]byte, error)

Marshal serializes v to JSON with ActivityPub optimizations Using standard library json for now (will upgrade to json/v2 when stable)

func MarshalString

func MarshalString(v any) (string, error)

MarshalString is optimized for string output

func MaskSensitiveData

func MaskSensitiveData(data string) string

MaskSensitiveData masks sensitive information in logs

func MethodNotAllowed

func MethodNotAllowed(err error) *events.APIGatewayV2HTTPResponse

MethodNotAllowed returns a 405 error response

func MustCheckModerationMLAccess

func MustCheckModerationMLAccess(ctx context.Context, tenantID string) error

MustCheckModerationMLAccess returns an error if ML moderation is not available. Useful for resolver-level validation.

func NewDecoder

func NewDecoder(r io.Reader) *json.Decoder

NewDecoder creates a streaming JSON decoder

func NewEncoder

func NewEncoder(w io.Writer) *json.Encoder

NewEncoder creates a streaming JSON encoder

func NoContent

func NoContent() *events.APIGatewayV2HTTPResponse

NoContent returns a 204 No Content response

func NotFound

func NotFound(err error) *events.APIGatewayV2HTTPResponse

NotFound returns a 404 Not Found response

func NotFoundMiddleware

func NotFoundMiddleware() apptheory.Middleware

NotFoundMiddleware creates middleware that handles 404 errors gracefully

func OK

OK returns a 200 OK response

func ParseAccountStatusesLimit

func ParseAccountStatusesLimit(limitStr string) (int, error)

ParseAccountStatusesLimit parses and validates limits for account status listings

func ParseActivityPubObject

func ParseActivityPubObject(body []byte, v any) error

ParseActivityPubObject safely parses an ActivityPub object with JSON bomb detection Use this for ActivityPub objects that may have extensions

func ParseAdminLimit

func ParseAdminLimit(limitStr string) (int, error)

ParseAdminLimit parses limit for admin endpoints (max 100)

func ParseAndValidateAPILimit

func ParseAndValidateAPILimit(limitStr string, maxLimit int) (int, error)

ParseAndValidateAPILimit parses and validates common API limit parameters This consolidates the very common pattern in API handlers

func ParseAndValidateActivityPubLimit

func ParseAndValidateActivityPubLimit(limitStr string) (int, error)

ParseAndValidateActivityPubLimit parses and validates limits for ActivityPub collections

func ParseAndValidateBoolean

func ParseAndValidateBoolean(value string) (bool, error)

ParseAndValidateBoolean parses a boolean parameter from string

func ParseAndValidateIntWithBounds

func ParseAndValidateIntWithBounds(field, value string, minValue, maxValue, defaultValue int) (int, error)

ParseAndValidateIntWithBounds parses a string to int and validates bounds This consolidates the common pattern: strconv.Atoi(str); err == nil && val > min && val <= max

func ParseCookies

func ParseCookies(cookieHeader string) map[string]string

ParseCookies extracts cookies from request headers (Lambda compatible)

func ParseFederationLimit

func ParseFederationLimit(limitStr string) (int, error)

ParseFederationLimit parses limit for federation endpoints (max 200)

func ParseFollowLimit

func ParseFollowLimit(limitStr string) (int, error)

ParseFollowLimit parses limit for follow/follower endpoints (max 80)

func ParseFormURLEncoded

func ParseFormURLEncoded(body string) (map[string]string, error)

ParseFormURLEncoded parses URL-encoded form data

func ParseFormValues

func ParseFormValues(body string) (url.Values, error)

ParseFormValues parses URL-encoded form data

func ParseHTTPResponse

func ParseHTTPResponse(r io.Reader, v any) error

ParseHTTPResponse safely parses an HTTP response body Use this when fetching data from external sources

func ParseHashtagLimit

func ParseHashtagLimit(limitStr string) (int, error)

ParseHashtagLimit parses limit for hashtag endpoints (max 200)

func ParseMastodonTimestamp

func ParseMastodonTimestamp(timestamp string) (time.Time, error)

ParseMastodonTimestamp parses a Mastodon timestamp

func ParseMultipartForm

func ParseMultipartForm(body string, contentType string) (map[string]string, error)

ParseMultipartForm parses multipart form data from a request body

func ParseRequestBody

func ParseRequestBody(body []byte, v any) error

ParseRequestBody safely parses a request body with JSON bomb detection Use this for API endpoints with known request structures

func ParseRequestBodyWithValidation

func ParseRequestBodyWithValidation(ctx *apptheory.Context, target interface{}, fieldName string) (*apptheory.Response, error)

ParseRequestBodyWithValidation parses request body with validation error response

func ParseRequestWithComplexFallback

func ParseRequestWithComplexFallback(ctx *apptheory.Context, target interface{}) error

ParseRequestWithComplexFallback handles the complex fallback pattern found in quotes.go and other files

func ParseRequestWithCustomError

func ParseRequestWithCustomError(ctx *apptheory.Context, target interface{}, errorMessage string) (*apptheory.Response, error)

ParseRequestWithCustomError allows custom error handling

func ParseRequestWithFallback

func ParseRequestWithFallback(ctx *apptheory.Context, target interface{}) error

ParseRequestWithFallback attempts to parse request using ctx.ParseRequest with fallback strategies This consolidates the common pattern of:

if err := ctx.ParseRequest(&req); err != nil {
  // Fallback logic for test environments
  ...
}

func ParseRequestWithValidation

func ParseRequestWithValidation(ctx *apptheory.Context, target interface{}) (*apptheory.Response, error)

ParseRequestWithValidation combines parsing with common validation responses

func ParseSearchLimit

func ParseSearchLimit(limitStr string) (int, error)

ParseSearchLimit parses limit for search endpoints (max 80)

func ParseSearchOffset

func ParseSearchOffset(offsetStr string) (int, error)

ParseSearchOffset parses and validates search offset parameters

func ParseStatusContextLimit

func ParseStatusContextLimit(limitStr string) (int, error)

ParseStatusContextLimit parses and validates limits for status context endpoints

func ParseStatusTimelineLimit

func ParseStatusTimelineLimit(limitStr string) (int, error)

ParseStatusTimelineLimit parses and validates limits for status timelines (home, public)

func ParseTimelineLimit

func ParseTimelineLimit(limitStr string) (int, error)

ParseTimelineLimit parses limit for timeline endpoints (max 40)

func ProductionErrorMiddleware

func ProductionErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

ProductionErrorMiddleware creates error middleware optimized for production

func ReadRequestBody

func ReadRequestBody(body io.Reader, maxSize int64) ([]byte, error)

ReadRequestBody safely reads a request body with a size limit If maxSize is 0 or negative, MaxRequestSize is used as default

func ReadRequestBodyString

func ReadRequestBodyString(body io.Reader, maxSize int64) (string, error)

ReadRequestBodyString is a convenience function that returns the body as a string

func ReadUntrustedHTTPResponseBody

func ReadUntrustedHTTPResponseBody(r io.Reader, maxBytes int64) ([]byte, bool, error)

ReadUntrustedHTTPResponseBody reads up to maxBytes from r and reports whether the response body was truncated. It never allocates more than maxBytes+1.

func RecordBusinessMetric

func RecordBusinessMetric(_ context.Context, metricType, _ string, actorID string, _ map[string]interface{}) error

RecordBusinessMetric records business metrics using the existing metrics infrastructure

func RespondAccountNotFound

func RespondAccountNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondAccountNotFound handles account not found errors by returning a 404 not found response

func RespondActorNotFound

func RespondActorNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondActorNotFound handles actor not found errors by returning a 404 not found response

func RespondAlreadyExists

func RespondAlreadyExists(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondAlreadyExists handles resource already exists conflicts by returning a 409 conflict response

func RespondAuthErrorWithCode

func RespondAuthErrorWithCode(ctx *apptheory.Context, errorCode int, err error) (*apptheory.Response, error)

RespondAuthErrorWithCode handles authentication/authorization errors with status code

func RespondBadRequest

func RespondBadRequest(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondBadRequest handles validation and bad request errors (400) - now using centralized errors

func RespondConflict

func RespondConflict(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondConflict handles resource conflict errors (409) - now using centralized errors

func RespondConversationNotFound

func RespondConversationNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondConversationNotFound handles conversation not found errors by returning a 404 not found response

func RespondCreateError

func RespondCreateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)

RespondCreateError handles errors from create operations - now using centralized errors

func RespondDatabaseError

func RespondDatabaseError(ctx *apptheory.Context) (*apptheory.Response, error)

RespondDatabaseError handles database errors by returning a 500 internal server error response

func RespondDeleteError

func RespondDeleteError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)

RespondDeleteError handles errors from delete operations - now using centralized errors

func RespondExpiredToken

func RespondExpiredToken(_ *apptheory.Context) (*apptheory.Response, error)

RespondExpiredToken handles expired token errors by returning a 401 unauthorized response

func RespondFailedToCreate

func RespondFailedToCreate(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondFailedToCreate handles resource creation failures by returning a 500 internal server error response

func RespondFailedToDelete

func RespondFailedToDelete(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondFailedToDelete handles resource deletion failures by returning a 500 internal server error response

func RespondFailedToGet

func RespondFailedToGet(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondFailedToGet handles resource retrieval failures by returning a 500 internal server error response

func RespondFailedToUpdate

func RespondFailedToUpdate(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondFailedToUpdate handles resource update failures by returning a 500 internal server error response

func RespondFilterNotFound

func RespondFilterNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondFilterNotFound handles filter not found errors by returning a 404 not found response

func RespondForbidden

func RespondForbidden(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondForbidden handles authorization/permission errors (403) - now using centralized errors

func RespondGetError

func RespondGetError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)

RespondGetError handles errors from get/fetch operations - now using centralized errors

func RespondGone

func RespondGone(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondGone handles resource gone errors (410) with optional custom message

func RespondInsufficientScope

func RespondInsufficientScope(_ *apptheory.Context, requiredScope ...string) (*apptheory.Response, error)

RespondInsufficientScope handles insufficient OAuth scope errors by returning a 403 forbidden response

func RespondInternalServerError

func RespondInternalServerError(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondInternalServerError handles internal server errors (500) - now using centralized errors

func RespondInvalidContent

func RespondInvalidContent(ctx *apptheory.Context) (*apptheory.Response, error)

RespondInvalidContent handles invalid content errors by returning a 422 unprocessable entity response

func RespondInvalidParameter

func RespondInvalidParameter(ctx *apptheory.Context, paramName string) (*apptheory.Response, error)

RespondInvalidParameter handles invalid parameter errors by returning a 400 bad request response

func RespondInvalidRequest

func RespondInvalidRequest(ctx *apptheory.Context) (*apptheory.Response, error)

RespondInvalidRequest handles general invalid request errors by returning a 400 bad request response

func RespondInvalidToken

func RespondInvalidToken(_ *apptheory.Context) (*apptheory.Response, error)

RespondInvalidToken handles invalid token errors by returning a 401 unauthorized response

func RespondLegacyError

func RespondLegacyError(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)

RespondLegacyError maintains compatibility with existing map[string]string{"error": "message"} pattern

func RespondMethodNotAllowed

func RespondMethodNotAllowed(_ *apptheory.Context) (*apptheory.Response, error)

RespondMethodNotAllowed handles HTTP method not allowed errors by returning a 405 response

func RespondMissingAccountID

func RespondMissingAccountID(ctx *apptheory.Context) (*apptheory.Response, error)

RespondMissingAccountID handles missing account ID errors by returning a 400 bad request response

func RespondMissingAuth

func RespondMissingAuth(ctx *apptheory.Context) (*apptheory.Response, error)

RespondMissingAuth handles authentication required errors by returning a 401 unauthorized response

func RespondMissingParameter

func RespondMissingParameter(ctx *apptheory.Context, paramName string) (*apptheory.Response, error)

RespondMissingParameter handles missing required parameter errors by returning a 400 bad request response

func RespondMissingStatusID

func RespondMissingStatusID(ctx *apptheory.Context) (*apptheory.Response, error)

RespondMissingStatusID handles missing status ID errors by returning a 400 bad request response

func RespondNotAuthorized

func RespondNotAuthorized(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondNotAuthorized handles general authorization errors by returning a 403 forbidden response

func RespondNotAuthorizedToDelete

func RespondNotAuthorizedToDelete(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondNotAuthorizedToDelete handles deletion authorization errors by returning a 403 forbidden response

func RespondNotAuthorizedToModify

func RespondNotAuthorizedToModify(ctx *apptheory.Context, resource string) (*apptheory.Response, error)

RespondNotAuthorizedToModify handles modification authorization errors by returning a 403 forbidden response

func RespondNotFound

func RespondNotFound(_ *apptheory.Context, resource ...string) (*apptheory.Response, error)

RespondNotFound handles resource not found errors (404) - now using centralized errors

func RespondRateLimited

func RespondRateLimited(_ *apptheory.Context) (*apptheory.Response, error)

RespondRateLimited handles rate limit exceeded errors by returning a 429 response

func RespondServiceUnavailable

func RespondServiceUnavailable(_ *apptheory.Context, service ...string) (*apptheory.Response, error)

RespondServiceUnavailable handles service unavailable errors (503) with optional service name

func RespondStatusNotFound

func RespondStatusNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondStatusNotFound handles status not found errors by returning a 404 not found response

func RespondStatusTooLong

func RespondStatusTooLong(ctx *apptheory.Context) (*apptheory.Response, error)

RespondStatusTooLong handles status text too long errors by returning a 422 unprocessable entity response

func RespondSuccess

func RespondSuccess(_ *apptheory.Context, data interface{}) (*apptheory.Response, error)

RespondSuccess handles successful responses with data

func RespondUnauthorized

func RespondUnauthorized(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondUnauthorized handles authentication errors (401) - now using centralized errors

func RespondUnauthorizedWithDescription

func RespondUnauthorizedWithDescription(_ *apptheory.Context, description string) (*apptheory.Response, error)

RespondUnauthorizedWithDescription handles authentication errors (401) with additional description

func RespondUnprocessableEntity

func RespondUnprocessableEntity(_ *apptheory.Context, message ...string) (*apptheory.Response, error)

RespondUnprocessableEntity handles unprocessable entity errors (422) with optional custom message

func RespondUpdateError

func RespondUpdateError(ctx *apptheory.Context, resource string, err error) (*apptheory.Response, error)

RespondUpdateError handles errors from update operations - now using centralized errors

func RespondUserNotFound

func RespondUserNotFound(ctx *apptheory.Context) (*apptheory.Response, error)

RespondUserNotFound handles user not found errors by returning a 404 not found response

func RespondValidationError

func RespondValidationError(_ *apptheory.Context, err error) (*apptheory.Response, error)

RespondValidationError handles validation failed errors - now using centralized errors

func RespondValidationOrError

func RespondValidationOrError(ctx *apptheory.Context, err error) (*apptheory.Response, error)

RespondValidationOrError handles validation errors and other errors appropriately

func RespondWithAppError

func RespondWithAppError(_ *apptheory.Context, appErr *errors.AppError) (*apptheory.Response, error)

RespondWithAppError creates a response from a centralized AppError

func RespondWithError

func RespondWithError(ctx *apptheory.Context, code int, message string) (*apptheory.Response, error)

RespondWithError is an alias for SendError for consistency with existing patterns

func RespondWithErrorAndDescription

func RespondWithErrorAndDescription(_ *apptheory.Context, statusCode int, errorMsg, description string) (*apptheory.Response, error)

RespondWithErrorAndDescription creates a detailed error response

func RespondWithErrorCode

func RespondWithErrorCode(_ *apptheory.Context, statusCode int, errorMsg, code string) (*apptheory.Response, error)

RespondWithErrorCode creates an error response with an error code

func RespondWithErrorMessage

func RespondWithErrorMessage(_ *apptheory.Context, statusCode int, message string) (*apptheory.Response, error)

RespondWithErrorMessage creates a standardized error response with custom message

func RespondWithJSON

func RespondWithJSON(ctx *apptheory.Context, code int, data interface{}) (*apptheory.Response, error)

RespondWithJSON is an alias for SendJSON for consistency with existing patterns

func RunningUnitTests

func RunningUnitTests() bool

RunningUnitTests reports whether the current binary is the Go test harness. It uses the convention that test binaries end with the .test suffix.

func SafeRedirect

func SafeRedirect(w http.ResponseWriter, r *http.Request, defaultPath string)

SafeRedirect performs a safe redirect with validation

func SafeRedirectOrDefault

func SafeRedirectOrDefault(w http.ResponseWriter, r *http.Request, redirectURL, defaultPath string)

SafeRedirectOrDefault redirects to the given URL if safe, otherwise to default

func SafeUnmarshalJSON

func SafeUnmarshalJSON(data []byte, v any) error

SafeUnmarshalJSON is a convenience function for safe JSON unmarshaling

func SafeUnmarshalJSONWithoutUnknownFields

func SafeUnmarshalJSONWithoutUnknownFields(data []byte, v any) error

SafeUnmarshalJSONWithoutUnknownFields unmarshals JSON without DisallowUnknownFields Use this for ActivityPub objects which may have extensions

func SanitizeActivityPubObjectDefault

func SanitizeActivityPubObjectDefault(obj map[string]any)

SanitizeActivityPubObjectDefault sanitizes an object using the default sanitizer

func SanitizeContent

func SanitizeContent(content string) string

SanitizeContent is a convenience function using the default sanitizer

func SanitizeHTML

func SanitizeHTML(content string) string

SanitizeHTML removes or escapes HTML content for Mastodon API responses

func SanitizeInput

func SanitizeInput(input string) string

SanitizeInput performs basic input sanitization

func SendAccepted

func SendAccepted(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)

SendAccepted sends a 202 Accepted response with data

func SendBool

func SendBool(ctx *apptheory.Context, value bool) (*apptheory.Response, error)

SendBool sends a boolean response

func SendCount

func SendCount(ctx *apptheory.Context, count int) (*apptheory.Response, error)

SendCount sends a count response

func SendCreated

func SendCreated(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)

SendCreated sends a 201 Created response with data

func SendEmpty

func SendEmpty(ctx *apptheory.Context) (*apptheory.Response, error)

SendEmpty sends an empty array response (used in many Mastodon endpoints)

func SendEmptyObject

func SendEmptyObject(ctx *apptheory.Context) (*apptheory.Response, error)

SendEmptyObject sends an empty object response

func SendError

func SendError(_ *apptheory.Context, code int, message string) (*apptheory.Response, error)

SendError is a convenience function for sending standardized error responses with Lift This consolidates the pattern: return apptheory.JSON(code, map[string]string{"error": message})

func SendHealthCheck

func SendHealthCheck(ctx *apptheory.Context, health HealthCheckResponse) (*apptheory.Response, error)

SendHealthCheck sends a health check response

func SendID

func SendID(ctx *apptheory.Context, id string) (*apptheory.Response, error)

SendID sends an ID response

func SendJSON

func SendJSON(_ *apptheory.Context, code int, data interface{}) (*apptheory.Response, error)

SendJSON is a convenience function for sending successful JSON responses with Lift This consolidates the pattern: return apptheory.JSON(code, data)

func SendMastodonAccount

func SendMastodonAccount(ctx *apptheory.Context, account MastodonAccount) (*apptheory.Response, error)

SendMastodonAccount sends a Mastodon-formatted account response

func SendMastodonAccounts

func SendMastodonAccounts(ctx *apptheory.Context, accounts []MastodonAccount) (*apptheory.Response, error)

SendMastodonAccounts sends a Mastodon-formatted accounts array response

func SendMastodonError

func SendMastodonError(_ *apptheory.Context, code int, errorMsg string) (*apptheory.Response, error)

SendMastodonError sends Mastodon API-compatible error responses Mastodon clients expect a specific error format for proper error handling

func SendMastodonStatus

func SendMastodonStatus(ctx *apptheory.Context, status MastodonStatus) (*apptheory.Response, error)

SendMastodonStatus sends a Mastodon-formatted status response

func SendMastodonStatuses

func SendMastodonStatuses(ctx *apptheory.Context, statuses []MastodonStatus) (*apptheory.Response, error)

SendMastodonStatuses sends a Mastodon-formatted statuses array response

func SendNoContent

func SendNoContent(ctx *apptheory.Context) (*apptheory.Response, error)

SendNoContent sends a 204 No Content response

func SendOK

func SendOK(ctx *apptheory.Context, data interface{}) (*apptheory.Response, error)

SendOK sends a 200 OK response with data

func SendPaginatedMastodonResponse

func SendPaginatedMastodonResponse(ctx *apptheory.Context, data interface{}, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string) (*apptheory.Response, error)

SendPaginatedMastodonResponse sends Mastodon-compatible paginated response Mastodon uses Link headers for pagination instead of response body metadata

func SendPaginatedResponse

func SendPaginatedResponse(ctx *apptheory.Context, data interface{}, pagination *Pagination) (*apptheory.Response, error)

SendPaginatedResponse sends a response with pagination metadata

func SendRateLimitHeaders

func SendRateLimitHeaders(resp *apptheory.Response, limit, remaining int, resetTime int64)

SendRateLimitHeaders sets rate limit headers

func SendStreamingMessage

func SendStreamingMessage(ctx *apptheory.Context, event string, data interface{}) (*apptheory.Response, error)

SendStreamingMessage sends a Server-Sent Events formatted message

func SetActivityPubHeaders

func SetActivityPubHeaders(resp *apptheory.Response)

SetActivityPubHeaders sets headers for ActivityPub responses

func SetCORSHeaders

func SetCORSHeaders(resp *apptheory.Response)

SetCORSHeaders sets comprehensive CORS headers for API responses.

func SetCacheHeaders

func SetCacheHeaders(resp *apptheory.Response, maxAge int)

SetCacheHeaders sets appropriate cache headers based on content type

func SetJSONHeaders

func SetJSONHeaders(resp *apptheory.Response)

SetJSONHeaders sets headers for JSON API responses

func SetNoCache

func SetNoCache(resp *apptheory.Response)

SetNoCache sets no-cache headers for sensitive responses

func SetPaginationHeaders

func SetPaginationHeaders(resp *apptheory.Response, baseURL string, params PaginationParams, hasNext, hasPrev bool, nextCursor, prevCursor string)

SetPaginationHeaders sets standard pagination headers on an AppTheory response.

func SetSecureCookie

func SetSecureCookie(w http.ResponseWriter, name, value string, maxAge int)

SetSecureCookie sets a cookie with all security flags

func SetSecureCookieWithConfig

func SetSecureCookieWithConfig(w http.ResponseWriter, name, value string, maxAge int, config CookieConfig)

SetSecureCookieWithConfig sets a cookie with custom configuration

func SetSecurityHeaders

func SetSecurityHeaders(resp *apptheory.Response)

SetSecurityHeaders sets security-related headers

func Slugify

func Slugify(value string) string

Slugify converts a human-friendly string into a lowercase, URL-safe slug.

func SplitKey

func SplitKey(key string) []string

SplitKey splits a composite key into its parts For example, "user#123" becomes ["user", "123"]

func Sync

func Sync()

Sync flushes any buffered log entries

func TimeoutErrorMiddleware

func TimeoutErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

TimeoutErrorMiddleware creates middleware that handles timeout errors

func TitleCase

func TitleCase(s string) string

TitleCase converts a string to title case (first letter uppercase)

func TooManyRequests

func TooManyRequests(err error) *events.APIGatewayV2HTTPResponse

TooManyRequests returns a 429 Too Many Requests response

func Unauthorized

func Unauthorized(err error) *events.APIGatewayV2HTTPResponse

Unauthorized returns a 401 Unauthorized response

func Unmarshal

func Unmarshal(data []byte, v any) error

Unmarshal deserializes JSON data with ActivityPub optimizations

func UnprocessableEntity

func UnprocessableEntity(err error) *events.APIGatewayV2HTTPResponse

UnprocessableEntity returns a 422 Unprocessable Entity response

func ValidateAccountBio

func ValidateAccountBio(bio string) error

ValidateAccountBio validates account bio length

func ValidateAccountFields

func ValidateAccountFields(fields interface{}) error

ValidateAccountFields validates account profile fields

func ValidateAccountID

func ValidateAccountID(accountID string) error

ValidateAccountID validates an account ID (can be username, numeric ID, or URL)

func ValidateAccountIDsParameter

func ValidateAccountIDsParameter(accountIDsStr string) ([]string, error)

ValidateAccountIDsParameter validates comma-separated account IDs (used in familiar followers)

func ValidateAccountParamID

func ValidateAccountParamID(accountID string) error

ValidateAccountParamID validates account ID from URL parameters (commonly used in API handlers)

func ValidateAccountParams

func ValidateAccountParams(params map[string]interface{}) error

ValidateAccountParams validates parameters for account updates

func ValidateAcctParameter

func ValidateAcctParameter(acct string) error

ValidateAcctParameter validates the 'acct' parameter used in account lookups

func ValidateActivityPubActivity

func ValidateActivityPubActivity(activity map[string]interface{}) error

ValidateActivityPubActivity validates an ActivityPub Activity object structure

func ValidateActivityPubActor

func ValidateActivityPubActor(actor map[string]interface{}) error

ValidateActivityPubActor validates an ActivityPub Actor object structure

func ValidateActivityPubAddressing

func ValidateActivityPubAddressing(addressing interface{}, fieldName string) error

ValidateActivityPubAddressing validates addressing fields (to, cc, bto, bcc)

func ValidateActivityPubAttachments

func ValidateActivityPubAttachments(attachments interface{}, fieldName string) error

ValidateActivityPubAttachments validates attachment arrays

func ValidateActivityPubContentType

func ValidateActivityPubContentType(contentType string) error

ValidateActivityPubContentType validates Content-Type headers for ActivityPub

func ValidateActivityPubContext

func ValidateActivityPubContext(obj map[string]interface{}) error

ValidateActivityPubContext validates the @context field

func ValidateActivityPubJSON

func ValidateActivityPubJSON(jsonStr string, fieldName string) error

ValidateActivityPubJSON validates that a string contains valid ActivityPub JSON

func ValidateActivityPubNote

func ValidateActivityPubNote(note map[string]interface{}) error

ValidateActivityPubNote validates an ActivityPub Note object structure

func ValidateActivityPubPublicKey

func ValidateActivityPubPublicKey(publicKey map[string]interface{}) error

ValidateActivityPubPublicKey validates public key objects

func ValidateActivityPubSignature

func ValidateActivityPubSignature(signature string) error

ValidateActivityPubSignature validates HTTP signature headers for ActivityPub

func ValidateActivityPubTags

func ValidateActivityPubTags(tags interface{}, fieldName string) error

ValidateActivityPubTags validates tag arrays

func ValidateActivityPubTimestamp

func ValidateActivityPubTimestamp(timestamp, fieldName string) error

ValidateActivityPubTimestamp validates timestamp formats used in ActivityPub

func ValidateActivityPubURL

func ValidateActivityPubURL(urlStr, fieldName string) error

ValidateActivityPubURL validates URLs for ActivityPub compliance

func ValidateActivityPubUsername

func ValidateActivityPubUsername(username string) error

ValidateActivityPubUsername validates usernames for ActivityPub compliance

func ValidateActivityType

func ValidateActivityType(activityType string, rules ActivityPubValidationRules) error

ValidateActivityType validates ActivityPub activity types

func ValidateActorEntity

func ValidateActorEntity(actorID, username string) error

ValidateActorEntity validates actor entity data before repository operations

func ValidateActorURI

func ValidateActorURI(actorURI string, rules ActivityPubValidationRules) error

ValidateActorURI validates ActivityPub actor URIs

func ValidateAdminScopes

func ValidateAdminScopes(claims Claims) bool

ValidateAdminScopes validates against common admin scope combinations

func ValidateAlphanumericID

func ValidateAlphanumericID(field, value string) error

ValidateAlphanumericID validates an alphanumeric ID

func ValidateAndSanitizeMediaType

func ValidateAndSanitizeMediaType(mediaType string) (string, error)

ValidateAndSanitizeMediaType validates and sanitizes media MIME types

func ValidateAndSanitizeString

func ValidateAndSanitizeString(field, value string, minLen, maxLen int) (string, error)

ValidateAndSanitizeString validates string length and sanitizes content

func ValidateApplicationName

func ValidateApplicationName(name string) error

ValidateApplicationName validates application name

func ValidateApplicationParams

func ValidateApplicationParams(params map[string]interface{}) error

ValidateApplicationParams validates parameters for application creation

func ValidateApplicationScopes

func ValidateApplicationScopes(scopes string) error

ValidateApplicationScopes validates OAuth application scopes

func ValidateBlockScopes

func ValidateBlockScopes(claims Claims) bool

ValidateBlockScopes validates against common block scope combinations

func ValidateBooleanString

func ValidateBooleanString(value string) bool

ValidateBooleanString validates boolean-like strings

func ValidateBusinessContent

func ValidateBusinessContent(content string, rules ContentValidationRules) error

ValidateBusinessContent validates content against business rules

func ValidateBusinessVisibility

func ValidateBusinessVisibility(visibility VisibilityLevel, _ string) error

ValidateBusinessVisibility validates business visibility settings

func ValidateContentOrAttachments

func ValidateContentOrAttachments(content string, attachmentIDs []string) error

ValidateContentOrAttachments validates that either content or attachments are provided

func ValidateDisplayName

func ValidateDisplayName(displayName string) error

ValidateDisplayName validates display name length

func ValidateDomainName

func ValidateDomainName(domain string) error

ValidateDomainName validates domain names for ActivityPub

func ValidateEntityID

func ValidateEntityID(id string, entityType string) error

ValidateEntityID validates entity IDs used in repository operations

func ValidateEntityIDsList

func ValidateEntityIDsList(ids []string, entityType string) error

ValidateEntityIDsList validates a list of entity IDs

func ValidateEnum

func ValidateEnum(field, value string, allowedValues []string) error

ValidateEnum validates that a value is within a set of allowed values

func ValidateEnumField

func ValidateEnumField(value string, allowedValues []string, fieldName string) error

ValidateEnumField validates enum values used in repository models

func ValidateFilterAction

func ValidateFilterAction(action string) error

ValidateFilterAction validates filter action

func ValidateFilterContext

func ValidateFilterContext(contexts []string) error

ValidateFilterContext validates filter context values

func ValidateFilterContextParam

func ValidateFilterContextParam(context interface{}) error

ValidateFilterContextParam validates filter context parameter

func ValidateFilterExpiration

func ValidateFilterExpiration(expiresIn interface{}) error

ValidateFilterExpiration validates filter expiration parameters

func ValidateFilterKeyword

func ValidateFilterKeyword(keyword string) error

ValidateFilterKeyword validates filter keyword

func ValidateFilterKeywords

func ValidateFilterKeywords(keywords interface{}) error

ValidateFilterKeywords validates filter keywords

func ValidateFilterParamID

func ValidateFilterParamID(filterID string) error

ValidateFilterParamID validates filter ID from URL parameters

func ValidateFilterParams

func ValidateFilterParams(params map[string]interface{}) error

ValidateFilterParams validates parameters for filter creation/update

func ValidateFilterTitle

func ValidateFilterTitle(title string) error

ValidateFilterTitle validates filter title

func ValidateFloatRange

func ValidateFloatRange(field string, value, minValue, maxValue float64) error

ValidateFloatRange validates that a float value is within the specified range

func ValidateFollowScopes

func ValidateFollowScopes(claims Claims) bool

ValidateFollowScopes validates against common follow scope combinations

func ValidateHTTPScheme

func ValidateHTTPScheme(scheme string) error

ValidateHTTPScheme validates HTTP/HTTPS schemes

func ValidateHashtag

func ValidateHashtag(hashtag string) error

ValidateHashtag validates hashtag format for Mastodon

func ValidateIntRange

func ValidateIntRange(field string, value, minValue, maxValue int) error

ValidateIntRange validates that an int value is within the specified range

func ValidateJSONField

func ValidateJSONField(jsonData string, fieldName string) error

ValidateJSONField validates JSON string fields in repository models

func ValidateKeywordParamID

func ValidateKeywordParamID(keywordID string) error

ValidateKeywordParamID validates keyword ID from URL parameters

func ValidateLanguageCode

func ValidateLanguageCode(language string) error

ValidateLanguageCode validates language codes (ISO 639-1 format)

func ValidateLimit

func ValidateLimit(limit int, maxValue int) error

ValidateLimit validates a limit parameter with bounds checking

func ValidateListParams

func ValidateListParams(params map[string]interface{}) error

ValidateListParams validates parameters for list creation/update

func ValidateListRepliesPolicy

func ValidateListRepliesPolicy(policy string) error

ValidateListRepliesPolicy validates list replies policy

func ValidateListTitle

func ValidateListTitle(title string) error

ValidateListTitle validates list title

func ValidateMastodonAccountID

func ValidateMastodonAccountID(accountID string) error

ValidateMastodonAccountID validates Mastodon account ID format

func ValidateMastodonFilterKeyword

func ValidateMastodonFilterKeyword(keyword string) error

ValidateMastodonFilterKeyword validates filter keyword patterns

func ValidateMastodonID

func ValidateMastodonID(id string) error

ValidateMastodonID validates Mastodon-style IDs

func ValidateMastodonMimeType

func ValidateMastodonMimeType(mimeType string) error

ValidateMastodonMimeType validates MIME types for Mastodon API

func ValidateMastodonOAuthScopes

func ValidateMastodonOAuthScopes(scopes string) ([]string, error)

ValidateMastodonOAuthScopes validates OAuth scope strings for Mastodon API

func ValidateMastodonStatusID

func ValidateMastodonStatusID(statusID string) error

ValidateMastodonStatusID validates Mastodon status ID format

func ValidateMastodonTimeline

func ValidateMastodonTimeline(params map[string]interface{}) error

ValidateMastodonTimeline validates timeline parameters

func ValidateMastodonUsername

func ValidateMastodonUsername(username string) error

ValidateMastodonUsername validates Mastodon-compatible usernames

func ValidateMediaDescription

func ValidateMediaDescription(description string) error

ValidateMediaDescription validates media attachment descriptions

func ValidateMediaEntity

func ValidateMediaEntity(mediaID, filename string, fileSize int64) error

ValidateMediaEntity validates media entity data before repository operations

func ValidateMediaFile

func ValidateMediaFile(fileData, fieldName string) error

ValidateMediaFile validates media file format/type

func ValidateMediaFocus

func ValidateMediaFocus(focus string) error

ValidateMediaFocus validates media focus point coordinates

func ValidateMediaIDs

func ValidateMediaIDs(mediaIDs interface{}) error

ValidateMediaIDs validates media attachment IDs

func ValidateMediaParams

func ValidateMediaParams(params map[string]interface{}) error

ValidateMediaParams validates parameters for media uploads

func ValidateMediaType

func ValidateMediaType(mediaType string) error

ValidateMediaType validates media attachment types

func ValidateMultipleRequiredParams

func ValidateMultipleRequiredParams(params map[string]string) error

ValidateMultipleRequiredParams validates multiple required parameters at once

func ValidateNormalizedQuery

func ValidateNormalizedQuery(query string) (string, error)

ValidateNormalizedQuery validates and normalizes search queries

func ValidateNotificationType

func ValidateNotificationType(notificationType string) error

ValidateNotificationType validates notification type

func ValidateNumericID

func ValidateNumericID(field, value string) error

ValidateNumericID validates a numeric ID (string representation)

func ValidateOffset

func ValidateOffset(offset int) error

ValidateOffset validates an offset parameter

func ValidatePaginationLimit

func ValidatePaginationLimit(limit int) int

ValidatePaginationLimit ensures the limit is within acceptable bounds

func ValidatePollParams

func ValidatePollParams(poll interface{}) error

ValidatePollParams validates poll creation parameters

func ValidatePreferenceValue

func ValidatePreferenceValue(key string, value interface{}) error

ValidatePreferenceValue validates user preference values

func ValidateQueryFilters

func ValidateQueryFilters(filters map[string]interface{}) error

ValidateQueryFilters validates filter parameters for repository queries

func ValidateQueryLimit

func ValidateQueryLimit(limit int, maxLimit int, operationType string) error

ValidateQueryLimit validates query limits with repository-specific maximums

func ValidateQueryOffset

func ValidateQueryOffset(offset int, maxOffset int) error

ValidateQueryOffset validates query offsets for repository operations

func ValidateReadAccess

func ValidateReadAccess(authResult *AuthenticationResult) error

ValidateReadAccess validates that the authenticated user can perform read operations

func ValidateReadScopes

func ValidateReadScopes(claims Claims) bool

ValidateReadScopes validates against common read scope combinations

func ValidateRedirectURIs

func ValidateRedirectURIs(uris string) error

ValidateRedirectURIs validates OAuth redirect URIs

func ValidateRedirectURL

func ValidateRedirectURL(redirectURL string, currentHost string) (string, error)

ValidateRedirectURL validates that a redirect URL is safe and allowed and returns the sanitized value.

func ValidateReportCategory

func ValidateReportCategory(category string) error

ValidateReportCategory validates report category

func ValidateReportComment

func ValidateReportComment(comment string) error

ValidateReportComment validates report comment

func ValidateReportParams

func ValidateReportParams(params map[string]interface{}) error

ValidateReportParams validates parameters for report creation

func ValidateReportStatusIDs

func ValidateReportStatusIDs(statusIDs interface{}) error

ValidateReportStatusIDs validates status IDs in reports

func ValidateRepositoryAccess

func ValidateRepositoryAccess(userID, resourceID string, operation string) error

ValidateRepositoryAccess validates access permissions for repository operations

func ValidateRepositoryCursor

func ValidateRepositoryCursor(cursor string) error

ValidateRepositoryCursor validates cursor parameters for pagination

func ValidateRepositoryRelationship

func ValidateRepositoryRelationship(fromEntity, toEntity string, relationType string) error

ValidateRepositoryRelationship validates relationships between entities

func ValidateRepositorySearchQuery

func ValidateRepositorySearchQuery(query string, minLength int) error

ValidateRepositorySearchQuery validates search queries for repository operations

func ValidateRequiredParam

func ValidateRequiredParam(paramName, value string) error

ValidateRequiredParam validates that a required parameter is not empty

func ValidateResourceAccess

func ValidateResourceAccess(_ context.Context, actorID, resourceID, resourceType string, requiredAccess AccessLevel) error

ValidateResourceAccess validates access to resources using existing auth patterns

func ValidateResponseData

func ValidateResponseData(data interface{}) interface{}

ValidateResponseData ensures response data is not nil and properly formatted

func ValidateScheduledTime

func ValidateScheduledTime(scheduledAt string) error

ValidateScheduledTime validates scheduled posting time

func ValidateSearchQuery

func ValidateSearchQuery(query string) error

ValidateSearchQuery validates search query parameters

func ValidateSliceLength

func ValidateSliceLength(fieldName string, slice interface{}, maxLength int) error

ValidateSliceLength validates slice length against bounds

func ValidateSliceNotEmpty

func ValidateSliceNotEmpty(fieldName string, slice interface{}) error

ValidateSliceNotEmpty validates that a slice is not empty

func ValidateSortParameters

func ValidateSortParameters(sortBy, sortOrder string, allowedFields []string) error

ValidateSortParameters validates sort field and order parameters

func ValidateSpoilerText

func ValidateSpoilerText(spoilerText string) error

ValidateSpoilerText validates content warning text

func ValidateStateTransition

func ValidateStateTransition(currentState, newState EntityState, entityType string) error

ValidateStateTransition validates state transitions

func ValidateStatusContent

func ValidateStatusContent(content string) error

ValidateStatusContent validates status content length and format

func ValidateStatusEntity

func ValidateStatusEntity(statusID, content string, visibility string) error

ValidateStatusEntity validates status entity data before repository operations

func ValidateStatusID

func ValidateStatusID(statusID string) error

ValidateStatusID validates a status ID format

func ValidateStatusParamID

func ValidateStatusParamID(statusID string) error

ValidateStatusParamID validates status ID from URL parameters

func ValidateStatusParams

func ValidateStatusParams(params map[string]interface{}) error

ValidateStatusParams validates parameters for status creation/update

func ValidateStatusState

func ValidateStatusState(status string) error

ValidateStatusState validates status states (pending, completed, failed, etc.)

func ValidateStringLength

func ValidateStringLength(field, value string, minLen, maxLen int) error

ValidateStringLength validates string length within bounds

func ValidateStruct

func ValidateStruct(data interface{}, rules ValidationRules) error

ValidateStruct performs basic struct validation using reflection

func ValidateTimestamp

func ValidateTimestamp(timestamp string, fieldName string) error

ValidateTimestamp validates timestamp formats used in repositories

func ValidateURL

func ValidateURL(url string, fieldName string) error

ValidateURL validates URL formats used in repositories

func ValidateUUID

func ValidateUUID(field, value string) error

ValidateUUID validates a UUID format

func ValidateUserEntity

func ValidateUserEntity(username, email string) error

ValidateUserEntity validates user entity data before repository operations

func ValidateUserRelationship

func ValidateUserRelationship(_ context.Context, actorID, targetID string, relationshipType string) error

ValidateUserRelationship validates relationships between users

func ValidateUsername

func ValidateUsername(username string) error

ValidateUsername validates a username according to platform rules

func ValidateUsernameParamID

func ValidateUsernameParamID(username string) error

ValidateUsernameParamID validates username from URL parameters

func ValidateVisibility

func ValidateVisibility(visibility string) error

ValidateVisibility validates status visibility values

func ValidateWebfingerResource

func ValidateWebfingerResource(resource string) error

ValidateWebfingerResource validates WebFinger resource identifiers

func ValidateWriteAccess

func ValidateWriteAccess(authResult *AuthenticationResult) error

ValidateWriteAccess validates that the authenticated user can perform write operations

func ValidateWriteScopes

func ValidateWriteScopes(claims Claims) bool

ValidateWriteScopes validates against common write scope combinations

func ValidationErrorMiddleware

func ValidationErrorMiddleware(serviceName string, logger *zap.Logger) apptheory.Middleware

ValidationErrorMiddleware creates middleware specifically for validation error handling

func VerifyOAuthClientSecret

func VerifyOAuthClientSecret(providedSecret, storedValue string) (bool, bool, error)

VerifyOAuthClientSecret verifies a provided secret against a stored value. It returns (valid, needsMigration, err). needsMigration is true when the stored value is a legacy plaintext secret and the verification succeeded.

func WithContext

func WithContext(ctx context.Context) *zap.Logger

WithContext returns a logger with Lambda context fields

func WithFields

func WithFields(fields ...zap.Field) *zap.Logger

WithFields returns a logger with additional fields

func WithSecurityContext

func WithSecurityContext(logger *zap.Logger, ctx SecurityContext) *zap.Logger

WithSecurityContext adds security context to logger

func WrapError

func WrapError(err error, context string) error

WrapError wraps an error with context while keeping it safe for users

func WrapObjectInActivity

func WrapObjectInActivity(activityType, actorID string, object interface{}, published time.Time) map[string]interface{}

WrapObjectInActivity wraps an object in an ActivityPub activity

func WrapWithLambdaResourceCheck

func WrapWithLambdaResourceCheck(operation string, fn func() error) error

WrapWithLambdaResourceCheck is a convenience function to wrap operations with the global monitor

Types

type AccessLevel

type AccessLevel string

AccessLevel represents access levels

const (
	AccessNone  AccessLevel = "none"  // AccessNone represents no access required
	AccessRead  AccessLevel = "read"  // AccessRead represents read access required
	AccessWrite AccessLevel = "write" // AccessWrite represents write access required
	AccessAdmin AccessLevel = "admin" // AccessAdmin represents admin access required
)

Resource access level constants

type AccountSuspendedError

type AccountSuspendedError struct {
	Username string
}

AccountSuspendedError indicates an account is suspended

func (AccountSuspendedError) Error

func (e AccountSuspendedError) Error() string

type ActivityNotFoundError

type ActivityNotFoundError struct {
	ID string
}

ActivityNotFoundError indicates an activity was not found

func (ActivityNotFoundError) Error

func (e ActivityNotFoundError) Error() string

type ActivityPubActivity

type ActivityPubActivity struct {
	Type   string
	Actor  string
	Object interface{}
	Target string
}

ActivityPubActivity represents an ActivityPub activity

func CreateFederationActivity

func CreateFederationActivity(actorID, activityType string, object interface{}) *ActivityPubActivity

CreateFederationActivity creates ActivityPub activities for federation

type ActivityPubActor

type ActivityPubActor interface {
	GetID() string
	GetType() string
	GetInbox() string
	GetOutbox() string
	GetFollowers() string
	GetFollowing() string
}

ActivityPubActor represents a generic ActivityPub actor interface

type ActivityPubAudience

type ActivityPubAudience struct {
	To  []string `json:"to,omitempty"`
	CC  []string `json:"cc,omitempty"`
	BTo []string `json:"bto,omitempty"`
	BCC []string `json:"bcc,omitempty"`
}

ActivityPubAudience represents the audience for an ActivityPub object

func CalculateActivityPubAudience

func CalculateActivityPubAudience(visibility VisibilityLevel, actorFollowers string, mentions []string) ActivityPubAudience

CalculateActivityPubAudience calculates the audience for an ActivityPub object

type ActivityPubBusinessLogic

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

ActivityPubBusinessLogic provides centralized ActivityPub business operations

func NewActivityPubBusinessLogic

func NewActivityPubBusinessLogic(config *FederationConfig, logger *zap.Logger) *ActivityPubBusinessLogic

NewActivityPubBusinessLogic creates a new ActivityPub business logic service

func (*ActivityPubBusinessLogic) ExecuteActivityPubOperation

func (ap *ActivityPubBusinessLogic) ExecuteActivityPubOperation(ctx context.Context, operation ActivityPubOperation) error

ExecuteActivityPubOperation executes a federation operation with standard error handling and retry logic

type ActivityPubCollection

type ActivityPubCollection struct {
	Context      interface{}   `json:"@context"`
	ID           string        `json:"id"`
	Type         string        `json:"type"`
	TotalItems   int           `json:"totalItems"`
	First        string        `json:"first,omitempty"`
	Last         string        `json:"last,omitempty"`
	Items        []interface{} `json:"items,omitempty"`
	OrderedItems []interface{} `json:"orderedItems,omitempty"`
}

ActivityPubCollection represents a paginated ActivityPub collection

func CreateActivityPubCollection

func CreateActivityPubCollection(id, collectionType string, totalItems int, firstPage string) ActivityPubCollection

CreateActivityPubCollection creates a standard ActivityPub collection

type ActivityPubCollectionPage

type ActivityPubCollectionPage struct {
	Context      interface{}   `json:"@context"`
	ID           string        `json:"id"`
	Type         string        `json:"type"`
	PartOf       string        `json:"partOf"`
	Next         string        `json:"next,omitempty"`
	Prev         string        `json:"prev,omitempty"`
	Items        []interface{} `json:"items,omitempty"`
	OrderedItems []interface{} `json:"orderedItems,omitempty"`
}

ActivityPubCollectionPage represents a page in an ActivityPub collection

func CreateActivityPubCollectionPage

func CreateActivityPubCollectionPage(id, pageType, partOf string, items []interface{}, nextPage, prevPage string) ActivityPubCollectionPage

CreateActivityPubCollectionPage creates a standard ActivityPub collection page

type ActivityPubError

type ActivityPubError struct {
	Type       string        `json:"type"`
	Message    string        `json:"message"`
	ActorID    string        `json:"actor,omitempty"`
	ObjectID   string        `json:"object,omitempty"`
	Temporary  bool          `json:"temporary"`
	RetryAfter time.Duration `json:"retry_after,omitempty"`
}

ActivityPubError represents an ActivityPub-specific error

func MapActivityPubError

func MapActivityPubError(err error, actorID, objectID string) ActivityPubError

MapActivityPubError maps common federation errors to ActivityPub error types

func NewActivityPubError

func NewActivityPubError(errorType, message string, temporary bool) ActivityPubError

NewActivityPubError creates a new ActivityPub error

func (ActivityPubError) Error

func (e ActivityPubError) Error() string

Error implements the error interface

func (ActivityPubError) IsTemporary

func (e ActivityPubError) IsTemporary() bool

IsTemporary returns whether the error is temporary and should be retried

type ActivityPubObject

type ActivityPubObject interface {
	GetID() string
	GetType() string
	GetActor() string
	GetObject() interface{}
	GetPublished() time.Time
}

ActivityPubObject represents a generic ActivityPub object interface

type ActivityPubOperation

type ActivityPubOperation interface {
	Validate(ctx context.Context) error
	Execute(ctx context.Context) error
	RecordMetrics(ctx context.Context, outcome string, attempts int) error
}

ActivityPubOperation defines the interface for ActivityPub operations

type ActivityPubSanitizer

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

ActivityPubSanitizer provides HTML sanitization for ActivityPub content

func NewActivityPubSanitizer

func NewActivityPubSanitizer() *ActivityPubSanitizer

NewActivityPubSanitizer creates a new sanitizer configured for ActivityPub content

func (*ActivityPubSanitizer) SanitizeActivityPubObject

func (s *ActivityPubSanitizer) SanitizeActivityPubObject(obj map[string]any)

SanitizeActivityPubObject sanitizes all string fields in an ActivityPub object

func (*ActivityPubSanitizer) SanitizeHTML

func (s *ActivityPubSanitizer) SanitizeHTML(content string) string

SanitizeHTML sanitizes HTML content for safe display

type ActivityPubValidationRules

type ActivityPubValidationRules struct {
	RequireHTTPS       bool
	AllowedDomains     []string
	BlockedDomains     []string
	MaxObjectSize      int64
	RequireSignature   bool
	ValidActivityTypes []string
}

ActivityPubValidationRules defines validation rules for ActivityPub objects

type ActorNotFoundError

type ActorNotFoundError struct {
	Username string
}

ActorNotFoundError indicates an actor was not found

func (ActorNotFoundError) Error

func (e ActorNotFoundError) Error() string

type AdminPaginationParams

type AdminPaginationParams struct {
	PaginationParams
	Origin       string `json:"origin"`        // local, remote
	Status       string `json:"status"`        // active, pending, disabled, etc.
	Permissions  string `json:"permissions"`   // Filter by permission level
	IP           string `json:"ip"`            // Filter by IP address
	Email        string `json:"email"`         // Filter by email pattern
	Username     string `json:"username"`      // Filter by username pattern
	ByDomain     string `json:"by_domain"`     // Filter by domain
	InviteFilter bool   `json:"invite_filter"` // Show only invited accounts
}

AdminPaginationParams extends PaginationParams for admin-specific needs

func GetAdminPaginationParams

func GetAdminPaginationParams(ctx *apptheory.Context) AdminPaginationParams

GetAdminPaginationParams extracts admin-specific pagination parameters.

type AlreadyFollowingError

type AlreadyFollowingError struct {
	Follower string
	Followee string
}

AlreadyFollowingError indicates already following the user

func (AlreadyFollowingError) Error

func (e AlreadyFollowingError) Error() string

type AppError

type AppError struct {
	Code          string // Internal error code for logging/monitoring
	UserMessage   string // Safe message for users
	InternalError error  // Detailed error for logging
	StatusCode    int    // HTTP status code
}

AppError represents a safe application error that separates internal details from user messages

func ErrBadRequest

func ErrBadRequest(userMessage string, internal error) AppError

ErrBadRequest creates a bad request error

func ErrForbidden

func ErrForbidden(internal error) AppError

ErrForbidden creates a forbidden error

func ErrInternal

func ErrInternal(internal error) AppError

ErrInternal creates an internal server error

func ErrNotFound

func ErrNotFound(resource string) AppError

ErrNotFound creates a not found error

func ErrUnauthorized

func ErrUnauthorized(internal error) AppError

ErrUnauthorized creates an unauthorized error

func ErrValidation

func ErrValidation(field string, message string) AppError

ErrValidation creates a validation error

func (AppError) Error

func (e AppError) Error() string

Error implements the error interface

type AuthContext

type AuthContext struct {
	Username string
	Claims   Claims
}

AuthContext holds authentication state

type AuthenticationError

type AuthenticationError struct {
	Message string
}

AuthenticationError indicates authentication failed

func (AuthenticationError) Error

func (e AuthenticationError) Error() string

type AuthenticationResult

type AuthenticationResult struct {
	Context   *AuthContext
	Error     error
	ErrorCode int
}

AuthenticationResult holds the result of authentication validation

func ExtractAndValidateAuth

func ExtractAndValidateAuth(ctx *apptheory.Context, requiredScope string, oauthService OAuthServiceInterface) *AuthenticationResult

ExtractAndValidateAuth performs the complete authentication flow This consolidates the most common pattern found across 80+ files:

  • Extract Authorization header (with fallback patterns)
  • Extract bearer token
  • Validate JWT token
  • Check required scopes

func ExtractAndValidateAuthWithMultipleScopes

func ExtractAndValidateAuthWithMultipleScopes(ctx *apptheory.Context, allowedScopes []string, oauthService OAuthServiceInterface) *AuthenticationResult

ExtractAndValidateAuthWithMultipleScopes validates authentication with multiple allowed scopes This handles the pattern where either of several scopes is acceptable

func ExtractOptionalAuth

func ExtractOptionalAuth(ctx *apptheory.Context, oauthService OAuthServiceInterface) *AuthenticationResult

ExtractOptionalAuth performs optional authentication (for public endpoints that benefit from auth) This consolidates the pattern where auth is optional but used if present

type AuthorizationError

type AuthorizationError struct {
	Action   string
	Resource string
}

AuthorizationError indicates authorization failed

func (AuthorizationError) Error

func (e AuthorizationError) Error() string

type BaseTransformer

type BaseTransformer[TSource, TTarget any] struct {
	// contains filtered or unexported fields
}

BaseTransformer provides a concrete implementation of the Transformer interface

func NewBaseTransformer

func NewBaseTransformer[TSource, TTarget any](
	name string,
	transformFn func(context.Context, TSource) (TTarget, error),
	logger *zap.Logger,
) *BaseTransformer[TSource, TTarget]

NewBaseTransformer creates a new BaseTransformer with the given function

func (*BaseTransformer[TSource, TTarget]) Transform

func (bt *BaseTransformer[TSource, TTarget]) Transform(ctx context.Context, source TSource) (TTarget, error)

Transform executes the transformation function

func (*BaseTransformer[TSource, TTarget]) WithCache

func (bt *BaseTransformer[TSource, TTarget]) WithCache(
	ttl time.Duration,
	maxSize int,
	keyFunc func(TSource) string,
) *BaseTransformer[TSource, TTarget]

WithCache enables caching for this transformer

type BatchTransformer

type BatchTransformer[TSource, TTarget any] interface {
	Transformer[TSource, TTarget]
	TransformBatch(ctx context.Context, sources []TSource) ([]TTarget, error)
}

BatchTransformer extends Transformer to handle batch operations efficiently

type BatchTransformerImpl

type BatchTransformerImpl[TSource, TTarget any] struct {
	*BaseTransformer[TSource, TTarget]
	// contains filtered or unexported fields
}

BatchTransformerImpl provides efficient batch processing capabilities

func NewBatchTransformer

func NewBatchTransformer[TSource, TTarget any](
	name string,
	transformFn func(context.Context, TSource) (TTarget, error),
	batchFn func(context.Context, []TSource) ([]TTarget, error),
	logger *zap.Logger,
) *BatchTransformerImpl[TSource, TTarget]

NewBatchTransformer creates a new batch transformer

func (*BatchTransformerImpl[TSource, TTarget]) TransformBatch

func (bt *BatchTransformerImpl[TSource, TTarget]) TransformBatch(
	ctx context.Context,
	sources []TSource,
) ([]TTarget, error)

TransformBatch processes multiple items efficiently

type BusinessLogicContext

type BusinessLogicContext struct {
	UserID       string
	Username     string
	DomainName   string
	Logger       *zap.Logger
	EventEmitter EventEmitter
}

BusinessLogicContext provides context for business operations

type BusinessLogicService

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

BusinessLogicService provides centralized business logic operations

func NewBusinessLogicService

func NewBusinessLogicService(logger *zap.Logger, eventEmitter EventEmitter, domainName string) *BusinessLogicService

NewBusinessLogicService creates a new business logic service

func (*BusinessLogicService) ExecuteBusinessOperation

func (s *BusinessLogicService) ExecuteBusinessOperation(ctx context.Context, operation BusinessOperation) error

ExecuteBusinessOperation executes a business operation with standard patterns

type BusinessOperation

type BusinessOperation interface {
	Validate(ctx context.Context) error
	Execute(ctx context.Context) error
	GetEvents(ctx context.Context) []*StreamingEvent
	RecordMetrics(ctx context.Context) error
}

BusinessOperation defines the interface for business operations

type BusinessRuleValidator

type BusinessRuleValidator interface {
	Validate(ctx context.Context, data interface{}) error
}

BusinessRuleValidator defines the interface for business rule validation

type CacheEntry

type CacheEntry[T any] struct {
	Value     T
	CreatedAt time.Time
}

CacheEntry represents a cached transformation result

type Claims

type Claims interface {
	HasScope(scope string) bool
	GetUsername() string
}

Claims represents JWT claims interface

type CommandValidationResult

type CommandValidationResult struct {
	IsValid  bool
	Errors   []string
	Warnings []string
}

CommandValidationResult represents the result of command validation

func ValidateCommand

func ValidateCommand(_ context.Context, cmd interface{}, rules ValidationRules) *CommandValidationResult

ValidateCommand performs standard validation on command structures

type ConditionalTransformer

type ConditionalTransformer[TSource, TTarget any] interface {
	Transformer[TSource, TTarget]
	CanTransform(ctx context.Context, source TSource) bool
}

ConditionalTransformer allows transformation based on runtime conditions

type ConditionalTransformerImpl

type ConditionalTransformerImpl[TSource, TTarget any] struct {
	*BaseTransformer[TSource, TTarget]
	// contains filtered or unexported fields
}

ConditionalTransformerImpl implements conditional transformation logic

func NewConditionalTransformer

func NewConditionalTransformer[TSource, TTarget any](
	name string,
	transformFn func(context.Context, TSource) (TTarget, error),
	conditionFn func(context.Context, TSource) bool,
	logger *zap.Logger,
) *ConditionalTransformerImpl[TSource, TTarget]

NewConditionalTransformer creates a transformer that only runs when condition is met

func (*ConditionalTransformerImpl[TSource, TTarget]) CanTransform

func (ct *ConditionalTransformerImpl[TSource, TTarget]) CanTransform(
	ctx context.Context,
	source TSource,
) bool

CanTransform checks if the transformation should be applied

func (*ConditionalTransformerImpl[TSource, TTarget]) Transform

func (ct *ConditionalTransformerImpl[TSource, TTarget]) Transform(
	ctx context.Context,
	source TSource,
) (TTarget, error)

Transform only executes if the condition is met

type ConflictError

type ConflictError struct {
	Resource string
	Message  string
}

ConflictError indicates a resource conflict

func (ConflictError) Error

func (e ConflictError) Error() string

type ContentValidationRules

type ContentValidationRules struct {
	MaxLength      int
	MinLength      int
	AllowedTypes   []string
	RequiredFields []string
	ForbiddenWords []string
}

ContentValidationRules defines rules for content validation

type ContextKey

type ContextKey string

ContextKey is the type for context keys

const (
	// ContextKeyClaims is the context key for JWT claims
	ContextKeyClaims ContextKey = "claims"
)

type CookieConfig

type CookieConfig struct {
	Domain   string // Leave empty to let browser handle
	Path     string
	Secure   bool // HTTPS only
	HTTPOnly bool // No JavaScript access
	SameSite http.SameSite
}

CookieConfig holds configuration for secure cookies

type DeliveryTarget

type DeliveryTarget struct {
	ActorID   string
	InboxURL  string
	SharedKey bool
}

DeliveryTarget represents a federation delivery target

func CalculateDeliveryTargets

func CalculateDeliveryTargets(_ context.Context, audience ActivityPubAudience, actorResolver func(string) (ActivityPubActor, error)) ([]DeliveryTarget, error)

CalculateDeliveryTargets calculates delivery targets for an ActivityPub activity

type EntityState

type EntityState string

EntityState represents entity states

const (
	StateDraft     EntityState = "draft"     // StateDraft represents entities in draft state
	StatePending   EntityState = "pending"   // StatePending represents entities awaiting approval
	StateActive    EntityState = "active"    // StateActive represents active entities
	StateInactive  EntityState = "inactive"  // StateInactive represents temporarily disabled entities
	StateSuspended EntityState = "suspended" // StateSuspended represents suspended entities
	StateDeleted   EntityState = "deleted"   // StateDeleted represents deleted entities
)

Entity state constants for state machine transitions

type ErrorMiddlewareConfig

type ErrorMiddlewareConfig struct {
	Logger              *zap.Logger
	ServiceName         string
	EnableStackTrace    bool
	EnablePanicRecovery bool
	EnableErrorMetrics  bool
	MaxErrorLogLength   int
}

ErrorMiddlewareConfig holds configuration for error handling middleware

func DefaultErrorConfig

func DefaultErrorConfig(serviceName string, logger *zap.Logger) ErrorMiddlewareConfig

DefaultErrorConfig returns a default error middleware configuration

type ErrorResponse

type ErrorResponse struct {
	Error   string `json:"error"`
	Message string `json:"message,omitempty"`
	Code    string `json:"code,omitempty"`
}

ErrorResponse represents a standard error response

type EventEmitter

type EventEmitter interface {
	EmitEvents(ctx context.Context, events []*StreamingEvent) error
}

EventEmitter defines the interface for event emission

type ExpiredTokenError

type ExpiredTokenError struct {
	Token string
}

ExpiredTokenError indicates a token has expired

func (ExpiredTokenError) Error

func (e ExpiredTokenError) Error() string

type FederationConfig

type FederationConfig struct {
	Domain         string
	PrivateKeyPath string
	PublicKeyPath  string
	UserAgent      string
	MaxRetries     int
	RetryDelay     time.Duration
	RequestTimeout time.Duration
}

FederationConfig configures federation behavior

type FederationDeliveryConfig

type FederationDeliveryConfig struct {
	MaxRetries     int
	RetryDelay     time.Duration
	RequestTimeout time.Duration
	MaxConcurrency int
	SignRequests   bool
}

FederationDeliveryConfig configures federation delivery behavior

type FederationError

type FederationError struct {
	Operation string
	Remote    string
	Err       error
}

FederationError indicates a federation operation failed

func (FederationError) Error

func (e FederationError) Error() string

func (FederationError) Unwrap

func (e FederationError) Unwrap() error

type FilterAction

type FilterAction string

FilterAction represents what action to take when filter matches

const (
	FilterActionWarn FilterAction = "warn"
	FilterActionHide FilterAction = "hide"
)

Actions that can be taken when a content filter matches

type FilterContext

type FilterContext string

FilterContext represents where a filter applies

const (
	FilterContextHome          FilterContext = "home"
	FilterContextNotifications FilterContext = "notifications"
	FilterContextPublic        FilterContext = "public"
	FilterContextThread        FilterContext = "thread"
	FilterContextAccount       FilterContext = "account"
)

Mastodon filter contexts define where content filters should be applied

type FilterParams

type FilterParams struct {
	Phrase       string   `json:"phrase"`
	Context      []string `json:"context"`
	ExpiresIn    int      `json:"expires_in"`
	Irreversible bool     `json:"irreversible"`
	WholeWord    bool     `json:"whole_word"`
}

FilterParams extracts filter-specific parameters

type HTTPSignatureInfo

type HTTPSignatureInfo struct {
	KeyID     string
	Algorithm string
	Headers   []string
	Signature string
}

HTTPSignatureInfo represents HTTP signature information

func ParseHTTPSignature

func ParseHTTPSignature(signatureHeader string) (*HTTPSignatureInfo, error)

ParseHTTPSignature parses an HTTP signature header

type HealthCheckResponse

type HealthCheckResponse struct {
	Status    string                 `json:"status"`
	Timestamp string                 `json:"timestamp"`
	Version   string                 `json:"version,omitempty"`
	Checks    map[string]interface{} `json:"checks,omitempty"`
}

HealthCheckResponse represents a health check response

type IDGenerator

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

IDGenerator provides production-ready ID generation with multiple formats

func NewIDGenerator

func NewIDGenerator(logger *zap.Logger) *IDGenerator

NewIDGenerator creates a new ID generator with cryptographically secure entropy

func (*IDGenerator) ExtractTimestamp

func (g *IDGenerator) ExtractTimestamp(id string) (time.Time, error)

ExtractTimestamp extracts the timestamp from a ULID

func (*IDGenerator) GenerateActivityID

func (g *IDGenerator) GenerateActivityID(domain string) string

GenerateActivityID generates an activity ID for ActivityPub activities

func (*IDGenerator) GenerateActivityPubID

func (g *IDGenerator) GenerateActivityPubID(domain, objectType string) string

GenerateActivityPubID generates an ActivityPub-compatible ID with domain context

func (*IDGenerator) GenerateActorID

func (g *IDGenerator) GenerateActorID(domain, username string) string

GenerateActorID generates an actor ID with proper ActivityPub format

func (*IDGenerator) GenerateAuditLogID

func (g *IDGenerator) GenerateAuditLogID() string

GenerateAuditLogID generates an audit log ID

func (*IDGenerator) GenerateCommunityNoteID

func (g *IDGenerator) GenerateCommunityNoteID() string

GenerateCommunityNoteID generates a community note ID

func (*IDGenerator) GenerateConversationID

func (g *IDGenerator) GenerateConversationID() string

GenerateConversationID generates a conversation ID

func (*IDGenerator) GenerateExportID

func (g *IDGenerator) GenerateExportID() string

GenerateExportID generates an export ID

func (*IDGenerator) GenerateImportID

func (g *IDGenerator) GenerateImportID() string

GenerateImportID generates an import ID

func (*IDGenerator) GenerateJobID

func (g *IDGenerator) GenerateJobID() string

GenerateJobID generates a job ID for background jobs

func (*IDGenerator) GenerateMediaID

func (g *IDGenerator) GenerateMediaID() string

GenerateMediaID generates a media ID with proper prefix

func (*IDGenerator) GenerateMessageID

func (g *IDGenerator) GenerateMessageID() string

GenerateMessageID generates a message ID

func (*IDGenerator) GenerateNoteID

func (g *IDGenerator) GenerateNoteID() string

GenerateNoteID generates a note ID with proper prefix

func (*IDGenerator) GenerateObjectID

func (g *IDGenerator) GenerateObjectID(domain string) string

GenerateObjectID generates an object ID for ActivityPub objects

func (*IDGenerator) GenerateOperationID

func (g *IDGenerator) GenerateOperationID() string

GenerateOperationID generates an operation ID for bulk operations

func (*IDGenerator) GenerateReportID

func (g *IDGenerator) GenerateReportID() string

GenerateReportID generates a report ID for moderation reports

func (*IDGenerator) GenerateRequestID

func (g *IDGenerator) GenerateRequestID() string

GenerateRequestID generates a request ID for tracing

func (*IDGenerator) GenerateSessionID

func (g *IDGenerator) GenerateSessionID() string

GenerateSessionID generates a session ID for user sessions

func (*IDGenerator) GenerateStatusID

func (g *IDGenerator) GenerateStatusID() string

GenerateStatusID generates a status ID with time-based prefix for better sorting

func (*IDGenerator) GenerateStreamingSessionID

func (g *IDGenerator) GenerateStreamingSessionID() string

GenerateStreamingSessionID generates a streaming session ID

func (*IDGenerator) GenerateULID

func (g *IDGenerator) GenerateULID() string

GenerateULID generates a ULID (Universally Unique Lexicographically Sortable Identifier) ULIDs are preferred for database performance as they are: - Lexicographically sortable - 128-bit compatible with UUID - More compact string representation - Better for database indexing performance

func (*IDGenerator) GenerateVouchID

func (g *IDGenerator) GenerateVouchID() string

GenerateVouchID generates a vouch ID for reputation system

func (*IDGenerator) IsOlderThan

func (g *IDGenerator) IsOlderThan(id string, duration time.Duration) bool

IsOlderThan checks if a ULID-based ID is older than the given duration

func (*IDGenerator) ShortID

func (g *IDGenerator) ShortID() string

ShortID generates a shorter ID for cases where full ULID is too long Uses base32 encoding of 8 bytes for readability while maintaining uniqueness

func (*IDGenerator) ValidateULID

func (g *IDGenerator) ValidateULID(id string) bool

ValidateULID validates if a string is a valid ULID

type InvalidPasswordError

type InvalidPasswordError struct{}

InvalidPasswordError indicates password validation failed

func (InvalidPasswordError) Error

func (e InvalidPasswordError) Error() string

type InvalidTokenError

type InvalidTokenError struct {
	Token string
}

InvalidTokenError indicates a token is invalid

func (InvalidTokenError) Error

func (e InvalidTokenError) Error() string

type LambdaConfig

type LambdaConfig struct {
	// Basic configuration
	ServiceName string
	LambdaType  LambdaType
	Version     string

	// Feature flags
	EnableMetrics      bool
	EnableTracing      bool
	EnableHealthCheck  bool
	EnableCostTracking bool

	// Timeout and retry settings
	RequestTimeout   time.Duration
	RetryMaxAttempts int

	// Custom AWS service requirements (overrides defaults)
	CustomServiceConfig *awsInit.ServiceConfig
}

LambdaConfig defines Lambda initialization configuration

type LambdaContext

type LambdaContext struct {
	// Configuration
	Config    *config.Config
	Logger    *zap.Logger
	StartTime time.Time

	// AWS Services
	AWSServices *awsInit.AWSServices

	// Storage (interfaces to avoid import cycles)
	DynamoDB interface{} // *tabletheory.Client
	Repos    interface{} // core.RepositoryStorage

	// Observability (interfaces to avoid import cycles)
	EMFMetrics        interface{} // *observability.EMFMetrics
	HealthChecker     interface{} // *observability.HealthChecker
	TracingManager    interface{} // *observability.TracingManager
	MetricsCollector  interface{} // *observability.MetricsCollector
	LatencyAggregator interface{} // *observability.LatencyAggregator
	LatencyAlerter    interface{} // *observability.LatencyAlerter
	AlertManager      interface{} // *monitoring.AlertManager

	// Service specific
	ServiceName string
	LambdaType  LambdaType

	// Service utilities (interfaces to avoid import cycles)
	AuthService      interface{} // *auth.AuthService
	AuthMiddleware   interface{} // *auth.Middleware
	StreamQueue      interface{} // *streaming.StreamQueue
	SignatureService interface{} // *federation.SignatureService
	DeliveryService  interface{} // *federation.DeliveryService
	CostCalculator   interface{} // *federation.CostCalculator
	RateLimiter      interface{} // *auth.RateLimiter
}

LambdaContext contains initialized Lambda dependencies

func InitializeLambda

func InitializeLambda(lambdaConfig LambdaConfig) (*LambdaContext, error)

InitializeLambda initializes a Lambda function with standard dependencies

func MustInitializeLambda

func MustInitializeLambda(lambdaConfig LambdaConfig) *LambdaContext

MustInitializeLambda is like InitializeLambda but panics on error

func (*LambdaContext) CreateLambdaHandler

func (lambdaCtx *LambdaContext) CreateLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)

CreateLambdaHandler creates a Lambda handler wrapper with basic logging

func (*LambdaContext) CreateStandardizedLambdaHandler

func (lambdaCtx *LambdaContext) CreateStandardizedLambdaHandler(handler func(ctx context.Context, event interface{}) (interface{}, error)) func(ctx context.Context, event interface{}) (interface{}, error)

CreateStandardizedLambdaHandler creates a Lambda handler with standardized observability and error handling

func (*LambdaContext) FlushObservability

func (lambdaCtx *LambdaContext) FlushObservability()

FlushObservability flushes all observability data before Lambda termination

func (*LambdaContext) FlushObservabilityServices

func (lambdaCtx *LambdaContext) FlushObservabilityServices()

FlushObservabilityServices flushes all observability data before Lambda termination

func (*LambdaContext) InitializeObservabilityServices

func (lambdaCtx *LambdaContext) InitializeObservabilityServices(options LambdaInitOptions) error

InitializeObservabilityServices initializes observability services based on options

func (*LambdaContext) InitializeServiceSpecificDependencies

func (lambdaCtx *LambdaContext) InitializeServiceSpecificDependencies(options LambdaInitOptions) error

InitializeServiceSpecificDependencies initializes service-specific dependencies

func (*LambdaContext) InitializeStorageServices

func (lambdaCtx *LambdaContext) InitializeStorageServices(options LambdaInitOptions) error

InitializeStorageServices initializes DynamORM and repository storage

func (*LambdaContext) InitializeWithDefaults

func (lambdaCtx *LambdaContext) InitializeWithDefaults() error

InitializeWithDefaults initializes Lambda with default options for the Lambda type

func (*LambdaContext) InitializeWithOptions

func (lambdaCtx *LambdaContext) InitializeWithOptions(options LambdaInitOptions) error

InitializeWithOptions initializes Lambda with custom options

type LambdaInitOptions

type LambdaInitOptions struct {
	// Storage options
	InitializeStorage      bool
	InitializeRepositories bool
	TableName              string

	// Observability options
	InitializeEMFMetrics       bool
	InitializeHealthChecker    bool
	InitializeTracingManager   bool
	InitializeMetricsCollector bool
	InitializeLatencyTracking  bool
	InitializeAlerting         bool

	// Service-specific options
	InitializeAuthService        bool
	InitializeFederationServices bool
	InitializeStreamingServices  bool

	// Performance options
	OptimizeForColdStart bool
	EnableServiceCaching bool
}

LambdaInitOptions provides additional initialization options

func DefaultLambdaInitOptions

func DefaultLambdaInitOptions(lambdaType LambdaType) LambdaInitOptions

DefaultLambdaInitOptions returns sensible defaults for different Lambda types

type LambdaResourceMonitor

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

LambdaResourceMonitor tracks resource usage in Lambda environment

func GetLambdaMonitor

func GetLambdaMonitor() *LambdaResourceMonitor

GetLambdaMonitor returns the global Lambda resource monitor

func NewLambdaResourceMonitor

func NewLambdaResourceMonitor() *LambdaResourceMonitor

NewLambdaResourceMonitor creates a monitor based on Lambda limits

func (*LambdaResourceMonitor) CheckResources

func (m *LambdaResourceMonitor) CheckResources(operation string) error

CheckResources verifies we're within Lambda limits

func (*LambdaResourceMonitor) GetCheckpoints

func (m *LambdaResourceMonitor) GetCheckpoints() []ResourceCheckpoint

GetCheckpoints returns all recorded checkpoints

func (*LambdaResourceMonitor) GetElapsedTime

func (m *LambdaResourceMonitor) GetElapsedTime() time.Duration

GetElapsedTime returns time elapsed since monitor creation

func (*LambdaResourceMonitor) GetMemoryUsageMB

func (m *LambdaResourceMonitor) GetMemoryUsageMB() uint64

GetMemoryUsageMB returns current memory usage in MB

func (*LambdaResourceMonitor) GetResourceUtilization

func (m *LambdaResourceMonitor) GetResourceUtilization() (memoryPercent float64, timePercent float64)

GetResourceUtilization returns current resource utilization as percentages

func (*LambdaResourceMonitor) WrapWithResourceCheck

func (m *LambdaResourceMonitor) WrapWithResourceCheck(operation string, fn func() error) error

WrapWithResourceCheck wraps an operation with resource monitoring

type LambdaRuntimeInfo

type LambdaRuntimeInfo struct{}

LambdaRuntimeInfo provides access to AWS Lambda runtime environment variables

func NewLambdaRuntime

func NewLambdaRuntime() *LambdaRuntimeInfo

NewLambdaRuntime creates a new LambdaRuntimeInfo instance

func (*LambdaRuntimeInfo) GetFunctionName

func (l *LambdaRuntimeInfo) GetFunctionName() string

GetFunctionName returns the AWS Lambda function name from AWS_LAMBDA_FUNCTION_NAME

func (*LambdaRuntimeInfo) GetFunctionVersion

func (l *LambdaRuntimeInfo) GetFunctionVersion() string

GetFunctionVersion returns the AWS Lambda function version from AWS_LAMBDA_FUNCTION_VERSION

func (*LambdaRuntimeInfo) GetInitializationType

func (l *LambdaRuntimeInfo) GetInitializationType() string

GetInitializationType returns the AWS Lambda initialization type from AWS_LAMBDA_INITIALIZATION_TYPE

func (*LambdaRuntimeInfo) GetLogGroupName

func (l *LambdaRuntimeInfo) GetLogGroupName() string

GetLogGroupName returns the AWS Lambda log group name from AWS_LAMBDA_LOG_GROUP_NAME

func (*LambdaRuntimeInfo) GetLogStreamName

func (l *LambdaRuntimeInfo) GetLogStreamName() string

GetLogStreamName returns the AWS Lambda log stream name from AWS_LAMBDA_LOG_STREAM_NAME

func (*LambdaRuntimeInfo) GetMemorySize

func (l *LambdaRuntimeInfo) GetMemorySize() string

GetMemorySize returns the AWS Lambda function memory size from AWS_LAMBDA_FUNCTION_MEMORY_SIZE

func (*LambdaRuntimeInfo) GetMemorySizeInt

func (l *LambdaRuntimeInfo) GetMemorySizeInt() (int, error)

GetMemorySizeInt returns the AWS Lambda function memory size as an integer

func (*LambdaRuntimeInfo) GetXRayTraceID

func (l *LambdaRuntimeInfo) GetXRayTraceID() string

GetXRayTraceID returns the X-Ray trace ID from _X_AMZN_TRACE_ID

func (*LambdaRuntimeInfo) IsColdStart

func (l *LambdaRuntimeInfo) IsColdStart() bool

IsColdStart returns true if this is a cold start (initialization type is on-demand)

func (*LambdaRuntimeInfo) IsRunningInLambda

func (l *LambdaRuntimeInfo) IsRunningInLambda() bool

IsRunningInLambda returns true if running in AWS Lambda environment

func (*LambdaRuntimeInfo) IsXRayEnabled

func (l *LambdaRuntimeInfo) IsXRayEnabled() bool

IsXRayEnabled returns true if X-Ray tracing is enabled

type LambdaType

type LambdaType string

LambdaType defines the type of Lambda function for initialization

const (
	// LambdaTypeAPI represents the API Lambda function type
	LambdaTypeAPI LambdaType = "api"
	// LambdaTypeProcessor represents the processor Lambda function type
	LambdaTypeProcessor LambdaType = "processor"
	// LambdaTypeMedia represents the media Lambda function type
	LambdaTypeMedia LambdaType = "media"
	// LambdaTypeFederation represents the federation Lambda function type
	LambdaTypeFederation LambdaType = "federation"
	// LambdaTypeAI represents the AI Lambda function type
	LambdaTypeAI LambdaType = "ai"
	// LambdaTypeBasic represents the basic Lambda function type
	LambdaTypeBasic LambdaType = "basic"
)

type ListNotFoundError

type ListNotFoundError struct {
	ID string
}

ListNotFoundError indicates a list was not found

func (ListNotFoundError) Error

func (e ListNotFoundError) Error() string

type MastodonAPIConfig

type MastodonAPIConfig struct {
	InstanceName      string
	Domain            string
	MaxStatusLength   int
	MaxBioLength      int
	MaxDisplayName    int
	MaxPollOptions    int
	MaxPollExpiry     time.Duration
	MediaUploadLimit  int64
	VideoUploadLimit  int64
	DefaultPagination int
	MaxPagination     int
}

MastodonAPIConfig configures Mastodon API behavior

func DefaultMastodonConfig

func DefaultMastodonConfig() *MastodonAPIConfig

DefaultMastodonConfig returns sensible defaults for Mastodon API

type MastodonAPIError

type MastodonAPIError struct {
	Type        string `json:"error"`
	Description string `json:"error_description,omitempty"`
	StatusCode  int    `json:"-"`
}

MastodonAPIError represents a Mastodon API-specific error

func NewMastodonAPIError

func NewMastodonAPIError(errorType, description string, statusCode int) MastodonAPIError

NewMastodonAPIError creates a new Mastodon API error

func (MastodonAPIError) Error

func (e MastodonAPIError) Error() string

Error implements the error interface

type MastodonAccount

type MastodonAccount struct {
	ID             string `json:"id"`
	Username       string `json:"username"`
	Acct           string `json:"acct"`
	DisplayName    string `json:"display_name"`
	Note           string `json:"note"`
	URL            string `json:"url"`
	Avatar         string `json:"avatar"`
	Header         string `json:"header"`
	Locked         bool   `json:"locked"`
	CreatedAt      string `json:"created_at"`
	FollowersCount int    `json:"followers_count"`
	FollowingCount int    `json:"following_count"`
	StatusesCount  int    `json:"statuses_count"`
	Bot            bool   `json:"bot"`
	Discoverable   bool   `json:"discoverable"`
}

MastodonAccount represents a basic Mastodon account structure for responses

type MastodonBusinessLogic

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

MastodonBusinessLogic provides centralized Mastodon API business operations

func NewMastodonBusinessLogic

func NewMastodonBusinessLogic(config *MastodonAPIConfig, logger *zap.Logger) *MastodonBusinessLogic

NewMastodonBusinessLogic creates a new Mastodon business logic service

func (*MastodonBusinessLogic) ExecuteMastodonAPIOperation

func (m *MastodonBusinessLogic) ExecuteMastodonAPIOperation(ctx context.Context, operation MastodonOperation) (interface{}, error)

ExecuteMastodonAPIOperation executes a Mastodon API operation with standard validation and error handling

func (*MastodonBusinessLogic) ValidateBio

func (m *MastodonBusinessLogic) ValidateBio(bio string) error

ValidateBio validates account bio/note

func (*MastodonBusinessLogic) ValidateDisplayName

func (m *MastodonBusinessLogic) ValidateDisplayName(displayName string) error

ValidateDisplayName validates account display name

func (*MastodonBusinessLogic) ValidateMastodonPaginationParams

func (m *MastodonBusinessLogic) ValidateMastodonPaginationParams(params MastodonPaginationParams) MastodonPaginationParams

ValidateMastodonPaginationParams validates Mastodon pagination parameters

func (*MastodonBusinessLogic) ValidateMediaUpload

func (m *MastodonBusinessLogic) ValidateMediaUpload(data []byte, mimeType string, mediaType MediaType) error

ValidateMediaUpload validates media upload according to Mastodon limits

func (*MastodonBusinessLogic) ValidatePollOptions

func (m *MastodonBusinessLogic) ValidatePollOptions(options []PollOption, expiresIn int) error

ValidatePollOptions validates poll creation

func (*MastodonBusinessLogic) ValidateRateLimit

func (m *MastodonBusinessLogic) ValidateRateLimit(_ context.Context, _, _ string, _ RateLimitConfig) error

ValidateRateLimit checks if an action is within rate limits

func (*MastodonBusinessLogic) ValidateStatusContent

func (m *MastodonBusinessLogic) ValidateStatusContent(content string, mediaCount int, pollOptions int) error

ValidateStatusContent validates status content according to Mastodon rules

type MastodonOperation

type MastodonOperation interface {
	Validate(ctx context.Context) error
	Execute(ctx context.Context) error
	GetResponse(ctx context.Context) interface{}
	RecordMetrics(ctx context.Context) error
}

MastodonOperation defines the interface for Mastodon API operations

type MastodonPaginationParams

type MastodonPaginationParams struct {
	Limit   int    `json:"limit,omitempty"`
	MaxID   string `json:"max_id,omitempty"`
	MinID   string `json:"min_id,omitempty"`
	SinceID string `json:"since_id,omitempty"`
	Cursor  string `json:"cursor,omitempty"` // For some endpoints
}

MastodonPaginationParams represents standard Mastodon API pagination

type MastodonStatus

type MastodonStatus struct {
	ID                 string          `json:"id"`
	CreatedAt          string          `json:"created_at"`
	InReplyToID        *string         `json:"in_reply_to_id"`
	InReplyToAccountID *string         `json:"in_reply_to_account_id"`
	Sensitive          bool            `json:"sensitive"`
	SpoilerText        string          `json:"spoiler_text"`
	Visibility         string          `json:"visibility"`
	Language           *string         `json:"language"`
	URI                string          `json:"uri"`
	URL                *string         `json:"url"`
	RepliesCount       int             `json:"replies_count"`
	ReblogsCount       int             `json:"reblogs_count"`
	FavouritesCount    int             `json:"favourites_count"`
	Content            string          `json:"content"`
	Reblog             *MastodonStatus `json:"reblog"`
	Account            MastodonAccount `json:"account"`
	Reblogged          bool            `json:"reblogged"`
	Favourited         bool            `json:"favourited"`
	Bookmarked         bool            `json:"bookmarked"`
	Pinned             bool            `json:"pinned"`
}

MastodonStatus represents a basic Mastodon status structure for responses

type MediaType

type MediaType string

MediaType represents different media types supported by Mastodon MediaType represents the type of media attachment in Mastodon These values correspond to the standard Mastodon media attachment types used for categorizing uploaded media files

const (
	MediaTypeImage MediaType = "image"
	MediaTypeVideo MediaType = "video"
	MediaTypeAudio MediaType = "audio"
	MediaTypeGIF   MediaType = "gifv"
)

Media attachment types supported by Mastodon

type NotificationType

type NotificationType string

NotificationType represents different Mastodon notification types

const (
	NotificationMention       NotificationType = "mention"
	NotificationStatus        NotificationType = "status"
	NotificationReblog        NotificationType = "reblog"
	NotificationFollow        NotificationType = "follow"
	NotificationFollowRequest NotificationType = "follow_request"
	NotificationFavourite     NotificationType = "favourite"
	NotificationPoll          NotificationType = "poll"
	NotificationUpdate        NotificationType = "update"
	NotificationAdminSignUp   NotificationType = "admin.sign_up"
	NotificationAdminReport   NotificationType = "admin.report"
)

Mastodon notification types as defined in the Mastodon API specification

type OAuthServiceInterface

type OAuthServiceInterface interface {
	ValidateAccessToken(token string) (Claims, error)
}

OAuthServiceInterface defines the interface for OAuth validation This avoids import cycles while providing the needed validation functionality

type PaginatedResponse

type PaginatedResponse struct {
	Data       interface{} `json:"data"`
	Pagination *Pagination `json:"pagination,omitempty"`
}

PaginatedResponse wraps data with pagination metadata

type Pagination

type Pagination struct {
	Limit      int    `json:"limit"`
	Offset     int    `json:"offset"`
	Page       int    `json:"page,omitempty"`
	TotalCount int    `json:"total_count,omitempty"`
	HasNext    bool   `json:"has_next"`
	HasPrev    bool   `json:"has_prev"`
	NextCursor string `json:"next_cursor,omitempty"`
	PrevCursor string `json:"prev_cursor,omitempty"`
}

Pagination contains pagination metadata

type PaginationLinks struct {
	Next string `json:"next,omitempty"`
	Prev string `json:"prev,omitempty"`
}

PaginationLinks holds Link header data for Mastodon API compatibility

type PaginationParams

type PaginationParams struct {
	Limit   int    `json:"limit"`
	Offset  int    `json:"offset"`
	Page    int    `json:"page"`
	MaxID   string `json:"max_id"`
	MinID   string `json:"min_id"`
	SinceID string `json:"since_id"`
	Cursor  string `json:"cursor"`
}

PaginationParams represents standardized pagination parameters used across the application

func GetPaginationParams

func GetPaginationParams(ctx *apptheory.Context) PaginationParams

GetPaginationParams extracts and validates pagination parameters from an AppTheory context.

func GetPaginationParamsFromRequest

func GetPaginationParamsFromRequest(queryParams map[string][]string) PaginationParams

GetPaginationParamsFromRequest extracts pagination from standard HTTP request This provides compatibility with non-Lift request handling

type PaginationResult

type PaginationResult struct {
	Items      interface{} `json:"items"`
	TotalCount int         `json:"total_count,omitempty"`
	HasNext    bool        `json:"has_next,omitempty"`
	HasPrev    bool        `json:"has_prev,omitempty"`
	NextCursor string      `json:"next_cursor,omitempty"`
	PrevCursor string      `json:"prev_cursor,omitempty"`
}

PaginationResult holds pagination response data

type PollOption

type PollOption struct {
	Title string `json:"title"`
	Count int    `json:"votes_count,omitempty"`
}

PollOption represents a poll option

type QuotaValidator

type QuotaValidator struct {
	MaxActionsPerHour int
	MaxActionsPerDay  int
}

QuotaValidator validates operations against quotas

func (*QuotaValidator) ValidateQuota

func (q *QuotaValidator) ValidateQuota(_ context.Context, actorID, actionType string) error

ValidateQuota checks if action is within quota limits

type RateLimitConfig

type RateLimitConfig struct {
	PostsPerHour    int
	FollowsPerHour  int
	ReportsPerHour  int
	UploadsPerHour  int
	SearchesPerHour int
}

RateLimitConfig configures rate limiting for different endpoints

func DefaultRateLimits

func DefaultRateLimits() RateLimitConfig

DefaultRateLimits returns Mastodon-compatible rate limits

type RequestPaginationParams

type RequestPaginationParams struct {
	Limit   int    `json:"limit"`
	Offset  int    `json:"offset"`
	MaxID   string `json:"max_id"`
	MinID   string `json:"min_id"`
	SinceID string `json:"since_id"`
}

RequestPaginationParams extracts common pagination parameters (different from pagination.go version)

type ResourceCheckpoint

type ResourceCheckpoint struct {
	Timestamp   time.Time
	MemoryUsed  uint64
	Goroutines  int
	Description string
}

ResourceCheckpoint represents a point-in-time snapshot of resource usage

type SafeJSONDecoder

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

SafeJSONDecoder wraps json.Decoder with safety limits

func NewSafeJSONDecoder

func NewSafeJSONDecoder(r io.Reader) *SafeJSONDecoder

NewSafeJSONDecoder creates a decoder with safety limits

func (*SafeJSONDecoder) Decode

func (d *SafeJSONDecoder) Decode(v any) error

Decode safely decodes JSON with depth and size limits

type SearchPaginationParams

type SearchPaginationParams struct {
	PaginationParams
	Type              string `json:"type"`               // account, hashtag, status
	Resolve           bool   `json:"resolve"`            // Resolve remote resources
	Following         bool   `json:"following"`          // Only search followed accounts
	AccountID         string `json:"account_id"`         // Limit search to specific account
	MaxResults        int    `json:"max_results"`        // Override limit for search APIs
	ExcludeUnreviewed bool   `json:"exclude_unreviewed"` // Exclude unreviewed content
}

SearchPaginationParams extends PaginationParams for search-specific needs

func GetSearchPaginationParams

func GetSearchPaginationParams(ctx *apptheory.Context) SearchPaginationParams

GetSearchPaginationParams extracts search-specific pagination parameters.

type SecurityContext

type SecurityContext struct {
	UserID    string
	SessionID string
	IP        string
	UserAgent string
	RequestID string
}

SecurityContext provides context for security logging

type SessionNotFoundError

type SessionNotFoundError struct {
	SessionID string
}

SessionNotFoundError indicates a session was not found

func (SessionNotFoundError) Error

func (e SessionNotFoundError) Error() string

type Snowflake

type Snowflake struct {
	ID        uint64
	Timestamp time.Time
}

Snowflake represents a Twitter-like snowflake ID

type StandardErrorResponse

type StandardErrorResponse struct {
	Error       string `json:"error"`
	Description string `json:"error_description,omitempty"`
	Code        string `json:"error_code,omitempty"`
}

StandardErrorResponse represents a standardized API error response

type StatusValidationRules

type StatusValidationRules struct {
	MaxLength      int
	AllowMarkdown  bool
	AllowHTML      bool
	RequireContent bool
	MaxMediaItems  int
	MaxPollOptions int
}

StatusValidationRules defines validation rules for status content

type StreamingEvent

type StreamingEvent struct {
	Type      string
	Object    string
	ObjectID  string
	ActorID   string
	Timestamp time.Time
	Metadata  map[string]interface{}
}

StreamingEvent represents a streaming event without import dependencies

func EmitBusinessEvent

func EmitBusinessEvent(_ context.Context, eventType, objectType, objectID, actorID string, metadata map[string]interface{}) *StreamingEvent

EmitBusinessEvent creates standardized business events

func EmitEntityCreatedEvents

func EmitEntityCreatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}) []*StreamingEvent

EmitEntityCreatedEvents creates standard creation events

func EmitEntityDeletedEvents

func EmitEntityDeletedEvents(ctx context.Context, entityType, entityID, actorID string) []*StreamingEvent

EmitEntityDeletedEvents creates standard deletion events

func EmitEntityUpdatedEvents

func EmitEntityUpdatedEvents(ctx context.Context, entityType, entityID, actorID string, entity interface{}, changes map[string]interface{}) []*StreamingEvent

EmitEntityUpdatedEvents creates standard update events

type StreamingMessage

type StreamingMessage struct {
	Event string      `json:"event"`
	Data  interface{} `json:"data"`
}

StreamingMessage represents a Server-Sent Events message

type TimelinePaginationParams

type TimelinePaginationParams struct {
	PaginationParams
	Local          bool `json:"local"`
	OnlyMedia      bool `json:"only_media"`
	RemoteOnly     bool `json:"remote_only"`
	IncludeReplies bool `json:"include_replies"`
}

TimelinePaginationParams extends PaginationParams for timeline-specific needs

func GetTimelinePaginationParams

func GetTimelinePaginationParams(ctx *apptheory.Context) TimelinePaginationParams

GetTimelinePaginationParams extracts timeline-specific pagination parameters.

type TimelineParams

type TimelineParams struct {
	RequestPaginationParams
	Local     bool `json:"local"`
	OnlyMedia bool `json:"only_media"`
}

TimelineParams extracts timeline-specific parameters

type TransformationCache

type TransformationCache[TSource, TTarget any] struct {
	// contains filtered or unexported fields
}

TransformationCache provides caching for expensive transformations

func NewTransformationCache

func NewTransformationCache[TSource, TTarget any](
	ttl time.Duration,
	maxSize int,
	keyFunc func(TSource) string,
	logger *zap.Logger,
) *TransformationCache[TSource, TTarget]

NewTransformationCache creates a new cache for transformations

func (*TransformationCache[TSource, TTarget]) Clear

func (tc *TransformationCache[TSource, TTarget]) Clear()

Clear removes all cached entries

func (*TransformationCache[TSource, TTarget]) Get

func (tc *TransformationCache[TSource, TTarget]) Get(source TSource) (TTarget, bool)

Get retrieves a cached transformation result

func (*TransformationCache[TSource, TTarget]) Set

func (tc *TransformationCache[TSource, TTarget]) Set(source TSource, target TTarget)

Set stores a transformation result in the cache

func (*TransformationCache[TSource, TTarget]) Stats

func (tc *TransformationCache[TSource, TTarget]) Stats() (hits, misses int64, hitRate float64)

Stats returns cache performance statistics

type TransformationContext

type TransformationContext struct {
	UserID       string
	RequestID    string
	Metadata     map[string]interface{}
	StartTime    time.Time
	Transformers map[string]interface{}
}

TransformationContext carries metadata through transformation pipelines

func NewTransformationContext

func NewTransformationContext(userID, requestID string) *TransformationContext

NewTransformationContext creates a new transformation context

func (*TransformationContext) Duration

func (tc *TransformationContext) Duration() time.Duration

Duration returns the elapsed time since context creation

func (*TransformationContext) GetMetadata

func (tc *TransformationContext) GetMetadata(key string) (interface{}, bool)

GetMetadata retrieves metadata from the transformation context

func (*TransformationContext) WithMetadata

func (tc *TransformationContext) WithMetadata(key string, value interface{}) *TransformationContext

WithMetadata adds metadata to the transformation context

type TransformationError

type TransformationError struct {
	Step       string
	SourceType string
	TargetType string
	Cause      error
}

TransformationError provides detailed error information for failed transformations

func (TransformationError) Error

func (e TransformationError) Error() string

func (TransformationError) Unwrap

func (e TransformationError) Unwrap() error

type TransformationMetrics

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

TransformationMetrics tracks performance and success rates

func NewTransformationMetrics

func NewTransformationMetrics() *TransformationMetrics

NewTransformationMetrics creates a new metrics tracker

func (*TransformationMetrics) GetStats

func (tm *TransformationMetrics) GetStats() (count, errors int64, avgDuration time.Duration, errorRate float64)

GetStats returns current transformation statistics

func (*TransformationMetrics) RecordTransformation

func (tm *TransformationMetrics) RecordTransformation(duration time.Duration, success bool)

RecordTransformation updates transformation metrics

func (*TransformationMetrics) Reset

func (tm *TransformationMetrics) Reset()

Reset clears all metrics

type TransformationPipeline

type TransformationPipeline[TSource, TTarget any] struct {
	// contains filtered or unexported fields
}

TransformationPipeline provides a framework for chaining transformations

type TransformationRegistry

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

TransformationRegistry manages named transformers for dynamic lookup

func NewTransformationRegistry

func NewTransformationRegistry(logger *zap.Logger) *TransformationRegistry

NewTransformationRegistry creates a new registry for managing transformers

func (*TransformationRegistry) Get

func (tr *TransformationRegistry) Get(name string) (interface{}, bool)

Get retrieves a transformer from the registry

func (*TransformationRegistry) List

func (tr *TransformationRegistry) List() []string

List returns all registered transformer names

func (*TransformationRegistry) Register

func (tr *TransformationRegistry) Register(name string, transformer interface{}) error

Register adds a transformer to the registry

func (*TransformationRegistry) Unregister

func (tr *TransformationRegistry) Unregister(name string) bool

Unregister removes a transformer from the registry

type TransformationStep

type TransformationStep[T any] struct {
	Name        string
	Transformer Transformer[T, T]
	Required    bool // If true, failure stops the pipeline
}

TransformationStep represents a single step in a transformation pipeline

type Transformer

type Transformer[TSource, TTarget any] interface {
	Transform(ctx context.Context, source TSource) (TTarget, error)
}

Transformer defines the core interface for data transformations This interface provides type-safe transformations with error handling

func MemoizedTransformer

func MemoizedTransformer[TSource, TTarget any](
	transformer Transformer[TSource, TTarget],
	keyFunc func(TSource) string,
	ttl time.Duration,
) Transformer[TSource, TTarget]

MemoizedTransformer provides memoization for expensive transformations

func ValidatingTransformer

func ValidatingTransformer[TSource, TTarget any](
	transformer Transformer[TSource, TTarget],
	validator func(TSource) error,
) Transformer[TSource, TTarget]

ValidatingTransformer wraps a transformer with input validation

type UsedTokenError

type UsedTokenError struct {
	Token string
}

UsedTokenError indicates a token has already been used

func (UsedTokenError) Error

func (e UsedTokenError) Error() string

type UserNotFoundError

type UserNotFoundError struct {
	Username string
}

UserNotFoundError indicates a user was not found

func (UserNotFoundError) Error

func (e UserNotFoundError) Error() string

type ValidationError

type ValidationError struct {
	Field   string
	Message string
}

ValidationError indicates input validation failed

func (ValidationError) Error

func (e ValidationError) Error() string

type ValidationRules

type ValidationRules struct {
	Required []string
	MaxLen   map[string]int
	MinLen   map[string]int
	Pattern  map[string]string
}

ValidationRules defines basic validation rules

type VisibilityLevel

type VisibilityLevel string

VisibilityLevel represents different visibility levels

const (
	VisibilityPublic   VisibilityLevel = "public"   // VisibilityPublic makes content visible to everyone
	VisibilityUnlisted VisibilityLevel = "unlisted" // VisibilityUnlisted makes content visible but not in public timelines
	VisibilityPrivate  VisibilityLevel = "private"  // VisibilityPrivate makes content visible only to followers
	VisibilityDirect   VisibilityLevel = "direct"   // VisibilityDirect makes content visible only to mentioned users
)

Visibility levels for content

type WebSocketMessage

type WebSocketMessage struct {
	Type    string      `json:"type"`
	Stream  []string    `json:"stream,omitempty"`
	Event   string      `json:"event,omitempty"`
	Payload interface{} `json:"payload,omitempty"`
}

WebSocketMessage represents a WebSocket message

func CreateWebSocketMessage

func CreateWebSocketMessage(msgType string, stream []string, event string, payload interface{}) WebSocketMessage

CreateWebSocketMessage creates a properly formatted WebSocket message

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL