# EmailSender Microservice

# EmailSender Microservice

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

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

- [emailsender/Dockerfile](emailsender/Dockerfile)
- [emailsender/src/index.ts](emailsender/src/index.ts)

</details>



The **EmailSender** microservice is a dedicated utility within the Primebrick v3 architecture responsible for the asynchronous dispatch of transactional emails. It acts as an abstraction layer over external email providers (primarily Brevo), handling template rendering, delivery status tracking via webhooks, and communication logging.

## Service Role & Architecture

The microservice operates as a consumer in the system's event-driven architecture. It listens for requests over NATS, processes them using internal business logic, and exposes a lightweight HTTP server to receive delivery status updates (webhooks) from external providers.

### Component Interaction

The following diagram illustrates how the core classes and functions within the `emailsender` package interact during the service lifecycle and message processing.

**EmailSender Internal Flow**
```mermaid
graph TD
    subgraph "Entry Point [src/index.ts]"
        Main["main()"]
    end

    subgraph "Messaging [src/nats/]"
        NC["getNatsConnection()"]
        Sub["subscribeToEmailSendRequests()"]
    end

    subgraph "Business Logic [src/services/]"
        ES["EmailService.sendEmail()"]
        SR["ServiceRegistration"]
    end

    subgraph "External Integration"
        BC["BrevoClient (Provider)"]
        NATS["NATS JetStream"]
    end

    Main --> SR
    Main --> NC
    NC -.-> NATS
    Main --> Sub
    Sub --> ES
    ES --> BC
```
Sources: [emailsender/src/index.ts:1-65](), [emailsender/src/nats/handlers.ts:1-10]()

---

## Startup Sequence

The service initialization follows a strict sequence to ensure connectivity and registration before accepting workloads:

1.  **Service Registration**: The `ServiceRegistration` class attempts to upsert the service's metadata into a central registry and starts a heartbeat interval (default 60s) [emailsender/src/index.ts:15-26]().
2.  **NATS Connectivity**: Establishes a connection to the NATS cluster via `getNatsConnection()` [emailsender/src/index.ts:29-35]().
3.  **Subscription**: Invokes `subscribeToEmailSendRequests()`, which binds a handler to the `EmailService.sendEmail()` method to process incoming requests [emailsender/src/index.ts:38-40]().
4.  **HTTP Server**: Launches a Node.js server (default port 3003) to handle `/health` checks and incoming provider webhooks [emailsender/src/index.ts:43-44]().

Sources: [emailsender/src/index.ts:12-59]()

---

## Subsystems Overview

The EmailSender is composed of several specialized subsystems, each detailed in its own documentation page.

### [NATS Messaging Layer](#2.1)
The primary communication interface. It utilizes NATS JetStream for reliable message delivery. It defines the `SendEmailRequest` and `SendEmailResponse` schemas used across the microservice ecosystem.
*   **Key Entities**: `getNatsConnection`, `subscribeToEmailSendRequests`.
*   For details, see [NATS Messaging Layer](#2.1).

### [Email Services & Business Logic](#2.2)
Contains the core domain logic. This includes the `EmailService` for managing the lifecycle of an email (from template rendering to dispatch) and the `WebhookService` for processing delivery receipts.
*   **Key Entities**: `EmailService`, `WebhookService`, `ServiceRegistration`.
*   For details, see [Email Services & Business Logic](#2.2).

### [Brevo Email Provider](#2.3)
The infrastructure adapter for the Brevo (formerly Sendinblue) API. It translates internal email requests into provider-specific HTTP calls and maps provider-specific delivery statuses back to internal states.
*   **Key Entities**: `BrevoClient`.
*   For details, see [Brevo Email Provider](#2.3).

### [HTTP Server & Webhook Endpoint](#2.4)
A lightweight server implementation using the native `http` module. It provides a `/webhook` endpoint for external providers to POST status updates and a `/health` endpoint for orchestration health checks.
*   **Key Entities**: `createHttpServer`, `/webhook`, `/health`.
*   For details, see [HTTP Server & Webhook Endpoint](#2.4).

### [Deployment & Docker](#2.5)
The containerization strategy for the service. It uses a multi-stage `Dockerfile` to ensure small production images and defines the necessary environment variables (like `NATS_URL` and `BREVO_API_KEY`) for operation.
*   **Key Files**: `emailsender/Dockerfile`, `emailsender/package.json`.
*   For details, see [Deployment & Docker](#2.5).

---

## Graceful Shutdown

The service handles `SIGTERM` and `SIGINT` signals to ensure a clean exit. The shutdown sequence clears the heartbeat interval and closes the NATS connection to prevent message loss or stale registry entries [emailsender/src/index.ts:49-58]().

Sources: [emailsender/src/index.ts:49-58]()

---
