# Architecture Details

In-depth technical reference for the FluxiQ PIX architecture, covering supervision trees, process lifecycle, and internal communication patterns.

## Prerequisites

- Strong understanding of Elixir/OTP concepts
- Familiarity with GenServer, Supervisor, and Application patterns
- Knowledge of the [Architecture overview](../guide/architecture.md)

## Application Startup Sequence

```mermaid
sequenceDiagram
    participant OS
    participant BEAM
    participant Shared
    participant Dict
    participant SPI
    participant Settlement

    OS->>BEAM: Start release
    BEAM->>Shared: Application.start/2
    Shared->>Shared: PostgrexSupervisor, Repo, Finch, Redis, CertificatePool, ChannelRouter, ErrorLookup, PartitionManager
    Shared->>Shared: NATS Supervisor (if NATS_ENABLED)
    Shared->>Shared: Simulator GenServer (if SIMULATOR_ENABLED)
    BEAM->>Dict: Application.start/2
    Dict->>Dict: Endpoint :4001, CidSyncService, NatsPublisher
    BEAM->>SPI: Application.start/2
    SPI->>SPI: Endpoint :4002, Workers Supervisor
    BEAM->>Settlement: Application.start/2
    Settlement->>Settlement: Endpoint :4003, Workers Supervisor, Broadcaster, HealthChecker, QueueMonitor
```

## Supervision Trees (Detailed)

### Shared.Application

```
Shared.Application (one_for_one, max_restarts: 10/60s)
├── Shared.PostgrexSupervisor
├── Shared.Repo
├── {Finch, name: Shared.Finch}
│   ├── DICT pool (10 x 2 = 20 connections)
│   └── Default pool (25 x 2 = 50 connections)
├── Shared.Telemetry
├── Shared.Redis.Connection (10-conn pool, 5s timeout)
├── Shared.Crypto.CertificatePool (5-min refresh)
├── Shared.Bacen.ChannelRouter (health tracking)
├── Shared.Bacen.ErrorLookup (10-min ETS refresh)
├── Shared.Nats.Supervisor (conditional: NATS_ENABLED=true)
├── Shared.Bacen.Simulator (conditional: SIMULATOR_ENABLED=true)
└── Shared.Audit.PartitionManager (daily check + purge)
```

### SpiService.Application

```
SpiService.Application (rest_for_one, max_restarts: 10/60s)
├── SpiServiceWeb.Endpoint (:4002)
└── SpiService.Workers.Supervisor (conditional: NATS_ENABLED=true, max_restarts: 10/60s)
    ├── InboundProcessor (batch: 100, concurrency: 10)
    ├── OutboundSender (batch: 100, concurrency: 10)
    ├── ReturnProcessor (batch: 100, concurrency: 5)
    └── StatusUpdater (batch: 100, concurrency: 10)
```

### SettlementService.Application

```
SettlementService.Application (rest_for_one, max_restarts: 10/60s)
├── SettlementServiceWeb.Endpoint (:4003)
├── SettlementService.Workers.Supervisor (conditional: NATS_ENABLED=true, max_restarts: 10/60s)
│   ├── Scheduler (LIMIT 500K, 30s timeout)
│   ├── FileImporter
│   └── CoreEventProcessor (batch: 50, concurrency: 5, HTTP retry: 3x backoff)
├── SettlementService.Monitoring.Broadcaster (PubSub events)
├── SettlementService.Monitoring.HealthChecker (10s/30s checks)
└── SettlementService.Monitoring.QueueMonitor (15s NATS lag)
```

## ETS Tables

| Table | Module | Purpose | Options |
|-------|--------|---------|---------|
| `:circuit_breaker_state` | CircuitBreaker | Circuit breaker state | `write_concurrency: true` |
| `:rbac_cache` | RequirePermission | Permission cache (5-min TTL) | `read_concurrency: true` |
| `:error_lookup` | ErrorLookup | BACEN error codes (10-min TTL) | `read_concurrency: true` |

## Request Pipeline (Settlement)

```
Client Request
  → Plug.SSL (redirect HTTP to HTTPS)
  → Plug.RequestId (assign request ID)
  → TraceContext (generate/extract x-trace-id)
  → Plug.Parsers (JSON body parsing)
  → Router
    → :gateway pipeline
      → CSRF verification
      → JWTAuth (cookie extraction, blacklist check)
      → RequirePermission (ETS-cached RBAC)
    → :idempotent pipeline (POST /payments, /transactions)
      → Idempotency plug (Redis SET NX)
    → Controller
      → InternalClient (circuit breaker + trace propagation)
      → Repo (Ecto queries)
      → NATS publish (if applicable)
  → Response (JSON with camelCase serialization)
```

## Circuit Breaker State Machine

```mermaid
stateDiagram-v2
    [*] --> Closed
    Closed --> Open: 5 failures
    Open --> HalfOpen: 30s cooldown
    HalfOpen --> Closed: Probe success
    HalfOpen --> Open: Probe failure
```

- Uses atomic `:ets.update_counter/4` for thread-safe failure counting
- Only 5xx and transport errors trip the breaker
- Single probe request in half-open state

## Finch Connection Pools

| Destination | Pool Size | Count | Total |
|-------------|-----------|-------|-------|
| DICT Service | 10 | 2 | 20 |
| Default | 25 | 2 | 50 |

## BaseWorker Lifecycle

```mermaid
stateDiagram-v2
    [*] --> Init: start_link
    Init --> CheckNATS: init/1
    CheckNATS --> Idle: NATS disabled
    CheckNATS --> Subscribe: NATS enabled
    Subscribe --> Poll: Consumer created
    Poll --> Process: Messages available
    Process --> ACK: Success
    Process --> NAK: Transient error
    Process --> DLQ: Max retries exceeded
    ACK --> Poll: Next batch
    NAK --> Poll: Retry later
    DLQ --> Poll: Discard message
```

## Expected Outcome

After reading this reference:

- Complete understanding of the application startup sequence
- Detailed knowledge of supervision trees and restart strategies
- Understanding of ETS tables and their consistency models
- Request pipeline from ingress to response
- Circuit breaker and worker lifecycle state machines
