This document provides an exhaustive overview of all Convex functions and files remaining in the codebase after the migration of heavy image/video generation compute to Cloudflare.
After migrating heavy compute tasks to Cloudflare, Convex now serves as the primary data store, authentication layer, and orchestration system. The remaining Convex functionality focuses on:
- User Management & Authentication
- Data Persistence & Metadata Storage
- Content Moderation & Analysis
- Social Features (Favorites, Follows)
- Subscription & Billing Management
- Rate Limiting & System Maintenance
- Cloudflare Worker Dispatch & Orchestration
Purpose: Defines all database tables and their relationships. This is the foundation of the entire data model.
Key Tables:
users- User profiles with encrypted API keysgeneratedImages- AI-generated image metadata with moderation statusgeneratedImageDetails- Heavy fields split for performance optimizationpendingGenerations- Async single generation trackingbatchJobs/batchItems- Batch generation managementreferenceImages- User-uploaded reference imagesfavorites- User favorited imagesfollows- User social relationshipsprompts/userPromptLibrary- Shared prompt managementrateLimits- API rate limitingproviderHealth- External provider status trackingmusicGenerations- AI-generated music tracks
Purpose: Clerk JWT authentication configuration for Convex.
- Configures JWT issuer domain from Clerk "convex" template
- Enables secure authentication between frontend and Convex
Purpose: User profile management and API key storage.
getOrCreateUser- Creates or updates user records from Clerk identitygetCurrentUser- Retrieves current authenticated userupdateApiKey- Stores encrypted Pollinations API keysgetApiKey- Retrieves decrypted API keys for BYOP flowupdateContentFilterPreference- Manages sensitive content settingsupdateDefaultPrivate- Controls default generation visibility
Purpose: Generates random usernames for new users.
- Creates privacy-preserving usernames when users first sign up
Purpose: Manages single image generation lifecycle with Cloudflare dispatch.
startGeneration- Creates pending generation record and dispatches to CloudflaregetGeneration- Retrieves generation status and metadatagetActiveGenerations- Gets user's in-progress generationscancelGeneration- Cancels pending generationsstoreGeneratedImage- Stores completed image metadata from CloudflarecleanupStuckGenerations- Recovers from orphaned generation records
Purpose: Handles batch image generation with chunked Cloudflare dispatch.
startBatchJob- Creates batch job and schedules first chunkgetBatchJob- Retrieves batch job status and progressgetActiveBatchJobs- Gets user's active batch jobspauseBatchJob/resumeBatchJob/cancelBatchJob- Batch lifecycle managementstoreBatchItemImage- Stores individual batch item resultsprocessBatchQueue- Internal queue processor for chunked dispatch
Purpose: Dispatches generation jobs to Cloudflare workers with retry logic.
dispatchSingleGeneration- Sends single generation jobs to workersdispatchBatchItem- Sends batch item jobs to workersdispatchPromptInference- Sends content analysis jobsdispatchVisionAnalysis- Sends image analysis jobsdispatchSecondaryAssets- Sends video derivative processing jobs
Purpose: HTTP endpoints for Cloudflare worker callbacks.
claimSingleGeneration- Worker claim endpoint for single generationscompleteSingleGeneration- Worker completion callbackfailSingleGeneration- Worker failure callbackclaimBatchItem/completeBatchItem/failBatchItem- Batch item lifecycleupdatePromptInference/updateVisionAnalysis- Content analysis callbacksupdateSecondaryAssets- Video derivative processing callbacks
Purpose: Coordinates AI-powered content moderation and analysis.
analyzeRecentImages- Catches up on unanalyzed imagesdispatchPromptInference- Sends prompts for AI analysisdispatchVisionAnalysis- Sends images for visual analysishandlePromptInferenceResult- Processes prompt analysis resultshandleVisionAnalysisResult- Processes visual analysis resultsanalyzeUnanalyzedImages- Recovery mechanism for stuck analysis
Purpose: Client-side NSFW keyword detection for immediate feedback.
analyzePromptForNSFW- Basic keyword-based content filtering- Provides instant feedback before server-side analysis
Purpose: AI-powered prompt analysis using external providers.
analyzePromptWithAI- Sends prompts to Groq/OpenRouter for analysis- Handles provider health and rate limiting
Purpose: AI-powered image content analysis.
analyzeImageWithAI- Sends images to vision analysis providers- Detects nudity, violence, and other sensitive content
Purpose: User favorite image management.
toggle- Adds/removes images from favoritesisFavorited- Checks favorite statuslist- Paginated user favoritesbatchIsFavorited- Efficient batch favorite status checks
Purpose: User social relationship management.
follow/unfollow- Manage user relationshipsisFollowing- Check follow statusgetFollowStats- Get follower/following counts
Purpose: Stripe subscription management and checkout.
createSubscriptionCheckout- Creates Stripe checkout sessionsgetSubscriptionStatus- Retrieves user subscription statusmanageBillingUrl- Creates Stripe customer portal links
Purpose: Subscription logic and trial management.
hasActiveSubscription- Checks for active Pro subscriptionisInTrialPeriod- Checks 24-hour trial eligibilitycanUserGenerate- Validates generation permissionsgetSubscriptionStatus- Gets detailed subscription status
Purpose: Stripe SDK utilities and error handling.
createStripeClient- Configures Stripe clientgetStripeErrorMessage- Normalizes Stripe errorsresolvePriceForPlan- Dynamic price resolution via lookup keys
Purpose: Shared prompt management and discovery.
searchPrompts- Full-text search across all promptssavePromptToLibrary- Saves prompts with deduplicationremovePromptFromLibrary- Removes prompts from user librarygetUserLibrary- Gets user's saved promptsisInLibrary- Checks if prompt is saved
Purpose: User-uploaded reference image management for image-to-image generation.
create- Stores new reference image metadatagetById- Retrieves specific reference image (owner only)getMyImages- Paginated user reference imagesremove- Deletes reference image recordgetByR2Key- Deduplication check by R2 storage keygetRecent- Gets recent reference images (limited)
Purpose: AI-generated music track persistence and reactions.
create- Stores new music generation recordssetReaction- Manages like/dislike reactionsupdateTitle- Updates track titleslistByOwner- Lists user's music generations with filtering
Purpose: Sliding window rate limiting for API endpoints.
checkRateLimit- Consumes rate limit quotagetRateLimitStatus- Checks remaining quota without consumingcleanupExpiredLimits- Removes expired rate limit records
Purpose: Scheduled maintenance tasks.
- Hourly rate limit cleanup
- Daily orphaned R2 object cleanup
- 5-minute stuck generation cleanup
- Hourly content analysis recovery
Purpose: Identifies and cleans up orphaned R2 storage objects.
auditOrphanedObjects- Scans for objects without Convex recordscleanupOrphanedObjects- Deletes confirmed orphaned objects- Prevents storage bloat from failed operations
Purpose: Development-only admin utilities.
grantProByEmail- Grants synthetic Pro subscriptions (dev only)revokeProByEmail- Revokes dev-granted subscriptions- Internal mutations - not exposed to public API
Purpose: AES-256-GCM encryption for API key storage.
encryptApiKey/decryptApiKey- Secure API key handling- Web Crypto API implementation (Convex V8 runtime compatible)
Purpose: Batch generation state management logic.
getBatchStatusAfterItemSettlement- Determines batch statusgetResumeBatchDecision- Batch resumption logic
Purpose: External provider availability tracking.
- Monitors rate limits for Groq/OpenRouter
- Prevents wasteful API calls during rate limit periods
Purpose: Retry logic with exponential backoff.
calculateRetryDelay- Smart retry timing- Handles transient failures gracefully
Purpose: Pollinations API client for image generation.
generateImage- Main generation API clientcheckGenerationStatus- Status polling- Model-specific parameter handling
- Error handling and retry logic
Purpose: Groq LLM API client for prompt analysis.
analyzePrompt- Prompt content analysis- Rate limit handling and error parsing
- Provider health integration
Purpose: OpenRouter LLM API client for prompt analysis.
analyzePrompt- Alternative prompt analysis provider- Provider fallback support
- Rate limit and error handling
Purpose: Central HTTP route registry for all Convex HTTP endpoints.
- Stripe Webhooks: Registers
/stripe/webhookfor subscription events - Cloudflare Worker Routes: All worker callback endpoints for generation and moderation
- Provider Health:
/workers/provider-health/rate-limitfor rate limit reporting
customer.subscription.created/updated/deleted- Subscription lifecyclecheckout.session.completed- Payment completionpayment_intent.succeeded/failed- Payment statusinvoice.created/paid/failed- Billing events
Purpose: Core AI-generated image CRUD operations with optimized queries.
create- Creates new image records with initial NSFW analysisgetById- Secure image retrieval with visibility checksgetMyImages- Optimized gallery thumbnails with filtering (visibility, models)getMyImagesWithDisplayData- History page with full display info (no generationParams)getPublicFeed- Public feed with content filtering and bandwidth optimizationgetImagesByUsername- User-specific public galleriesgetFollowingFeed- Social feed from followed users (optimized per-user queries)setVisibility- Visibility updates with NSFW analysis for private→public transitions
Optimization Features:
- Lightweight thumbnail format for gallery (90% bandwidth reduction)
- Public feed optimization with owner enrichment
- Advanced indexing strategy for multi-dimensional filtering
- Content-sensitive feed filtering (block/blur/allow)
Purpose: Video thumbnail and preview generation lifecycle management.
updateSecondaryAssets- Stores thumbnail/preview URLs from workersmarkSecondaryAssetsDispatched- Dispatch state management with retry trackingclaimSecondaryAssetsForWorker- Worker claim mechanism with duplicate preventiongetSecondaryAssetsWorkerContinuationState- Worker resume capabilitycompleteSecondaryAssetsFromWorker- Completion handling with duplicate detectionfailSecondaryAssetsFromWorker- Failure handling with error storage
Purpose: Development and maintenance utilities.
getSystemTime- Server time verificationforceCleanupAllStuck- Manual cleanup of stuck generations (15+ minutes)
Purpose: Advanced troubleshooting and user diagnostics.
verifyUserAndGenerations- Complete user state analysis with similar user detectiondiagnoseCronCleanup- Cron job visibility and stuck generation diagnosticsforceCleanStuckGenerations- User-specific stuck generation cleanup
Purpose: NSFW tagging progress and statistics.
getTaggingStatus- Efficient tagging completion statistics- Performance-optimized queries with indexed lookups
- Legacy record detection and counting
Purpose: P0 optimization migration for table splitting. Status: ✅ Complete for development, production deployment required
- Phase 1: Copy heavy fields to
generatedImageDetailstable - Phase 2: Strip legacy fields from main records
- Preview functions for safe migration planning
- Batch processing to respect Convex limits
Purpose: One-time sensitivity threshold adjustment.
- Migrates vision analysis results from 0.5 to 0.8 threshold
- Updates images incorrectly marked as sensitive
- Preview and batch processing capabilities
Purpose: Data access patterns for orphan cleanup operations.
getAllR2Keys- Collects all R2 storage keys from images and references- Supports orphaned object detection and cleanup
Purpose: Dirtberry model watermark removal processing.
isDirtberryModel- Model detectioncalculateDirtberryCropRegion- 3% top/bottom trim calculationcropDirtberryImageBuffer- Jimp-based image processing (Convex compatible)- Constants for source dimensions and trim fractions
Purpose: Provider health management API functions.
checkProvidersAvailable- Availability statusgetHealth/getAllHealth- Health status queriesrecordRateLimit/recordRateLimitWithReset- Rate limit trackingmarkAvailable- Manual provider resetrefreshExpiredLimits- Automatic limit expirationresetAllProviders- Debug utilities
Purpose: Internal HTTP client for Cloudflare communication.
- HTTP utilities for worker dispatch and callbacks
- Error handling and retry logic
- Response parsing and validation
Purpose: Convex app configuration with middleware.
- Stripe component integration
- App middleware setup
Purpose: Standard Convex development documentation.
- Function examples and patterns
- Basic usage instructions
- Heavy Compute: Actual image/video generation API calls
- File Processing: Media uploads to R2 storage
- External API Calls: Pollinations provider interactions
- Long-running Operations: Generation processing loops
- Data Persistence: All metadata and user data
- Authentication & Authorization: User identity and permissions
- Social Features: Favorites, follows, user interactions
- Content Moderation: Analysis coordination and results storage
- Business Logic: Subscription management, rate limiting
- Orchestration: Job dispatch and lifecycle management
- System Maintenance: Cleanup tasks and health monitoring
- Cost Efficiency: Heavy compute moved to cheaper Cloudflare workers
- Performance: Convex focused on fast data operations
- Reliability: Separate failure domains for compute vs data
- Scalability: Independent scaling of compute and storage layers
- Client retrieves encrypted API key from Convex
- Client sends API key with generation request
- Convex stores API key securely for worker use
- Cloudflare worker uses stored API key for generation
- Results flow back through Convex for persistence
- Convex creates job record with "pending" dispatch status
- Internal action dispatches job to Cloudflare worker
- Worker claims job via HTTP callback
- Worker processes and reports completion/failure
- Convex updates final status and stores results
- Initial prompt analysis during generation
- Vision analysis after image generation
- Results stored in image metadata
- User preferences control content display
This documentation reflects the current state of Convex functionality after the Cloudflare migration, focusing on its role as the data and orchestration layer rather than heavy compute processing.