Platform Architecture
Badges: Core Platform · v1.2.0 Stable
Hero
Platform Architecture — A modular, high-performance framework for building AI-powered applications with integrated session management, secure storage, and cloud-native capabilities.
System Design (Architecture Layers)
Application Layer
User-facing logic & UI Integration
↓
Platform Services
[Thread Pool] [Usage Tracking] [User Settings]
↓
Interface Layer
[Storage API] [Auth API] [Cloud API]
↓
Implementation Layer
[File System] [HSQL DB] [AWS SDK]
Application Services
The 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
Sessions & Users
Session Management
The platform uses a structured session ID system to isolate global resources from user-specific data.
Session ID Format:
| Format | Meaning |
|---|---|
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.newUserID()
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)
Data Storage
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
Directory layout:
data/
├── global/ # Shared sessions
│ └── 2023-12-15/
│ └── AbC1/
│ ├── messages/
│ └── config.json
├── user-sessions/ # Private data
│ └── user@example.com/
│ └── 2023-12-15/XyZ2/
└── users/ # User profiles
└── user@example.com.json
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)
Auth & Permissions
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:
Read, Write, Public, Share, Execute, Delete, Admin.
Permission Syntax
| Syntax | Meaning |
|---|---|
user@example.com |
Specific user access |
@company.com |
Domain-wide access |
. |
Any authenticated user |
* |
Public access (Anonymous) |
Permission files:
/permissions/read.txt— Global read permissions/permissions/write.txt— Global write permissions/permissions/com/example/app/read.txt— App-specific permissions
Cloud 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)
Configuration properties:
share_bucket— S3 bucket for uploadsshare_base— Base URL for shared linksaws.profile— AWS CLI profile for credentials
Usage & Settings
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
ThreadPoolManagerto 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
ApplicationServicesConfigafter 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()
Quick Start: Initializing the Platform
// 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