# インフラ構成図

## 全体アーキテクチャ

```mermaid
flowchart TB
    subgraph Internet["Internet"]
        Client[Client Applications]
        AdminUser[Admin Users]
        Webhook[External Webhooks]
    end

    subgraph LoadBalancer["Load Balancer / CDN"]
        LB[Load Balancer<br/>TLS Termination]
        CDN[CDN<br/>Static Assets]
    end

    subgraph AppTier["Application Tier"]
        subgraph APIServers["API Servers"]
            API1[Medusa API Server 1<br/>Node.js 20+<br/>Express.js]
            API2[Medusa API Server N<br/>Node.js 20+<br/>Express.js]
        end
        subgraph Workers["Worker Servers"]
            Worker1[Medusa Worker 1<br/>Node.js 20+<br/>BullMQ]
            Worker2[Medusa Worker N<br/>Node.js 20+<br/>BullMQ]
        end
    end

    subgraph DataTier["Data Tier"]
        subgraph PostgreSQLCluster["PostgreSQL Cluster"]
            PGPrimary[(PostgreSQL Primary<br/>MikroORM)]
            PGReplica[(PostgreSQL Replica<br/>Read-only)]
        end
        subgraph RedisCluster["Redis Cluster"]
            RedisMain[(Redis<br/>Cache / EventBus / Workflow)]
        end
    end

    subgraph Storage["Storage Services"]
        S3[(S3 Compatible Storage<br/>Files / Media)]
    end

    subgraph External["External Services"]
        Stripe[Stripe API<br/>Payments]
        SendGrid[SendGrid API<br/>Notifications]
        OAuth[OAuth Providers<br/>GitHub / Google]
        PostHog[PostHog<br/>Analytics]
    end

    Client --> LB
    AdminUser --> LB
    Webhook --> LB

    LB --> API1
    LB --> API2
    LB --> CDN
    CDN --> AdminDashboard[Admin Dashboard<br/>React SPA]

    API1 --> PGPrimary
    API1 --> PGReplica
    API1 --> RedisMain
    API1 --> S3

    API2 --> PGPrimary
    API2 --> PGReplica
    API2 --> RedisMain
    API2 --> S3

    Worker1 --> PGPrimary
    Worker1 --> RedisMain
    Worker1 --> S3

    Worker2 --> PGPrimary
    Worker2 --> RedisMain
    Worker2 --> S3

    PGPrimary --> PGReplica

    API1 --> Stripe
    API1 --> SendGrid
    API1 --> OAuth
    API1 --> PostHog

    API2 --> Stripe
    API2 --> SendGrid
    API2 --> OAuth
    API2 --> PostHog

    Worker1 --> SendGrid
    Worker2 --> SendGrid
```

## コンポーネント詳細図

### API Server内部構造

```mermaid
flowchart TB
    subgraph APIServer["Medusa API Server"]
        subgraph HTTP["HTTP Layer"]
            Express[Express.js Server<br/>Port 9000]
            Middleware[Middlewares<br/>CORS / Auth / Compression]
            Router[API Router<br/>/admin /store /auth]
        end

        subgraph Core["Core Framework"]
            ConfigManager[Config Manager]
            Logger[Logger]
            Telemetry[OpenTelemetry<br/>Tracer]
        end

        subgraph Modules["Commerce Modules"]
            ProductMod[Product Module]
            OrderMod[Order Module]
            CartMod[Cart Module]
            PaymentMod[Payment Module]
            AuthMod[Auth Module]
            MoreMods[30+ Modules...]
        end

        subgraph Providers["Providers"]
            PaymentProviders[Payment Providers<br/>Stripe]
            AuthProviders[Auth Providers<br/>Email / OAuth]
            NotifProviders[Notification Providers<br/>SendGrid / Local]
            FileProviders[File Providers<br/>S3 / Local]
        end

        subgraph Workflows["Workflow Engine"]
            WorkflowSDK[Workflow SDK]
            CoreFlows[Core Flows]
            Orchestrator[Orchestrator]
        end
    end

    Express --> Middleware
    Middleware --> Router
    Router --> Modules
    Modules --> Providers
    Modules --> Workflows

    ConfigManager --> Express
    Logger --> Express
    Telemetry --> Express
```

### データフロー図

```mermaid
flowchart LR
    subgraph Client["Client Layer"]
        Storefront[Storefront App]
        AdminPanel[Admin Dashboard]
    end

    subgraph API["API Layer"]
        StoreAPI[Store API<br/>/store/*]
        AdminAPI[Admin API<br/>/admin/*]
        AuthAPI[Auth API<br/>/auth/*]
    end

    subgraph Services["Service Layer"]
        CoreFlows[Core Flows]
        ModuleServices[Module Services]
    end

    subgraph Data["Data Layer"]
        PostgreSQL[(PostgreSQL)]
        Redis[(Redis)]
        FileStorage[(File Storage)]
    end

    Storefront -->|REST API| StoreAPI
    AdminPanel -->|REST API| AdminAPI

    StoreAPI --> CoreFlows
    AdminAPI --> CoreFlows
    AuthAPI --> CoreFlows

    CoreFlows --> ModuleServices
    ModuleServices --> PostgreSQL
    ModuleServices --> Redis
    ModuleServices --> FileStorage
```

## Redis利用構成図

```mermaid
flowchart TB
    subgraph Application["Application"]
        API[API Server]
        Worker[Worker Server]
    end

    subgraph Redis["Redis Services"]
        subgraph Cache["Cache Module"]
            CacheRedis[cache-redis<br/>@medusajs/cache-redis]
            CacheInmem[cache-inmemory<br/>@medusajs/cache-inmemory]
        end

        subgraph EventBus["Event Bus Module"]
            EventRedis[event-bus-redis<br/>@medusajs/event-bus-redis<br/>BullMQ]
            EventLocal[event-bus-local<br/>@medusajs/event-bus-local]
        end

        subgraph WorkflowEngine["Workflow Engine"]
            WFRedis[workflow-engine-redis<br/>@medusajs/workflow-engine-redis]
            WFInmem[workflow-engine-inmemory<br/>@medusajs/workflow-engine-inmemory]
        end

        subgraph Locking["Distributed Locking"]
            LockRedis[locking-redis<br/>@medusajs/locking-redis]
            LockPG[locking-postgres<br/>@medusajs/locking-postgres]
        end

        subgraph Session["Session Store"]
            SessionRedis[connect-redis]
            SessionDynamo[connect-dynamodb]
        end
    end

    API --> CacheRedis
    API --> CacheInmem
    API --> EventRedis
    API --> EventLocal
    API --> WFRedis
    API --> WFInmem
    API --> LockRedis
    API --> LockPG
    API --> SessionRedis
    API --> SessionDynamo

    Worker --> EventRedis
    Worker --> EventLocal
    Worker --> WFRedis
    Worker --> WFInmem
```

## 認証フロー図

```mermaid
sequenceDiagram
    participant Client
    participant API as Medusa API
    participant Auth as Auth Module
    participant Provider as Auth Provider
    participant DB as PostgreSQL
    participant Session as Session Store

    Client->>API: POST /auth/user/emailpass
    API->>Auth: authenticate()
    Auth->>Provider: validate credentials
    Provider->>DB: query auth_identity
    DB-->>Provider: identity data
    Provider-->>Auth: validation result
    Auth->>Session: create session
    Auth-->>API: JWT token
    API-->>Client: { token }

    Note over Client,Session: Subsequent requests

    Client->>API: GET /admin/products<br/>Authorization: Bearer {token}
    API->>API: verify JWT
    API->>Session: validate session
    Session-->>API: session valid
    API->>DB: query products
    DB-->>API: products data
    API-->>Client: { products }
```

## ワークフロー実行図

```mermaid
sequenceDiagram
    participant API as API Server
    participant WF as Workflow Engine
    participant Redis
    participant DB as PostgreSQL
    participant External as External Services

    API->>WF: run workflow
    WF->>Redis: store workflow state

    loop Each Step
        WF->>WF: execute step
        WF->>DB: database operations
        WF->>External: external API calls
        WF->>Redis: update state
    end

    alt Success
        WF->>Redis: mark completed
        WF->>API: return result
    else Failure
        WF->>WF: run compensation
        WF->>Redis: rollback state
        WF->>API: return error
    end
```

## デプロイメント構成図（本番環境例）

```mermaid
flowchart TB
    subgraph AWS["AWS / Cloud Provider"]
        subgraph VPC["VPC"]
            subgraph PublicSubnet["Public Subnet"]
                ALB[Application Load Balancer<br/>TLS Termination]
            end

            subgraph PrivateSubnet["Private Subnet"]
                subgraph ECS["ECS / Kubernetes"]
                    APITask1[API Task 1]
                    APITask2[API Task 2]
                    WorkerTask1[Worker Task 1]
                    WorkerTask2[Worker Task 2]
                end

                subgraph RDS["Amazon RDS"]
                    PGPrimary[(PostgreSQL Primary)]
                    PGReplica[(PostgreSQL Replica)]
                end

                subgraph ElastiCache["Amazon ElastiCache"]
                    RedisCluster[(Redis Cluster)]
                end
            end
        end

        S3[(Amazon S3<br/>File Storage)]
        CloudFront[CloudFront<br/>CDN]
        SecretsManager[Secrets Manager]
        CloudWatch[CloudWatch<br/>Monitoring]
    end

    Internet[Internet] --> CloudFront
    Internet --> ALB

    CloudFront --> S3
    ALB --> APITask1
    ALB --> APITask2

    APITask1 --> PGPrimary
    APITask1 --> PGReplica
    APITask1 --> RedisCluster
    APITask1 --> S3

    APITask2 --> PGPrimary
    APITask2 --> PGReplica
    APITask2 --> RedisCluster
    APITask2 --> S3

    WorkerTask1 --> PGPrimary
    WorkerTask1 --> RedisCluster
    WorkerTask1 --> S3

    WorkerTask2 --> PGPrimary
    WorkerTask2 --> RedisCluster
    WorkerTask2 --> S3

    PGPrimary --> PGReplica

    APITask1 --> SecretsManager
    APITask2 --> SecretsManager
    WorkerTask1 --> SecretsManager
    WorkerTask2 --> SecretsManager

    APITask1 --> CloudWatch
    APITask2 --> CloudWatch
    WorkerTask1 --> CloudWatch
    WorkerTask2 --> CloudWatch
```

## モジュール依存関係図

```mermaid
flowchart TB
    subgraph Core["Core Framework"]
        Framework["@medusajs/framework"]
        Utils["@medusajs/utils"]
        Types["@medusajs/types"]
        WorkflowsSDK["@medusajs/workflows-sdk"]
        ModulesSDK["@medusajs/modules-sdk"]
        Orchestration["@medusajs/orchestration"]
    end

    subgraph CommerceModules["Commerce Modules"]
        Product["@medusajs/product"]
        Order["@medusajs/order"]
        Cart["@medusajs/cart"]
        Customer["@medusajs/customer"]
        Payment["@medusajs/payment"]
        Auth["@medusajs/auth"]
        Fulfillment["@medusajs/fulfillment"]
        Inventory["@medusajs/inventory"]
        Pricing["@medusajs/pricing"]
        Promotion["@medusajs/promotion"]
        Region["@medusajs/region"]
        Tax["@medusajs/tax"]
        Notification["@medusajs/notification"]
        File["@medusajs/file"]
    end

    subgraph Providers["Providers"]
        PaymentStripe["@medusajs/payment-stripe"]
        AuthEmailPass["@medusajs/auth-emailpass"]
        AuthGitHub["@medusajs/auth-github"]
        AuthGoogle["@medusajs/auth-google"]
        FileS3["@medusajs/file-s3"]
        FileLocal["@medusajs/file-local"]
        NotifSendGrid["@medusajs/notification-sendgrid"]
    end

    subgraph Infrastructure["Infrastructure Modules"]
        CacheRedis["@medusajs/cache-redis"]
        EventBusRedis["@medusajs/event-bus-redis"]
        WorkflowRedis["@medusajs/workflow-engine-redis"]
        LockingRedis["@medusajs/locking-redis"]
    end

    Framework --> Utils
    Framework --> Types
    Framework --> WorkflowsSDK
    Framework --> ModulesSDK
    Framework --> Orchestration

    Product --> Framework
    Order --> Framework
    Cart --> Framework
    Customer --> Framework
    Payment --> Framework
    Auth --> Framework
    Fulfillment --> Framework
    Inventory --> Framework
    Pricing --> Framework
    Promotion --> Framework
    Region --> Framework
    Tax --> Framework
    Notification --> Framework
    File --> Framework

    PaymentStripe --> Payment
    AuthEmailPass --> Auth
    AuthGitHub --> Auth
    AuthGoogle --> Auth
    FileS3 --> File
    FileLocal --> File
    NotifSendGrid --> Notification

    CacheRedis --> Framework
    EventBusRedis --> Framework
    WorkflowRedis --> Framework
    LockingRedis --> Framework
```
