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:

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:

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:

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:

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

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