# Overview

# Overview

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

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

- [README.md](README.md)
- [package.json](package.json)
- [src/index.ts](src/index.ts)

</details>



The `@primebrick/sdk` package provides shared microservice infrastructure for the Primebrick v3 ecosystem. Its primary goal is to standardize common cross-cutting concerns—such as configuration loading, database migrations, service registration, and lifecycle management—while remaining strictly decoupled from specific database drivers or business logic.

The SDK is built on the **Ports and Adapters** (Hexagonal) architecture pattern. By defining abstract interfaces (Ports) for external dependencies, the SDK allows consuming microservices to provide their own implementations (Adapters) using whatever Data Access Layer (DAL) or database technology they prefer.

### System Purpose & Core Philosophy

The SDK serves as the foundational backbone for microservices, ensuring that every service follows a consistent operational pattern:
*   **Zero Direct Dependencies:** The SDK has no mandatory runtime dependencies on database drivers or specific frameworks [package.json:33]().
*   **Dependency Inversion:** Consumers implement port interfaces to bridge the SDK with their chosen persistence layer [src/index.ts:4-5]().
*   **Graceful Resilience:** Built-in support for signal handling, parallel resource cleanup, and idempotent migrations [README.md:10-13]().
*   **Type Safety:** First-class TypeScript support with exported interfaces for all configuration and registry entities [src/index.ts:18-58]().

### High-Level Architecture

The following diagram illustrates how the SDK sits between the Microservice logic and external infrastructure through the use of Port interfaces.

**SDK Integration Pattern**
```mermaid
graph TD
    subgraph "Microservice (Consumer)"
        ServiceLogic["Service Logic"]
        Adapters["Adapters (Impl Ports)"]
    end

    subgraph "@primebrick/sdk"
        direction TB
        Ports["Port Interfaces"]
        Modules["Core Modules (Config, Migrations, etc.)"]
    end

    subgraph "External Infrastructure"
        DB[("Database (PostgreSQL, SQLite, etc.)")]
        NATS["NATS Broker"]
    end

    ServiceLogic --> Modules
    Modules -.-> Ports
    Adapters -- "Implements" --> Ports
    Adapters --> DB
    Modules -.-> NATS
```
*Sources: [src/index.ts:1-16](), [README.md:5-17]()*

### Module Map

The SDK is organized into several functional modules, each addressing a specific microservice requirement:

| Module | Primary Responsibility | Key Entities |
| :--- | :--- | :--- |
| **Ports** | Abstract contracts for external systems. | `ConfigRepositoryPort`, `DatabasePort`, `ServiceRegistryPort`, `HealthCheckPort` |
| **Config** | Database-backed configuration with in-memory caching. | `ConfigLoader`, `IConfigEntity` |
| **Migrations** | SHA256-based idempotent database patch runner. | `applyPatches`, `PATCH_REGISTRY_DDL` |
| **Service** | Service discovery and heartbeat management. | `ServiceRegistrar`, `IServiceRegistry` |
| **Lifecycle** | Signal handling and graceful shutdown orchestration. | `GracefulShutdown` |
| **HTTP** | Lightweight health check server. | `createHttpServer`, `HealthCheck` |
| **Env** | Centralized environment variable validation. | `validateEnv`, `requireEnv` |
| **NATS** | Singleton management for NATS messaging. | `NatsClient` |

*Sources: [src/index.ts:18-58](), [README.md:5-17]()*

### Integration Flow

When a microservice starts, it typically follows this integration sequence using the SDK:

1.  **Environment Validation**: Use `requireEnv` to ensure all necessary `process.env` variables are present [src/index.ts:57]().
2.  **Port Implementation**: The service creates classes or objects that satisfy the Port interfaces (e.g., a `DatabasePort` implementation using Drizzle or Prisma).
3.  **Bootstrap**:
    *   Initialize `ConfigLoader` to fetch runtime settings [src/index.ts:26]().
    *   Execute `applyPatches` to ensure the database schema is up to date [src/index.ts:40]().
    *   Register the service instance via `ServiceRegistrar` to start heartbeats [src/index.ts:44]().
4.  **Lifecycle Setup**: Install `GracefulShutdown` handlers to manage `SIGTERM` and `SIGINT` signals [src/index.ts:47]().

**Entity Mapping: Code to Infrastructure**
```mermaid
graph LR
    subgraph "Code Entities"
        SR["ServiceRegistrar"]
        CL["ConfigLoader"]
        MR["applyPatches"]
    end

    subgraph "Data Structures"
        ISR["IServiceRegistry (Table)"]
        ICE["IConfigEntity (Table)"]
        PRD["PATCH_REGISTRY_DDL"]
    end

    SR -- "updates" --> ISR
    CL -- "reads" --> ICE
    MR -- "creates/tracks" --> PRD
```
*Sources: [src/index.ts:25-44](), [src/migrations/patch-registry.ts:30-31]()*

### Next Steps

To dive deeper into specific areas of the SDK, refer to the following sections:

*   **[Getting Started](#1.1)**: A step-by-step guide on installing the package, handling the `nats` peer dependency, and wiring the SDK into a new service.
*   **[Architecture: Ports & Adapters](#1.2)**: A detailed look at the hexagonal design, the specific port contracts, and how to write custom adapters.
*   **[Core Modules](#2)**: Detailed documentation for each individual module (Config, Migrations, Lifecycle, etc.).

---
