Core Platform v1.2.0 Stable

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
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

/services

The ApplicationServices object is the central registry for all platform services, providing unified access to authentication, storage, and cloud capabilities.

kotlin
// 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)
kotlin
// 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.

kotlin
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.

kotlin
// 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
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

kotlin
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.

kotlin
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 User objects
  • • Manages the sessionId cookie
  • • Provides a defaultUser for local development

File-based Authorization

The AuthorizationManager uses resource files to define access. Supported operations:

Read Write Public Share Execute Delete Admin

Permission Syntax

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

AWS Integration

The AwsPlatform provides S3-based sharing and KMS-based encryption for enterprise deployments.

kotlin
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 uploads
  • share_base — Base URL for shared links
  • aws.profile — AWS CLI profile for credentials

Usage Tracking

The HSQLUsageManager tracks API usage per session and user for billing and analytics.

kotlin
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.

kotlin
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.

kotlin
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.

kotlin
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.

kotlin
// 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.

kotlin
// 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
kotlin
// 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