Platform Architecture
A modular, high-performance framework for building AI-powered applications with integrated session management, secure storage, and cloud-native capabilities.
System Design
/architectureApplication Services
/servicesThe ApplicationServices object is the central registry for all platform services, providing unified access to authentication, storage, and cloud capabilities.
// Access services
val authManager = ApplicationServices.authenticationManager
val authzManager = ApplicationServices.authorizationManager
val storage = ApplicationServices.fileApplicationServices().dataStorageFactory
val cloud = ApplicationServices.cloud
val usageManager = ApplicationServices.fileApplicationServices().usageManager
val threadPoolManager = ApplicationServices.threadPoolManager
Session Management
The platform uses a structured session ID system to isolate global resources from user-specific data.
Session ID Format:
-
G-YYYY-MM-DD-XXXX— Global sessions (accessible to all users) -
U-YYYY-MM-DD-XXXX— User sessions (private to owner) -
YYYY-MM-DD-XXXX— Legacy format (treated as global)
// Create new sessions
val globalSession = Session.newGlobalID()
val userSession = Session.newUserID()
// Parse and validate
val session = Session.parseSessionID("G-20231215-AbC1")
// Check session type
if (session.isGlobal()) {
// Handle global session
}
User Identity
The User data class encapsulates authenticated identity and credentials.
val user = User(
email = "user@example.com",
name = "John Doe",
id = "user123",
picture = "https://example.com/avatar.jpg",
credential = oauthCredential // Optional
)
Thread Pool Management
The ThreadPoolManager provides execution contexts scoped to specific sessions and users.
// Get a standard thread pool for a session
val pool = ApplicationServices.threadPoolManager.getPool(session, user)
// Get a scheduled executor
val scheduledPool = ApplicationServices.threadPoolManager.getScheduledPool(session, user)
Storage Architecture
Data Storage Interface
The StorageInterface handles physical persistence of session data:
- • Message Persistence: Storing and retrieving chat messages
- • Session Management: Listing, deleting, organizing directories
- • JSON Data: Generic storage for session config and state
File Storage Implementation
val dataStorage = DataStorage(File("/path/to/data"))
// Store JSON data
dataStorage.setJson(user, session, "config.json", myConfig)
// Update messages
dataStorage.updateMessage(user, session, "msg-123", "Hello World")
// Get session directory
val sessionDir = dataStorage.getSessionDir(user, session)
Metadata Storage
The HSQLMetadataStorage manages high-level session information separately from raw content for fast querying.
val metadataStorage = HSQLMetadataStorage()
// Set session metadata
metadataStorage.setSessionName(user, session, "My Chat Session")
metadataStorage.setMessageIds(user, session, listOf("msg-1", "msg-2"))
// Query metadata
val sessionName = metadataStorage.getSessionName(user, session)
val messageIds = metadataStorage.getMessageIds(user, session)
Authorization Model
Authentication
The AuthenticationManager handles user identity:
- • Maps access tokens to
Userobjects - • Manages the
sessionIdcookie - • Provides a
defaultUserfor local development
File-based Authorization
The AuthorizationManager uses resource files to define access. Supported operations:
Permission Syntax
/permissions/read.txt— Global read permissions/permissions/write.txt— Global write permissions/permissions/com/example/app/read.txt— App-specific permissions
AWS Integration
The AwsPlatform provides S3-based sharing and KMS-based encryption for enterprise deployments.
val awsPlatform = AwsPlatform(
bucket = "my-bucket",
shareBase = "https://my-bucket.s3.amazonaws.com",
region = Region.US_EAST_1,
profileName = "my-profile"
)
// Upload file
val url = awsPlatform.upload("path/to/file.txt", "text/plain", fileBytes)
// Encrypt/decrypt with KMS
val encrypted = awsPlatform.encrypt(data, kmsKeyArn)
val decrypted = awsPlatform.decrypt(encryptedData)
share_bucket— S3 bucket for uploadsshare_base— Base URL for shared linksaws.profile— AWS CLI profile for credentials
Usage Tracking
The HSQLUsageManager tracks API usage per session and user for billing and analytics.
val usageManager = HSQLUsageManager()
// Track usage
usageManager.incrementUsage(session, apiKey, ChatModel.GPT35Turbo, usage)
// Get summaries
val userUsage = usageManager.getUserUsageSummary(apiKey)
val sessionUsage = usageManager.getSessionUsageSummary(session)
User Settings
The UserSettings object contains structured configuration for AI providers and tools.
val userSettings = ApplicationServices
.fileApplicationServices()
.userSettingsManager
.getUserSettings(user)
// Update API configurations
val updatedSettings = userSettings.copy(
apiKeys = userSettings.apiKeys + ApiData(
provider = APIProvider.OpenAI,
key = "sk-..."
)
)
Developer Best Practices
Resource Isolation
Always use the ThreadPoolManager to get pools scoped to a session. This prevents one session from starving others of CPU resources.
threadPoolManager.getPool(session, user)
Error Handling
Validate session IDs at the entry point of every service call to prevent directory traversal or unauthorized access.
try {
val session = Session.parseSessionID(sessionId)
// Use session
} catch (e: IllegalArgumentException) {
log.error("Invalid session ID: $sessionId", e)
}
Resource Management
Always ensure directories exist and use proper stream handling for file operations.
val sessionDir = dataStorage
.getSessionDir(user, session)
.apply { mkdirs() }
sessionDir.resolve("data.json")
.outputStream().use { output ->
// Write data
}
Security
- • Validate user permissions before operations
- • Use encrypted storage for sensitive data
- • Implement proper session timeout mechanisms
Performance
- • Cache frequently accessed data
- • Use appropriate thread pools for concurrent operations
- • Monitor usage patterns and optimize accordingly
Configuration Locking
Lock the ApplicationServicesConfig after initialization to prevent runtime modification.
// Configure before locking
ApplicationServices.dataStorageRoot = File("/custom/data/path")
// Lock configuration
ApplicationServicesConfig.isLocked = true
Custom Service Implementation
Extend the platform with custom storage, authentication, or authorization implementations.
// Custom storage implementation
class CustomStorage(dataDir: File) : DataStorage(dataDir) {
override fun getMessages(user: User?, session: Session): LinkedHashMap<String, String> {
// Custom implementation
return super.getMessages(user, session)
}
}
// Register custom services
ApplicationServices.fileApplicationServices().dataStorageFactory = { file -> CustomStorage(file) }
ApplicationServices.authenticationManager = CustomAuthenticationManager()
ApplicationServices.authorizationManager = CustomAuthorizationManager()
// 1. Set data root
ApplicationServices.dataStorageRoot = File("/var/lib/cognotik")
// 2. Initialize services
val dataDir = ApplicationServices.dataStorageRoot
val storage = ApplicationServices.fileApplicationServices().dataStorageFactory(dataDir)
// 3. Lock configuration to prevent changes
ApplicationServicesConfig.isLocked = true