# アーキテクチャ構成図

## システム全体構成図

```mermaid
graph TB
    subgraph "External Clients"
        STOREFRONT[Store Frontend<br/>React/Next.js]
        ADMIN_UI[Admin Dashboard<br/>React + Vite]
        MOBILE[Mobile Apps]
        EXTERNAL_SYS[External Systems]
    end

    subgraph "Medusa Backend"
        subgraph "HTTP Layer"
            EXPRESS[Express Server]
            subgraph "API Routes"
                STORE_API["/store/*<br/>Store API"]
                ADMIN_API["/admin/*<br/>Admin API"]
                AUTH_API["/auth/*<br/>Auth API"]
            end
        end

        subgraph "Middleware Stack"
            CORS[CORS]
            BODY[Body Parser]
            AUTH_MW[Authentication<br/>Session/JWT/API Key]
            CONTEXT[Context Setup]
            ERROR[Error Handler]
        end

        subgraph "Application Layer"
            WORKFLOWS[Workflows<br/>@medusajs/core-flows]
            STEPS[Workflow Steps]
            ORCHESTRATION[Orchestration Engine]
        end

        subgraph "Domain Layer - Modules"
            subgraph "Commerce Modules"
                PRODUCT[Product]
                ORDER[Order]
                CART[Cart]
                CUSTOMER[Customer]
                PAYMENT[Payment]
                FULFILLMENT[Fulfillment]
                PROMOTION[Promotion]
                PRICING[Pricing]
                INVENTORY[Inventory]
            end
            subgraph "Platform Modules"
                AUTH[Auth]
                USER[User]
                API_KEY[API Key]
                RBAC[RBAC]
                NOTIFICATION[Notification]
                FILE[File]
            end
            subgraph "Supporting Modules"
                REGION[Region]
                TAX[Tax]
                CURRENCY[Currency]
                SETTINGS[Settings]
                TRANSLATION[Translation]
            end
        end

        subgraph "Infrastructure Layer"
            subgraph "Data Access"
                REPOS[Repositories<br/>MikroORM]
            end
            subgraph "Event System"
                EVENT_BUS[Event Bus<br/>Local/Redis]
                SUBSCRIBERS[Subscribers]
            end
            subgraph "Providers"
                AUTH_PROVIDERS[Auth Providers<br/>Email/Google/GitHub]
                PAYMENT_PROVIDERS[Payment Providers<br/>Stripe]
                NOTIFICATION_PROVIDERS[Notification Providers<br/>SendGrid]
                FILE_PROVIDERS[File Providers<br/>Local/S3]
            end
        end
    end

    subgraph "External Services"
        POSTGRES[(PostgreSQL<br/>Primary Database)]
        REDIS[(Redis<br/>Cache/Events/Workflows)]
        S3[(AWS S3<br/>File Storage)]
        STRIPE_SVC[Stripe API]
        SENDGRID_SVC[SendGrid API]
        OAUTH_PROVIDERS[OAuth Providers<br/>Google/GitHub]
    end

    STOREFRONT --> STORE_API
    ADMIN_UI --> ADMIN_API
    MOBILE --> STORE_API
    EXTERNAL_SYS --> ADMIN_API

    EXPRESS --> CORS --> BODY --> AUTH_MW --> CONTEXT --> STORE_API & ADMIN_API & AUTH_API
    STORE_API & ADMIN_API --> WORKFLOWS
    AUTH_API --> AUTH

    WORKFLOWS --> STEPS
    STEPS --> ORCHESTRATION
    ORCHESTRATION --> PRODUCT & ORDER & CART & CUSTOMER & PAYMENT & FULFILLMENT & PROMOTION & PRICING & INVENTORY
    ORCHESTRATION --> AUTH & USER & API_KEY & RBAC & NOTIFICATION & FILE
    ORCHESTRATION --> REGION & TAX & CURRENCY & SETTINGS & TRANSLATION

    PRODUCT & ORDER & CART --> REPOS
    CUSTOMER & PAYMENT & FULFILLMENT --> REPOS
    REPOS --> POSTGRES

    PRODUCT & ORDER --> EVENT_BUS
    EVENT_BUS --> SUBSCRIBERS
    EVENT_BUS --> REDIS

    AUTH --> AUTH_PROVIDERS
    AUTH_PROVIDERS --> OAUTH_PROVIDERS
    PAYMENT --> PAYMENT_PROVIDERS
    PAYMENT_PROVIDERS --> STRIPE_SVC
    NOTIFICATION --> NOTIFICATION_PROVIDERS
    NOTIFICATION_PROVIDERS --> SENDGRID_SVC
    FILE --> FILE_PROVIDERS
    FILE_PROVIDERS --> S3

    ERROR --> EXPRESS
```

## レイヤー構成図

```mermaid
graph TB
    subgraph "Presentation Layer"
        direction LR
        HTTP[HTTP Routes<br/>packages/medusa/src/api/]
        MW[Middlewares<br/>packages/core/framework/src/http/middlewares/]
    end

    subgraph "Application Layer"
        direction LR
        WF[Workflows<br/>packages/core/core-flows/]
        WF_SDK[Workflows SDK<br/>packages/core/workflows-sdk/]
    end

    subgraph "Domain Layer"
        direction LR
        MOD_SVC[Module Services<br/>packages/modules/*/src/services/]
        MODELS[Entity Models<br/>packages/modules/*/src/models/]
    end

    subgraph "Infrastructure Layer"
        direction LR
        REPO[Repositories<br/>packages/modules/*/src/repositories/]
        PROV[Providers<br/>packages/modules/providers/*/]
        EB[Event Bus<br/>packages/modules/event-bus-*/]
    end

    HTTP --> MW
    MW --> WF
    WF --> WF_SDK
    WF_SDK --> MOD_SVC
    MOD_SVC --> MODELS
    MOD_SVC --> REPO
    MOD_SVC --> PROV
    MOD_SVC --> EB
```

## モジュール構成図

```mermaid
graph TB
    subgraph "Core Packages"
        FW[framework<br/>@medusajs/framework]
        TYPES[types<br/>@medusajs/types]
        UTILS[utils<br/>@medusajs/utils]
        WF_SDK[workflows-sdk<br/>@medusajs/workflows-sdk]
        CF[core-flows<br/>@medusajs/core-flows]
        MOD_SDK[modules-sdk<br/>@medusajs/modules-sdk]
        ORCH[orchestration<br/>@medusajs/orchestration]
    end

    subgraph "Commerce Modules"
        PROD[product]
        ORD[order]
        CART[cart]
        CUST[customer]
        PAY[payment]
        FULFILL[fulfillment]
        PROMO[promotion]
        PRICE[pricing]
        INV[inventory]
        STOCK[stock-location]
    end

    subgraph "Platform Modules"
        AUTH[auth]
        USR[user]
        AK[api-key]
        RBAC[rbac]
        NOTIF[notification]
        FL[file]
        TRANS[translation]
    end

    subgraph "Infrastructure Modules"
        EB_LOCAL[event-bus-local]
        EB_REDIS[event-bus-redis]
        CACHE_MEM[cache-inmemory]
        CACHE_REDIS[cache-redis]
        WF_MEM[workflow-engine-inmemory]
        WF_REDIS[workflow-engine-redis]
        LOCK[locking]
    end

    subgraph "Providers"
        AUTH_EP[auth-emailpass]
        AUTH_G[auth-google]
        AUTH_GH[auth-github]
        PAY_STRIPE[payment-stripe]
        NOTIF_SG[notification-sendgrid]
        FILE_S3[file-s3]
        FILE_LOCAL[file-local]
    end

    subgraph "Main Package"
        MEDUSA[@medusajs/medusa]
    end

    subgraph "Admin"
        DASH[dashboard]
        ADMIN_SDK[admin-sdk]
    end

    FW --> TYPES
    FW --> UTILS
    FW --> WF_SDK
    FW --> MOD_SDK
    FW --> ORCH

    CF --> WF_SDK
    CF --> TYPES

    MEDUSA --> FW
    MEDUSA --> CF
    MEDUSA --> PROD & ORD & CART & CUST & PAY & FULFILL & PROMO & PRICE & INV & STOCK
    MEDUSA --> AUTH & USR & AK & RBAC & NOTIF & FL & TRANS
    MEDUSA --> EB_LOCAL & EB_REDIS
    MEDUSA --> CACHE_MEM & CACHE_REDIS
    MEDUSA --> WF_MEM & WF_REDIS
    MEDUSA --> AUTH_EP & AUTH_G & AUTH_GH
    MEDUSA --> PAY_STRIPE
    MEDUSA --> NOTIF_SG
    MEDUSA --> FILE_S3 & FILE_LOCAL

    DASH --> ADMIN_SDK
```

## リクエスト処理フロー

```mermaid
sequenceDiagram
    participant C as Client
    participant E as Express Server
    participant M as Middleware Stack
    participant R as Route Handler
    participant W as Workflow
    participant S as Workflow Step
    participant MS as Module Service
    participant DB as PostgreSQL

    C->>E: HTTP Request
    E->>M: Process Request

    Note over M: CORS Check
    Note over M: Body Parser
    Note over M: Authentication
    Note over M: Context Setup

    M->>R: Authenticated Request
    R->>W: Execute Workflow

    loop For each step
        W->>S: Execute Step
        S->>MS: Call Module Service
        MS->>DB: Database Operation
        DB-->>MS: Result
        MS-->>S: Operation Result
        S-->>W: Step Response
    end

    W-->>R: Workflow Response
    R-->>E: JSON Response
    E-->>C: HTTP Response
```

## ワークフロー補償パターン

```mermaid
sequenceDiagram
    participant W as Workflow
    participant S1 as Step 1
    participant S2 as Step 2
    participant S3 as Step 3
    participant C1 as Compensation 1
    participant C2 as Compensation 2

    W->>S1: Execute Step 1
    S1-->>W: Success (with compensation data)

    W->>S2: Execute Step 2
    S2-->>W: Success (with compensation data)

    W->>S3: Execute Step 3
    S3-->>W: Error!

    Note over W: Start Compensation

    W->>C2: Compensate Step 2
    C2-->>W: Compensation Complete

    W->>C1: Compensate Step 1
    C1-->>W: Compensation Complete

    Note over W: Workflow Failed with Rollback
```

## イベント駆動フロー

```mermaid
sequenceDiagram
    participant MS as Module Service
    participant EM as Event Emitter
    participant EB as Event Bus
    participant SUB as Subscriber
    participant NS as Notification Service
    participant EXT as External Service

    MS->>MS: Execute Business Logic
    MS->>EM: @EmitEvents decorator
    EM->>EB: Publish Event

    alt Local Event Bus
        EB->>SUB: Synchronous Call
    else Redis Event Bus
        EB->>EB: Queue to BullMQ
        EB->>SUB: Async Processing
    end

    SUB->>NS: Process Event
    NS->>EXT: Send Notification
    EXT-->>NS: Confirmation
    NS-->>SUB: Complete
```

## 依存性注入構成

```mermaid
graph TB
    subgraph "Awilix Container"
        CONTAINER[MedusaContainer]
    end

    subgraph "Registration Keys"
        LOGGER[LOGGER]
        PG_CONN[PG_CONNECTION]
        CONFIG[CONFIG_MODULE]
        QUERY[QUERY]
    end

    subgraph "Module Services"
        ORDER_SVC[IOrderModuleService]
        PRODUCT_SVC[IProductModuleService]
        CART_SVC[ICartModuleService]
        CUSTOMER_SVC[ICustomerModuleService]
    end

    subgraph "Providers"
        AUTH_PROV[Auth Provider]
        PAYMENT_PROV[Payment Provider]
        NOTIFICATION_PROV[Notification Provider]
    end

    CONTAINER --> LOGGER
    CONTAINER --> PG_CONN
    CONTAINER --> CONFIG
    CONTAINER --> QUERY

    CONTAINER --> ORDER_SVC
    CONTAINER --> PRODUCT_SVC
    CONTAINER --> CART_SVC
    CONTAINER --> CUSTOMER_SVC

    CONTAINER --> AUTH_PROV
    CONTAINER --> PAYMENT_PROV
    CONTAINER --> NOTIFICATION_PROV
```

## 認証フロー

```mermaid
flowchart TB
    subgraph "Authentication Methods"
        SESSION[Session Auth]
        BEARER[Bearer JWT]
        API_KEY[API Key]
    end

    subgraph "Actor Types"
        USER[User<br/>Admin]
        CUSTOMER[Customer<br/>Store]
    end

    REQUEST[HTTP Request] --> AUTH_MW{Authentication<br/>Middleware}

    AUTH_MW --> |Check Session| SESSION
    AUTH_MW --> |Check Authorization Header| BEARER
    AUTH_MW --> |Check x-medusa-access-token| API_KEY

    SESSION --> |Extract auth_context| VERIFY{Verify<br/>Actor Type}
    BEARER --> |Verify JWT| VERIFY
    API_KEY --> |Validate Key| VERIFY

    VERIFY --> |user| USER
    VERIFY --> |customer| CUSTOMER

    USER --> ADMIN_ACCESS[Admin API Access]
    CUSTOMER --> STORE_ACCESS[Store API Access]

    ADMIN_ACCESS --> RBAC_CHECK{RBAC<br/>Permission Check}
    RBAC_CHECK --> |Allowed| EXECUTE[Execute Request]
    RBAC_CHECK --> |Denied| FORBIDDEN[403 Forbidden]
```

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

```mermaid
graph TB
    subgraph "Load Balancer"
        LB[Application Load Balancer]
    end

    subgraph "Application Tier"
        APP1[Medusa Instance 1]
        APP2[Medusa Instance 2]
        APP3[Medusa Instance N]
    end

    subgraph "Data Tier"
        PG_PRIMARY[(PostgreSQL Primary)]
        PG_REPLICA[(PostgreSQL Replica)]
        REDIS_CLUSTER[Redis Cluster<br/>Cache + Events + Workflows]
    end

    subgraph "Storage"
        S3[AWS S3<br/>File Storage]
        CDN[CloudFront CDN]
    end

    subgraph "External Services"
        STRIPE[Stripe]
        SENDGRID[SendGrid]
    end

    LB --> APP1 & APP2 & APP3

    APP1 & APP2 & APP3 --> PG_PRIMARY
    PG_PRIMARY --> PG_REPLICA

    APP1 & APP2 & APP3 --> REDIS_CLUSTER

    APP1 & APP2 & APP3 --> S3
    S3 --> CDN

    APP1 & APP2 & APP3 --> STRIPE
    APP1 & APP2 & APP3 --> SENDGRID
```
