# Giao Tiếp Giữa Các Services (Inter-Service Communication)

Inter-service communication patterns for GoodGo microservices including gRPC, GraphQL, service-to-service authentication, protocol selection, and client patterns. Use when implementing service-to-service calls, choosing communication protocols, or building service clients.
> Các patterns giao tiếp giữa services cho GoodGo microservices bao gồm gRPC, GraphQL, service-to-service authentication, lựa chọn protocol, và client patterns. Sử dụng khi implement service-to-service calls, chọn communication protocols, hoặc xây dựng service clients.

## Tổng Quan

Inter-service communication enables services to work together in a microservices architecture. GoodGo supports multiple protocols: HTTP/REST (current standard), gRPC (for high performance), and GraphQL (for flexible queries). This skill covers patterns for implementing resilient, secure, and performant inter-service communication.

Giao tiếp giữa các services cho phép các services làm việc cùng nhau trong kiến trúc microservices. GoodGo hỗ trợ nhiều protocols: HTTP/REST (chuẩn hiện tại), gRPC (cho hiệu suất cao), và GraphQL (cho queries linh hoạt). Skill này bao gồm các patterns để implement giao tiếp giữa services có khả năng phục hồi, bảo mật và hiệu suất cao.

## Khi Nào Sử Dụng

Use this skill when:
- Implementing service-to-service communication
- Choosing between REST, gRPC, or GraphQL protocols
- Setting up gRPC services and clients
- Implementing GraphQL services and resolvers
- Implementing service-to-service authentication
- Building resilient service clients with circuit breakers

Sử dụng skill này khi:
- Implement giao tiếp giữa các services
- Chọn giữa REST, gRPC, hoặc GraphQL protocols
- Setup gRPC services và clients
- Implement GraphQL services và resolvers
- Implement service-to-service authentication
- Xây dựng service clients có khả năng phục hồi với circuit breakers

## Khái Niệm Chính

### Các Lựa Chọn Protocol

**HTTP/REST:**
- Dễ đọc, dễ debug / Human-readable, easy to debug
- Tương thích browser / Browser-compatible
- Semantics HTTP chuẩn / Standard HTTP semantics
- JSON payloads
- Tốt cho external APIs / Good for external APIs

**gRPC:**
- Binary protocol (Protocol Buffers)
- Hiệu suất cao, độ trễ thấp / High performance, low latency
- Hỗ trợ streaming / Streaming support
- Strong typing với .proto files
- Dựa trên HTTP/2 / HTTP/2 based

**GraphQL:**
- Ngôn ngữ query linh hoạt / Flexible query language
- Single endpoint
- Client kiểm soát data fetching / Client-controlled data fetching
- Strong typing với schema

### Hướng Dẫn Lựa Chọn Protocol

Chọn protocol dựa trên use case, yêu cầu hiệu suất, chuyên môn team, và nhu cầu ecosystem.

Choose protocol based on use case, performance requirements, team expertise, and ecosystem needs.

#### Sơ Đồ Quyết Định Lựa Chọn Protocol / Protocol Selection Decision Tree

```mermaid
flowchart TD
    Start([Need Inter-Service Communication]) --> CheckExternal{External/Public API?}
    
    CheckExternal -->|Yes| UseREST[Use REST]
    CheckExternal -->|No| CheckPerformance{High Performance<br/>Required?}
    
    CheckPerformance -->|Yes| CheckStreaming{Need Streaming?}
    CheckPerformance -->|No| CheckFlexible{Need Flexible<br/>Queries?}
    
    CheckStreaming -->|Yes| UseGRPC[Use gRPC]
    CheckStreaming -->|No| CheckLowLatency{Ultra Low<br/>Latency?}
    
    CheckLowLatency -->|Yes| UseGRPC
    CheckLowLatency -->|No| UseREST
    
    CheckFlexible -->|Yes| UseGraphQL[Use GraphQL]
    CheckFlexible -->|No| UseREST
    
    UseREST --> RESTDesc["REST: External APIs<br/>Browser clients<br/>Simple CRUD"]
    UseGRPC --> GRPCDesc["gRPC: Internal services<br/>High performance<br/>Streaming support"]
    UseGraphQL --> GraphQLDesc["GraphQL: Complex queries<br/>Mobile apps<br/>Flexible data"]
    
    style UseREST fill:#e1f5ff
    style UseGRPC fill:#fff4e1
    style UseGraphQL fill:#e8f5e9
```

## Các Patterns Chính

### Luồng Gọi Service-to-Service / Service-to-Service Call Flow

Sơ đồ sau minh họa luồng hoàn chỉnh của service-to-service call, bao gồm authentication, interceptors, và error handling:

The following diagram illustrates the complete flow of a service-to-service call, including authentication, interceptors, and error handling:

```mermaid
sequenceDiagram
    participant ClientService as Client Service
    participant ClientLib as Service Client<br/>(HTTP/gRPC/GraphQL)
    participant Interceptor as Request<br/>Interceptor
    participant Auth as Auth<br/>Middleware
    participant TargetService as Target Service
    participant Logger as Logger
    participant Metrics as Metrics
    
    ClientService->>ClientLib: Make request
    ClientLib->>Interceptor: Add correlation ID<br/>Add service auth header<br/>Add request ID
    Interceptor->>Logger: Log request start
    Interceptor->>Metrics: Track request start
    Interceptor->>TargetService: HTTP/gRPC/GraphQL Request<br/>(with headers)
    
    TargetService->>Auth: Validate x-service-auth
    alt Invalid Auth
        Auth-->>TargetService: 403 Forbidden
        TargetService-->>ClientLib: Error Response
        ClientLib->>Logger: Log error
        ClientLib->>Metrics: Track failure
        ClientLib-->>ClientService: ServiceError
    else Valid Auth
        Auth->>TargetService: Authenticated
        TargetService->>TargetService: Process request
        TargetService-->>ClientLib: Success Response
        ClientLib->>Logger: Log success<br/>(with correlation ID)
        ClientLib->>Metrics: Track success<br/>(duration, status)
        ClientLib-->>ClientService: Response Data
    end
```

### HTTP/REST Service Client

```typescript
// EN: Service client với circuit breaker
// VI: Service client với circuit breaker
import { ServiceClient } from '../../core/clients/service-client';

const notificationClient = new ServiceClient({
  baseURL: process.env.NOTIFICATION_SERVICE_URL || 'http://notification-service:5003',
  serviceName: 'notification-service',
  timeout: 5000,
  enableCircuitBreaker: true,
});

// EN: Usage
// VI: Sử dụng
await notificationClient.post('/api/v1/notifications', {
  userId,
  message,
});
```

### gRPC Service

```typescript
// EN: gRPC server
// VI: gRPC server
import { UserGrpcServer } from './user.grpc.service';

const grpcServer = new UserGrpcServer(userService);
grpcServer.start(50051);

// EN: gRPC client
// VI: gRPC client
const userGrpcClient = new GrpcClient({
  protoPath: './proto/user_service.proto',
  packageName: 'goodgo.user.v1',
  serviceName: 'UserService',
  serverUrl: 'localhost:50051',
});

const user = await userGrpcClient.call('getUser', { user_id: '123' });
```

### GraphQL Service

```typescript
// EN: GraphQL client
// VI: GraphQL client
const userGraphQLClient = new GraphQLServiceClient({
  endpoint: 'http://user-service:5002/graphql',
});

const GET_USER_QUERY = `
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      email
      name
    }
  }
`;

const user = await userGraphQLClient.query(GET_USER_QUERY, { id: '123' });
```

### Service-to-Service Authentication

Luồng authentication đảm bảo giao tiếp an toàn giữa các services:

The authentication flow ensures secure communication between services:

```mermaid
sequenceDiagram
    participant ClientService as Client Service
    participant ServiceClient as Service Client
    participant Env as Environment<br/>Variables
    participant TargetService as Target Service
    participant AuthMiddleware as Auth<br/>Middleware
    
    ClientService->>ServiceClient: Create client instance
    ServiceClient->>Env: Read INTERNAL_API_KEY
    Env-->>ServiceClient: API Key
    
    ClientService->>ServiceClient: Make request
    ServiceClient->>ServiceClient: Auto-add x-service-auth<br/>header with API key
    
    ServiceClient->>TargetService: HTTP Request<br/>(x-service-auth: token)
    
    TargetService->>AuthMiddleware: Extract x-service-auth
    AuthMiddleware->>AuthMiddleware: Compare with<br/>INTERNAL_API_KEY
    
    alt Token Matches
        AuthMiddleware->>TargetService: Auth Success
        TargetService->>TargetService: Process request
        TargetService-->>ServiceClient: 200 OK + Data
    else Token Mismatch
        AuthMiddleware->>TargetService: Auth Failed
        TargetService-->>ServiceClient: 403 Forbidden<br/>(INVALID_SERVICE_AUTH)
        ServiceClient->>ServiceClient: Throw ServiceError
        ServiceClient-->>ClientService: Error Response
    end
```

#### Implementation / Triển Khai

```typescript
// EN: Internal auth middleware
// VI: Internal auth middleware
import { internalAuthMiddleware } from '../../middlewares/internal-auth.middleware';

router.use('/internal', internalAuthMiddleware);

// EN: Client tự động thêm auth header
// VI: Client automatically adds auth header
const client = new ServiceClient({
  baseURL: 'http://service:5000',
  serviceName: 'service',
});
// X-Service-Auth header được thêm tự động
```

## Best Practices / Thực Hành Tốt

### Protocol Selection / Lựa Chọn Protocol

- **REST**: External APIs, browser clients, simple CRUD / APIs ngoài, browser clients, CRUD đơn giản
- **gRPC**: Internal services, high performance, streaming / Services nội bộ, hiệu suất cao, streaming
- **GraphQL**: Complex queries, mobile apps, flexible data / Queries phức tạp, mobile apps, data linh hoạt

### Performance / Hiệu Suất

- Use connection pooling / Sử dụng connection pooling
- Enable HTTP keep-alive / Bật HTTP keep-alive
- Set appropriate timeouts / Thiết lập timeout phù hợp
- Implement circuit breakers / Implement circuit breakers

### Security / Bảo Mật

- Always authenticate internal calls / Luôn xác thực internal calls
- Use TLS/mTLS / Sử dụng TLS/mTLS
- Store secrets securely / Lưu secrets an toàn
- Implement rate limiting / Implement rate limiting

### Observability / Khả Năng Quan Sát

- Log with correlation IDs / Ghi log với correlation IDs
- Track metrics (duration, success rate) / Theo dõi metrics
- Add distributed tracing / Thêm distributed tracing
- Monitor service health / Giám sát sức khỏe service

## Testing / Kiểm Thử

```typescript
// EN: Mock service client
// VI: Mock service client
const mockClient = createMockServiceClient();
mockClient.get.mockResolvedValue({ id: '123' });
```

## Skills Liên Quan

- [Resilience Patterns](./resilience-patterns.md) - Circuit breaker, retry patterns / Circuit breaker, các patterns retry
- [Security](./security.md) - Authentication, authorization / Authentication, authorization
- [API Design](./api-design.md) - RESTful API patterns / RESTful API patterns
- [Project Rules](./project-rules.md) - GoodGo coding standards / Tiêu chuẩn coding GoodGo

## Tài Nguyên

- [gRPC Documentation](https://grpc.io/docs/) - Tài liệu gRPC chính thức
- [GraphQL Documentation](https://graphql.org/learn/) - Tài liệu GraphQL
- [Protocol Buffers](https://developers.google.com/protocol-buffers) - Hướng dẫn Protocol Buffers
- Skill Source: `.cursor/skills/inter-service-communication/SKILL.md` - Source file đầy đủ
