# HTTP Server & Webhook Endpoint

# HTTP Server & Webhook Endpoint

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [emailsender/src/server/http-server.ts](emailsender/src/server/http-server.ts)

</details>



The `EmailSender` microservice includes a lightweight HTTP server built using the native Node.js `http` module. This server serves two primary purposes: providing a health check mechanism for container orchestration (e.g., Docker, Kubernetes) and exposing a public webhook endpoint to receive delivery status notifications from external email providers like Brevo.

### Server Implementation

The server is initialized via the `createHttpServer` function, which defaults to listening on port `3003` [emailsender/src/server/http-server.ts:11-11](). It avoids heavy framework dependencies like Express, opting for a direct implementation using `createServer` [emailsender/src/server/http-server.ts:12-12]().

#### Endpoint Overview

| Path | Method | Purpose | Authentication |
| :--- | :--- | :--- | :--- |
| `/health` | `GET` | Service liveness check | None |
| `/webhook` | `POST` | Inbound provider events | API Key (Bearer/ApiKey) |

**Sources:**
- [emailsender/src/server/http-server.ts:11-64]()

---

### Webhook Endpoint (`/webhook`)

The `/webhook` endpoint is the entry point for asynchronous updates from email providers. It identifies the source provider via a URL query parameter and routes the payload to the internal business logic.

#### Authentication Logic
The server enforces security by comparing the `Authorization` header against the `WEBHOOK_API_KEY` environment variable [emailsender/src/server/http-server.ts:5-9](). It supports both `Bearer` and `ApiKey` prefix formats [emailsender/src/server/http-server.ts:18-25]().

#### Request Processing Flow
1.  **URL Parsing**: The server extracts the `provider` from the search parameters (defaulting to `"brevo"`) [emailsender/src/server/http-server.ts:28-28]().
2.  **Stream Consumption**: The request body is collected into `Buffer` chunks and parsed as JSON [emailsender/src/server/http-server.ts:31-36]().
3.  **Service Delegation**: The parsed payload and provider ID are passed to the `WebhookService.handleWebhook` method [emailsender/src/server/http-server.ts:38-38]().

#### Data Flow: External Event to WebhookService
The following diagram illustrates how an external HTTP request is transformed into a call to the internal service layer.

**Webhook Request Handling Flow**
```mermaid
sequenceDiagram
    participant P as "External Provider (e.g. Brevo)"
    participant S as "http.createServer (IncomingMessage)"
    participant H as "createHttpServer Logic"
    participant W as "WebhookService"

    P->>S: POST /webhook?provider=brevo
    Note over S: Headers: Authorization: Bearer <key>
    S->>H: Request Stream
    H->>H: Validate WEBHOOK_API_KEY
    alt Invalid Key
        H->>P: 401 Unauthorized
    else Valid Key
        H->>H: Buffer.concat(chunks)
        H->>H: JSON.parse(body)
        H->>W: handleWebhook("brevo", payload)
        W-->>H: Promise<void>
        H->>P: 200 OK
    end
```

**Sources:**
- [emailsender/src/server/http-server.ts:12-48]()
- [emailsender/src/services/webhook-service.ts:4-4]() (Reference to `WebhookService`)

---

### Health Check Endpoint (`/health`)

The `/health` endpoint provides a simple JSON response to indicate that the microservice process is running and the HTTP event loop is responsive.

*   **Response Body**: `{"status": "healthy"}` [emailsender/src/server/http-server.ts:53-53]()
*   **Content Type**: `application/json` [emailsender/src/server/http-server.ts:52-52]()

This endpoint is critical for the Docker `HEALTHCHECK` directive and orchestration readiness probes.

**Sources:**
- [emailsender/src/server/http-server.ts:51-55]()

---

### Integration and Data Mapping

The HTTP server acts as a bridge between the "External Network Space" and the "Internal Service Space." It maps raw HTTP primitives (Methods, Headers, Streams) to typed service calls.

**Entity Mapping: HTTP to Code**
```mermaid
graph TD
    subgraph "External Network Space"
        R["HTTP POST /webhook"]
        A["Authorization Header"]
        Q["?provider=brevo"]
        B["JSON Body"]
    end

    subgraph "Code Entity Space (emailsender/src/server/http-server.ts)"
        F["createHttpServer"]
        K["webhookApiKey (Env Var)"]
        WS["WebhookService.handleWebhook"]
    end

    R --> F
    A -- "Extracted & Compared" --> K
    Q -- "provider string" --> WS
    B -- "parsed payload object" --> WS
```

**Sources:**
- [emailsender/src/server/http-server.ts:1-64]()
- [emailsender/src/services/webhook-service.ts:1-10]()

---

### Error Handling & Reliability

*   **Startup Validation**: If `WEBHOOK_API_KEY` is missing from the environment variables, the server will throw an error and prevent the microservice from starting [emailsender/src/server/http-server.ts:7-9]().
*   **Request Safety**: The webhook handler is wrapped in a `try/catch` block. Any failure during body parsing or service execution results in a `500 Internal Server Error` response to the provider, preventing the server process from crashing [emailsender/src/server/http-server.ts:42-46]().
*   **Default Routing**: Any request that does not match `/webhook` or `/health` receives a `404 Not Found` response [emailsender/src/server/http-server.ts:57-58]().

**Sources:**
- [emailsender/src/server/http-server.ts:7-9]()
- [emailsender/src/server/http-server.ts:42-48]()
- [emailsender/src/server/http-server.ts:57-59]()

---
