Files
pos-system/services/social-service-net/docs/vi/ARCHITECTURE.md

8.7 KiB

Tài Liệu Kiến Trúc - Social Service

Tài liệu kiến trúc chi tiết cho Social Service - Dịch vụ quản lý quan hệ xã hội.

Tổng Quan Kiến Trúc

graph TB
    subgraph "Lớp API"
        RC[RelationshipsController]
        BC[BlocksController]
        CMD[Commands]
        Q[Queries]
        B[Behaviors]
    end
    
    subgraph "Lớp Domain"
        RA[Relationship Aggregate]
        UBA[UserBlock Aggregate]
        UPA[UserProfile Aggregate]
        DE[Domain Events]
    end
    
    subgraph "Lớp Infrastructure"
        DB[(PostgreSQL)]
        RR[RelationshipRepository]
        UBR[UserBlockRepository]
        UPR[UserProfileRepository]
        CTX[SocialServiceContext]
    end
    
    RC --> CMD
    RC --> Q
    BC --> CMD
    BC --> Q
    CMD --> B
    CMD --> RA
    CMD --> UBA
    Q --> RR
    Q --> UBR
    RR --> CTX --> DB
    UBR --> CTX
    UPR --> CTX
    RA --> DE
    UBA --> DE
    
    style RC fill:#4a90d9,stroke:#2d5986,color:#fff
    style BC fill:#4a90d9,stroke:#2d5986,color:#fff
    style RA fill:#50c878,stroke:#2d8659,color:#fff
    style UBA fill:#50c878,stroke:#2d8659,color:#fff
    style UPA fill:#50c878,stroke:#2d8659,color:#fff
    style DB fill:#ff6b6b,stroke:#c0392b,color:#fff

Trách Nhiệm Các Lớp

1. Lớp Domain (SocialService.Domain)

Trái tim của ứng dụng chứa business logic thuần túy.

Aggregates

Aggregate Mục Đích
Relationship Quản lý kết bạn (Friendship) và theo dõi (Following)
UserBlock Quản lý việc block users
UserProfile Cache thông tin user từ IAM Service

Domain Events

Event Trigger
FriendRequestSentDomainEvent Gửi yêu cầu kết bạn
FriendshipCreatedDomainEvent Chấp nhận kết bạn
UserFollowedDomainEvent Follow user
RelationshipStatusChangedDomainEvent Thay đổi trạng thái quan hệ
RelationshipRemovedDomainEvent Hủy kết bạn/bỏ theo dõi
UserBlockedDomainEvent Block user
UserUnblockedDomainEvent Unblock user

2. Lớp Infrastructure (SocialService.Infrastructure)

Triển khai kỹ thuật và truy cập dữ liệu.

Component Mục Đích
SocialServiceContext DbContext với Unit of Work pattern
RelationshipRepository CRUD cho Relationship aggregate
UserBlockRepository CRUD cho UserBlock aggregate
UserProfileRepository CRUD cho UserProfile aggregate
EntityConfigurations EF Core Fluent API mappings

3. Lớp API (SocialService.API)

Điểm vào ứng dụng và triển khai CQRS.

Component Mục Đích
RelationshipsController APIs cho kết bạn và theo dõi
BlocksController APIs cho block/unblock users
Commands 6 write operations (MediatR)
Queries 4 read operations
Behaviors Logging, Validation, Transaction

Luồng CQRS

sequenceDiagram
    participant Client
    participant Controller
    participant MediatR
    participant LoggingBehavior
    participant ValidatorBehavior
    participant TransactionBehavior
    participant Handler
    participant Repository
    participant DbContext
    
    Client->>Controller: HTTP Request
    Controller->>MediatR: Send(Command)
    MediatR->>LoggingBehavior: Handle
    LoggingBehavior->>ValidatorBehavior: Next()
    ValidatorBehavior->>TransactionBehavior: Next()
    TransactionBehavior->>Handler: Next()
    Handler->>Repository: Add/Update/Delete
    Repository->>DbContext: SaveEntitiesAsync()
    DbContext-->>Repository: Success + Dispatch Events
    Repository-->>Handler: Result
    Handler-->>Controller: Response
    Controller-->>Client: HTTP Response

Relationship State Machine

stateDiagram-v2
    [*] --> Pending: SendFriendRequest
    Pending --> Accepted: Accept()
    Pending --> Rejected: Reject()
    Pending --> Cancelled: Cancel()
    Accepted --> Cancelled: Remove()
    
    [*] --> Accepted: FollowUser (auto-accept)
    
    note right of Pending: Chỉ cho Friendship type
    note right of Accepted: Follow tự động Accepted

Schema Database

erDiagram
    relationships {
        uuid id PK
        uuid requester_id FK
        uuid addressee_id FK
        int type_id FK
        int status_id FK
        timestamp created_at
        timestamp updated_at
    }
    
    relationship_types {
        int id PK
        varchar(50) name
    }
    
    relationship_statuses {
        int id PK
        varchar(50) name
    }
    
    user_blocks {
        uuid id PK
        uuid blocker_id FK
        uuid blocked_id FK
        varchar(500) reason
        timestamp created_at
    }
    
    user_profiles {
        uuid id PK
        uuid user_id UK
        varchar(100) display_name
        varchar(500) avatar_url
        varchar(500) bio
        timestamp last_synced_at
        timestamp created_at
    }
    
    relationships ||--o| relationship_types : has_type
    relationships ||--o| relationship_statuses : has_status

Enumeration Values

RelationshipType:

ID Name
1 Friendship
2 Following

RelationshipStatus:

ID Name
1 Pending
2 Accepted
3 Rejected
4 Cancelled

Domain Events Flow

graph LR
    subgraph "Relationship Aggregate"
        R[Relationship] -->|Creates| E1[FriendRequestSentEvent]
        R -->|Accept| E2[FriendshipCreatedEvent]
        R -->|Follow| E3[UserFollowedEvent]
        R -->|Any Change| E4[StatusChangedEvent]
        R -->|Remove| E5[RemovedEvent]
    end
    
    subgraph "UserBlock Aggregate"
        UB[UserBlock] -->|Creates| E6[UserBlockedEvent]
    end
    
    subgraph "Event Handlers"
        E1 --> H1[Notification Handler]
        E2 --> H2[Notification Handler]
        E3 --> H3[Feed Handler]
        E6 --> H4[Cleanup Handler]
    end
    
    style R fill:#50c878,stroke:#2d8659,color:#fff
    style UB fill:#50c878,stroke:#2d8659,color:#fff

Health Checks

graph TD
    HC[Health Check Endpoint]
    HC --> |/health/live| L[Liveness]
    HC --> |/health/ready| R[Readiness]
    HC --> |/health| F[Full Status]
    
    R --> PG[(PostgreSQL)]
    R --> RD[(Redis)]
    
    style HC fill:#3498db,stroke:#2980b9,color:#fff
    style L fill:#2ecc71,stroke:#27ae60,color:#fff
    style R fill:#f39c12,stroke:#d68910,color:#fff

Kiến Trúc Deployment

Docker Compose (Local)

services:
  socialservice-api:
    build: .
    ports: ["5000:8080"]
    depends_on:
      - postgres
      - redis
  
  postgres:
    image: postgres:16-alpine
    
  redis:
    image: redis:7-alpine

Kubernetes (Production)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: socialservice-api
spec:
  replicas: 3
  template:
    spec:
      containers:
      - name: api
        image: socialservice:latest
        ports:
        - containerPort: 8080
        livenessProbe:
          httpGet:
            path: /health/live
            port: 8080
        readinessProbe:
          httpGet:
            path: /health/ready
            port: 8080

Cân Nhắc Bảo Mật

  1. Authentication: JWT Bearer token từ IAM Service
  2. Authorization: Kiểm tra ownership trong business logic
  3. Input Validation: FluentValidation trên tất cả requests
  4. Block Enforcement: Block một user sẽ ngăn mọi tương tác
  5. SQL Injection: EF Core parameterized queries

Tích Hợp Với Các Services Khác

graph LR
    SS[Social Service] <-->|Integration Events| EB[Event Bus]
    EB <--> IAM[IAM Service]
    EB <--> NS[Notification Service]
    EB <--> FS[Feed Service]
    
    IAM -->|UserCreated/Updated| SS
    SS -->|FriendshipCreated| NS
    SS -->|UserFollowed| FS
    
    style SS fill:#4a90d9,stroke:#2d5986,color:#fff
    style EB fill:#9b59b6,stroke:#7d3c98,color:#fff

Tối Ưu Hiệu Năng

  1. Connection Pooling: EF Core với Npgsql connection resilience
  2. Async/Await: Tất cả I/O operations đều async
  3. Pagination: Tất cả list queries hỗ trợ skip/take
  4. Indexes:
    • relationships: (requester_id, addressee_id, type_id)
    • user_blocks: (blocker_id, blocked_id)
    • user_profiles: (user_id) UNIQUE

Tài Liệu Tham Khảo