T4 — Thiết kế kiến trúc tổng thể - congsinhv/fluxion GitHub Wiki

Thiết Kế Kiến Trúc Tổng Thể Fluxion MDM

Numbering chính thức: Mục 3.2 theo Master TOC

Issue: #21 — Thiết kế kiến trúc tổng thể (Component Diagram) Tuần: 4 | 14/04 – 20/04/2026


3.2.1 Component Diagram

3.2.1.1 Tổng Quan Kiến Trúc

Fluxion được thiết kế theo kiến trúc 100% serverless, event-driven trên AWS, chia thành 3 lớp chính: UI, BE (Backend), OEM (Original Equipment Manufacturer — 3rd party integration).

Kiến trúc tổng thể Fluxion MDM

Hình 3.2.1: Sơ đồ kiến trúc tổng thể hệ thống Fluxion MDM trên AWS. Biểu tượng AWS chính thức thể hiện các dịch vụ: Lambda (resolvers + workers), AppSync (GraphQL API), SQS/SNS (messaging), RDS (PostgreSQL), ElastiCache (Redis), API Gateway (OEM endpoint).

Mermaid Diagram (tham khảo)

graph TB
    subgraph "External"
        LLM[LLM API — GPT-4o mini]
        IOS_3RD[ios-3rd-party — Apple APNS]
        IOS_DEV[iOS Device]
    end

    subgraph "UI Layer"
        CLIENT[Client — React + Tailwind]
    end

    subgraph "BE Layer — Resolvers"
        APPSYNC[AWS AppSync]
        COGNITO[AWS Cognito]
        CH[chat-resolver λ]
        UR[user-resolver λ]
        PR[platform-resolver λ]
        DR[device-resolver λ]
        UPR[upload-resolver λ]
        AR[action-resolver λ]
        MTR[message-template-resolver λ]
        TR[tac-resolver λ]
        ALR[action-log-resolver λ]
    end

    subgraph "BE Layer — Workers"
        SQS_UP[upload-processor-sqs]
        UP[upload-processor λ]
        SQS_AT[action-trigger-sqs]
        AT[action-trigger λ]
        CK[checkin-handler λ]
        SQS_CK[checkin-handler-sqs]
    end

    subgraph "Event Layer"
        SNS[device-event-sns]
        SQS_OEM[apple-process-action-sqs]
    end

    subgraph "OEM Layer"
        OEM_L[apple-process-action λ]
        APIGW[fluxion-oem-service — API Gateway]
        CACHE[(ElastiCache Redis)]
    end

    subgraph "Data Layer"
        RDS[(RDS PostgreSQL)]
        S3_ERR[(S3 error-reports)]
    end

    LLM -.-> CH
    CLIENT --> APPSYNC
    CLIENT --> COGNITO
    COGNITO -->|JWT| APPSYNC

    APPSYNC --> CH & UR & PR & DR & UPR & AR & MTR & TR & ALR

    UPR --> SQS_UP --> UP --> RDS
    AR --> SQS_AT --> AT --> RDS
    CH & UR & PR & DR & MTR & TR & ALR --> RDS
    ALR --> S3_ERR

    AT -->|publish| SNS
    SNS --> SQS_OEM --> OEM_L
    OEM_L <--> CACHE
    OEM_L -->|POST /apns| APIGW -->|proxy| IOS_3RD
    IOS_DEV -->|PUT /mdm| APIGW -->|invoke| OEM_L
    OEM_L --> SQS_CK --> CK --> RDS

    CK -->|subscription trigger| APPSYNC
    APPSYNC -->|subscription push| CLIENT
Loading

3.2.1.2 3-Layer Architecture

Layer Responsibility DB Access 3rd Party Access
UI User interface
BE Business logic, DB CRUD ✅ RDS ❌ (trừ LLM cho chatbot)
OEM Apple MDM protocol ✅ APNS, MDM devices

Nguyên tắc: BE chỉ biết DB. OEM chỉ biết 3rd party. Giao tiếp giữa BE ↔ OEM qua SNS/SQS events.

3.2.1.3 Mô Tả Các Component

UI Layer

Component Công nghệ Vai trò
Dashboard React 19 + Tailwind CSS Giao diện quản lý: device list, detail, command status, stats
Chat UI React component Giao diện chatbot NLP tích hợp trong dashboard

BE Layer — Lambda Resolvers (AppSync)

Lambda Vai trò
chat-resolver Process chat → LLM (GPT-4o mini) → tool calls → response
user-resolver CRUD users, role management
platform-resolver Platform config (states, policies, actions, services)
device-resolver CRUD devices, query by state/ID
upload-resolver Validate upload request + enqueue to SQS
action-resolver Validate action (+ load MessageTemplate khi có messageTemplateId) + enqueue to SQS; tạo batch_actions/batch_device_actions rows
message-template-resolver CRUD MessageTemplate (name, content, notificationType, icons)
tac-resolver CRUD TAC + Brand (Type Allocation Code management)
action-log-resolver Query batch_actions; mutation generateActionLogErrorReport → render CSV → upload S3 → return pre-signed URL

BE Layer — Lambda Workers

Lambda Trigger Vai trò
upload-processor SQS (upload-processor-sqs) Batch INSERT devices + device_informations vào RDS
action-trigger SQS (action-trigger-sqs) INSERT action_executions (ACTION_PENDING), UPDATE devices, publish command → SNS
checkin-handler SQS (checkin-handler-sqs, from OEM) Process device events → update DB (tokens, device info, action results)

OEM Layer

Component Type Vai trò
API Gateway HTTP API fluxion.oem-service.com/api/v1/apple — tất cả HTTPS traffic
apple-process-action Lambda (SQS + API GW) 1 Lambda, 2 triggers: cache + APNS (SQS) và MDM protocol (API GW)
Command Cache Redis hoặc DynamoDB Temporary command storage — OEM không query RDS

API Gateway routes:

Route Direction Target
PUT /mdm Inbound (device → Fluxion) → invoke apple-process-action λ
POST /apns/{token} Outbound (Fluxion → Apple) → HTTP proxy → api.push.apple.com

Lambda không gọi HTTPS trực tiếp — mọi HTTP traffic đi qua API Gateway → no NAT Gateway needed.

Event Layer

Component Vai trò
device-event-sns Fan-out commands từ BE → OEM
upload-processor-sqs Buffer cho upload-processor Lambda
action-trigger-sqs Buffer cho action-trigger Lambda
apple-process-action-sqs Buffer cho apple-process-action Lambda (from SNS)
checkin-handler-sqs Buffer cho checkin-handler Lambda (from OEM)
DLQ Capture messages thất bại sau 3 retries

Data Layer

Store Dịch vụ Dữ liệu
PostgreSQL RDS db.t3.micro devices, device_informations, device_tokens, users, action_executions, milestones, chat, message_templates, brands, tacs, batch_actions, batch_device_actions
S3 S3 Standard Terraform state, static assets, action log error reports (action-log-errors/{batchId}.csv — pre-signed URL download, TTL 5 min)

3.2.2 Deployment Diagram (AWS Infrastructure)

graph TB
    subgraph "AWS Region"
        subgraph "Public"
            CF[CloudFront CDN]
            APPSYNC_SVC[AppSync Service]
            COGNITO_SVC[Cognito User Pool]
            APIGW_SVC[API Gateway — mTLS<br/>MDM endpoint]
        end

        subgraph "Private Subnet"
            LAMBDA_BE[BE Lambdas<br/>resolvers + workers]
            LAMBDA_OEM[OEM Lambda<br/>apple-process-action]
            RDS_PRI[(RDS Primary<br/>db.t3.micro)]
        end

        subgraph "Messaging"
            SNS_SVC[SNS Topics]
            SQS_SVC[SQS Queues + DLQ]
        end

        subgraph "Cache"
            CACHE_SVC[ElastiCache Redis<br/>or DynamoDB]
        end

        CF --> S3_STATIC[S3 Static<br/>React Build]
    end

    INTERNET((Internet)) --> CF
    INTERNET --> APPSYNC_SVC
    IOS((iOS Devices)) -->|mTLS| APIGW_SVC
    APIGW_SVC --> LAMBDA_OEM
    LAMBDA_OEM --> CACHE_SVC
    LAMBDA_OEM --> APNS_EXT((Apple APNS))
    LAMBDA_BE --> LLM_EXT((GPT-4o mini))
    LAMBDA_BE --> RDS_PRI
Loading

3.2.2.1 Network Architecture

Zone Components Access
Public CloudFront, AppSync, Cognito, API Gateway (mTLS) Internet-facing
Private All Lambda functions, RDS VPC internal; outbound NAT Gateway
Messaging SNS, SQS AWS managed; VPC endpoint
Cache ElastiCache Redis / DynamoDB VPC internal (Redis) or AWS managed (DynamoDB)

3.2.2.2 Terraform Modules

Module Resources
network VPC, subnets, NAT, security groups
database RDS PostgreSQL, subnet group
auth Cognito User Pool, App Client
api AppSync API, all BE resolvers
compute-be BE Lambda functions, IAM roles
compute-oem apple-process-action Lambda, IAM roles
messaging SNS topics, SQS queues, DLQ
mdm-endpoint API Gateway HTTP API, mTLS config, custom domain
cache ElastiCache Redis cluster / DynamoDB table

3.2.3 Luồng Dữ Liệu Chính

3.2.3.1 Command Flow (Lock Device)

Admin → Dashboard → AppSync mutation assignAction(deviceId, actionId)
  → action-resolver λ [validate: busy? valid transition?]
    → SQS (action-trigger-sqs)
      → action-trigger λ [INSERT action_executions: ACTION_PENDING, UPDATE devices]
        → SNS (command-sns) [command payload + device tokens]
          → SQS (apple-process-action-sqs)
            → apple-process-action λ [cache command → Redis]
              → API Gateway POST /apns/{token} → proxy → APNS [silent push]
                → iOS Device [wake up]
                  → API Gateway PUT /mdm → apple-process-action λ [read cache → respond]
                    → Device executes DeviceLock
                      → API Gateway PUT /mdm → apple-process-action λ [receive result]
                        → SNS (checkin-sns) [ACTION_COMPLETED]
                          → SQS → checkin-handler λ
                            → UPDATE action_executions: ACTION_COMPLETED
                            → UPDATE devices: current_policy_id → Locked
                            → INSERT milestones
                            → AppSync subscription → Dashboard real-time update

3.2.3.2 Checkin Events

Event Source checkin-handler Action
DEVICE_TOKEN_UPDATE Device TokenUpdate check-in UPSERT device_tokens (push_token, push_magic, unlock_token)
DEVICE_RELEASED Device CheckOut (MDM profile removed) — trigger khi khách hoàn tất hợp đồng trả góp (graduation) UPDATE devices → Released policy; data khách giữ nguyên
ACTION_COMPLETED Device Status=Acknowledged UPDATE action_executions + devices.current_policy_id + INSERT milestones
ACTION_FAILED Device Status=Error UPDATE action_executions → FAILED, clear assigned_action_id

3.2.3.3 Chat Flow

Admin → Chat UI → AppSync mutation sendChatMessage(input)
  → chat-handler λ
    → validate JWT → load 10 recent messages from RDS
      → build [system_prompt + history + user_msg]
        → call GPT-4o mini API (with tools)
          → LLM returns tool_call → Lambda executes tool
            → return response to user via AppSync

3.2.3.4 Real-time Subscription Flow

Dashboard (React) → AppSync WebSocket → subscribe onDeviceStateChange
  ...
  checkin-handler receives ACTION_COMPLETED event → updates RDS
    → triggers AppSync mutation
      → AppSync pushes to all active subscriptions
        → Dashboard re-renders device card with new state

Kết Luận

Kiến trúc tổng thể Fluxion MDM được thiết kế theo mô hình 3 lớp phân tách nghiêm ngặt (UI, BE, OEM), toàn bộ triển khai trên nền tảng serverless AWS. Nguyên tắc cốt lõi — BE chỉ biết DB, OEM chỉ biết 3rd party, giao tiếp qua SNS/SQS events — đảm bảo tính độc lập giữa các lớp và khả năng thay thế từng thành phần mà không ảnh hưởng toàn hệ thống. Mỗi lựa chọn công nghệ có lý do rõ ràng: AppSync cho real-time subscriptions, Lambda cho pay-per-use scaling, RDS Proxy cho connection pooling, và API Gateway làm điểm tập trung toàn bộ HTTPS traffic (loại bỏ NAT Gateway cho Lambda).

Sơ đồ Component Diagram thể hiện 9 Lambda resolvers (6 core + 3 admin: message-template, tac, action-log), 3 Lambda workers, 5 SQS queues, 1 SNS topic, và 1 OEM layer xử lý Apple MDM protocol. Deployment Diagram với 9 Terraform modules đảm bảo hạ tầng reproducible và có thể tái tạo hoàn toàn từ code. Các luồng dữ liệu chính (Command Flow, Checkin Events, Chat Flow, Real-time Subscription) được thiết kế theo Choreography Saga pattern — không có điểm điều phối tập trung (orchestrator), giảm thiểu single point of failure.

Kiến trúc này cân bằng giữa độ phức tạp cần thiết để minh chứng Event-Driven Architecture và nguyên tắc KISS phù hợp với quy mô đồ án tốt nghiệp. Chi phí vận hành ước tính dưới $50/tháng cho fleet 100 thiết bị, đáp ứng NFR5 về Cost Efficiency.

Tài Liệu Tham Khảo

[1] Bass, L., Clements, P., Kazman, R. Software Architecture in Practice, 4th ed. Addison-Wesley, 2021.

[2] Richards, M. & Ford, N. Fundamentals of Software Architecture. O'Reilly, 2020.

[3] AWS. Serverless Application Lens — Well-Architected Framework. 2023.

[4] Richardson, C. Microservices Patterns. Manning, 2018.

⚠️ **GitHub.com Fallback** ⚠️