# Smartbotic Microbit Architecture This document describes the architecture and design of the Smartbotic Microbit platform. ## System Overview Smartbotic Microbit is a multi-tier application consisting of three primary components: ``` ┌─────────────────┐ │ Web Browser │ (React/TypeScript SPA) └────────┬────────┘ │ HTTP/REST ▼ ┌─────────────────┐ │ Microbit Service│ (C++ HTTP Server) └────────┬────────┘ │ gRPC ▼ ┌─────────────────┐ │ Database Service│ (Custom Storage Engine) └─────────────────┘ ``` ## Component Architecture ### 1. Microbit Service (Backend) The main application server implemented in C++20, providing RESTful API endpoints and business logic. #### Core Components **App (`src/app.cpp`)** - Main application entry point - Manages component lifecycle - Initializes all services, stores, and routes - HTTP server configuration **HTTP Layer** - Uses `cpp-httplib` for HTTP server - RESTful API endpoints organized by feature - JWT-based authentication middleware - CORS support - Request/response handling #### Module Structure ``` src/ ├── main.cpp # Application entry point ├── app.{hpp,cpp} # Main app class ├── routes/ # HTTP route handlers │ ├── auth_routes # Authentication endpoints │ ├── user_routes # User management │ ├── workspace_routes # Workspace CRUD │ ├── assistant_routes # AI assistant management │ ├── calendar_routes # Calendar & appointments │ ├── invitation_routes # Team invitations │ └── settings_routes # Settings management ├── services/ # Business logic layer │ ├── auth_service # Authentication logic │ ├── workspace_service # Workspace operations │ ├── invitation_service# Invitation workflow │ ├── assistant_service # Assistant management │ └── calendar_service # Calendar operations └── stores/ # Data access layer ├── user_store # User data operations ├── workspace_store # Workspace data ├── assistant_store # Assistant data ├── calendar_store # Calendar data ├── invitation_store # Invitation data └── settings_store # Settings data ``` #### Library Modules ``` lib/ ├── auth/ # Authentication & authorization │ ├── jwt_utils # JWT token generation/validation │ ├── bcrypt_utils # Password hashing │ └── auth_middleware # Request authentication ├── common/ # Common utilities │ ├── config_loader # Configuration parsing │ ├── logging # Logging utilities │ └── utils # General utilities ├── smtp/ # Email sending │ └── smtp_client # SMTP client implementation └── callerai/ # CallerAI integration └── callerai_client # CallerAI API client ``` ### 2. Database Service Custom database service providing persistent storage via gRPC interface. **Location**: `external/smartbotic-database` (git submodule) **Key Features**: - Collection-based storage model - Document-oriented (JSON documents) - Query and indexing support - Migration system - gRPC API **Client Interface**: `smartbotic::database::Client` - CRUD operations on collections - Query execution - Transaction support ### 3. Web UI Modern single-page application built with React and TypeScript. ``` webui/ ├── src/ │ ├── main.tsx # Application entry point │ ├── App.tsx # Root component & routing │ ├── api/ # Backend API client │ ├── pages/ # Page components │ │ ├── auth/ # Login, Register │ │ ├── dashboard/ # Main dashboard │ │ ├── members/ # Team member management │ │ ├── invitations/ # Invitation management │ │ ├── assistants/ # AI assistant pages │ │ └── calendar/ # Calendar & appointments │ ├── components/ # Reusable UI components │ └── stores/ # Client-side state (Zustand) ├── package.json └── vite.config.ts ``` **Key Technologies**: - **React 19**: UI framework - **TypeScript**: Type safety - **Tailwind CSS**: Styling - **React Router**: Client-side routing - **TanStack Query**: Server state management - **Zustand**: Client state management - **Vite**: Build tool and dev server ## Data Model ### Core Entities **User** - `id`: Unique identifier (usr_xxx) - `email`: User email (unique) - `password_hash`: BCrypt hashed password - `display_name`: User's display name - `status`: Account status (active, suspended) **Workspace** - `id`: Unique identifier (ws_xxx) - `name`: Workspace name - `company_name`: Company name - `address`: Physical address - `phone`: Contact phone number **WorkspaceMember** - `id`: Unique identifier (wm_xxx) - `workspace_id`: Reference to workspace - `user_id`: Reference to user - `role`: Member role (owner, admin, member, guest) **Assistant** (AI Voice Assistant) - `id`: Unique identifier (ast_xxx) - `workspace_id`: Owning workspace - `name`: Assistant name - `phone_number`: Phone number for calls - `instructions`: AI behavior instructions - `callerai_id`: CallerAI platform ID - `status`: Active/inactive status **Calendar** - `id`: Unique identifier (cal_xxx) - `workspace_id`: Owning workspace - `name`: Calendar name - `assistant_id`: Associated assistant (optional) **TimeSlot** - `id`: Unique identifier (ts_xxx) - `calendar_id`: Parent calendar - `day_of_week`: Day (0=Sunday, 6=Saturday) - `start_time`: Slot start time (HH:MM) - `end_time`: Slot end time (HH:MM) **Appointment** - `id`: Unique identifier (apt_xxx) - `calendar_id`: Associated calendar - `start_time`: Appointment start (ISO 8601) - `end_time`: Appointment end (ISO 8601) - `customer_name`, `customer_phone`, `customer_email`: Customer info - `notes`: Appointment notes - `status`: pending, confirmed, cancelled **Invitation** - `id`: Unique identifier (inv_xxx) - `workspace_id`: Target workspace - `email`: Invitee email - `role`: Intended role - `token`: Unique invitation token - `status`: pending, accepted, rejected **Session** - `id`: Unique identifier (ses_xxx) - `user_id`: Associated user - Used for refresh token validation ## Authentication & Authorization ### Authentication Flow 1. **Registration**: `POST /api/v1/auth/register` - Validate password policy - Hash password with BCrypt - Create user record - Create session - Return JWT tokens (access + refresh) 2. **Login**: `POST /api/v1/auth/login` - Validate credentials - Delete old sessions - Create new session - Return JWT tokens 3. **Token Refresh**: `POST /api/v1/auth/refresh` - Validate refresh token - Check session validity - Issue new access token ### Authorization Model **JWT Claims**: - `sub`: User ID - `email`: User email - `role`: Global role (currently "user") - `exp`: Expiration timestamp **Workspace Roles** (per workspace): - **Owner**: Full control, can delete workspace - **Admin**: Manage members, assistants, calendars - **Member**: View and use workspace resources - **Guest**: Read-only access **Role Hierarchy**: ``` Owner > Admin > Member > Guest ``` ### Middleware Flow ``` Request → Auth Middleware → Route Handler │ ├─ Extract JWT from Authorization header ├─ Validate token signature ├─ Check expiration ├─ Store AuthContext (user_id, email, role) └─ Continue or reject (401) ``` Route handlers check workspace membership and roles as needed. ## Configuration System ### Configuration File Structure JSON-based configuration with environment variable substitution: ```json { "database": { "rpc_address": "${DB_ADDRESS:localhost:9004}" }, "auth": { "jwt_secret": "${JWT_SECRET:change-me-in-production}" } } ``` **Syntax**: `${VAR_NAME:default_value}` ### Configuration Loading `ConfigLoader` class: - Loads JSON configuration file - Resolves environment variables at runtime - Provides type-safe getters with defaults ### Configuration Files - **Development**: `config/microbit.json` - **Production**: `/etc/smartbotic/microbit.json` - **Environment**: `/etc/smartbotic/smartbotic.env` (sourced by systemd) ## External Integrations ### CallerAI Integration **Purpose**: Create and manage AI-powered voice assistants **Client**: `callerai::CallerAIClient` **Operations**: - Create assistant with phone number - Update assistant configuration - Delete assistant - List assistants **Configuration**: - `callerai.api_url`: CallerAI API endpoint - `callerai.api_key`: API authentication key - `callerai.timeout_sec`: Request timeout ### SMTP Integration **Purpose**: Send email notifications (invitations, etc.) **Client**: `smtp::SmtpClient` **Operations**: - Send invitation emails - Configurable templates **Configuration**: - `smtp.host`: SMTP server hostname - `smtp.port`: SMTP server port (default 587) - `smtp.username`: SMTP authentication username - `smtp.password`: SMTP authentication password - `smtp.from_address`: Sender email address - `smtp.use_tls`: Enable TLS (recommended) ## HTTP Server Architecture ### Request Flow ``` HTTP Request │ ├─ CORS Middleware (if enabled) │ └─ Add CORS headers │ ├─ Rate Limiting (if enabled) │ └─ Check request count │ ├─ Auth Middleware (protected routes) │ └─ Validate JWT token │ └─ Route Handler ├─ Parse request body ├─ Validate input ├─ Check authorization (workspace roles) ├─ Call service layer ├─ Access data via stores └─ Return JSON response ``` ### Error Handling Standard error responses: ```json { "error": "Error message" } ``` HTTP Status Codes: - `200` OK - Success - `201` Created - Resource created - `400` Bad Request - Invalid input - `401` Unauthorized - Missing/invalid token - `403` Forbidden - Insufficient permissions - `404` Not Found - Resource not found - `500` Internal Server Error - Server error ### Static File Serving The HTTP server can serve the WebUI static files: ```json { "http": { "static_files": { "enabled": true, "path": "webui/dist" } } } ``` When enabled, all non-API routes serve static files from the configured path. ## Build System ### CMake Structure ``` CMakeLists.txt # Root build configuration ├── cmake/ │ ├── CompilerFlags.cmake # Compiler settings │ ├── FindPackages.cmake # External package detection │ └── Dependencies.cmake # Dependency management ├── lib/CMakeLists.txt # Library builds │ ├── auth/ │ ├── common/ │ ├── smtp/ │ └── callerai/ └── src/CMakeLists.txt # Main application build ``` ### Build Options - `CMAKE_BUILD_TYPE`: Release|Debug (default: Release) - `BUILD_TESTS`: Build tests (default: OFF) - `BUNDLE_DATABASE`: Include database service in build (default: OFF) ### Dependencies **System Libraries**: - OpenSSL (libssl-dev) - gRPC and Protobuf - Abseil (from gRPC/Protobuf) **Bundled Libraries** (via CMake FetchContent): - cpp-httplib - nlohmann/json - spdlog - jwt-cpp - bcrypt (custom implementation) ## Deployment Architecture ### Systemd Services Two systemd services run the platform: 1. **smartbotic-database.service** - Runs the database service - Port: 9004 (gRPC) - Data: `/var/lib/smartbotic/database/` 2. **smartbotic-microbit.service** - Runs the main application - Port: 8090 (HTTP) - Depends on database service ### File System Layout ``` /opt/smartbotic/ ├── bin/ │ ├── smartbotic-database │ └── smartbotic-microbit └── share/smartbotic/ └── nginx/ └── smartbotic.conf.template /etc/smartbotic/ ├── database.json ├── microbit.json └── smartbotic.env /var/lib/smartbotic/ ├── database/ │ ├── storage/ │ └── migrations/ └── microbit/ └── webui/ /var/log/smartbotic/ ├── database.log └── microbit.log ``` ### Nginx Reverse Proxy (Optional) ``` Browser → Nginx (443) → Microbit Service (8090) ``` Nginx provides: - TLS termination - Reverse proxy to backend - Static file serving (WebUI) - Request logging Configuration template: `packaging/nginx/smartbotic.conf.template` ## Security Considerations ### Password Security - BCrypt hashing with salt - Configurable password policy (minimum length, character requirements) - Passwords never logged or returned in responses ### Token Security - JWT with HMAC-SHA256 signature - Short-lived access tokens (default: 15 minutes) - Long-lived refresh tokens (default: 7 days) - Refresh tokens tied to sessions (revocable) ### API Security - All protected endpoints require valid JWT - Workspace operations check membership - Role-based authorization enforced - Rate limiting available ### Configuration Security - Sensitive values via environment variables - Config files readable only by service user - Database connections over localhost or private network ## Logging ### Logging Framework: spdlog **Log Levels**: - `trace`: Detailed debug information - `debug`: Debug information - `info`: General information (default) - `warn`: Warning messages - `error`: Error conditions - `critical`: Critical errors **Configuration**: `log_level` in config file **Output**: - Development: Console output - Production: File output (`/var/log/smartbotic/microbit.log`) ## Performance Considerations ### Database Access - Connection pooling (managed by database client) - Efficient queries with indexes - Minimal round-trips per request ### HTTP Server - Single-threaded event loop (cpp-httplib) - Non-blocking I/O where possible - Keep-alive connections supported ### Caching - JWT validation caching (implicit in middleware) - No application-level caching currently implemented ### Rate Limiting - In-memory rate limiting per IP - Configurable limits: `rate_limit.requests_per_minute` ## Future Considerations ### Scalability - Horizontal scaling requires session store (Redis) - Database service already supports clustering - Load balancing via Nginx ### Monitoring - Prometheus metrics endpoint (planned) - Health check endpoints - Performance metrics ### Testing - Unit tests (planned: `BUILD_TESTS`) - Integration tests - API endpoint tests ## Conclusion The Smartbotic Microbit platform follows a layered architecture with clear separation of concerns: - **Routes**: HTTP request handling - **Services**: Business logic - **Stores**: Data access This design promotes maintainability, testability, and extensibility while providing a robust foundation for workspace management and AI assistant deployment.