# Architecture

Detailed technical architecture of the FluxiQ PIX platform, covering the Elixir umbrella structure, service boundaries, data flow, and infrastructure components.

## Prerequisites

- Familiarity with Elixir/OTP supervision trees
- Understanding of microservice communication patterns
- Basic knowledge of ISO 20022 message standards

## Umbrella Architecture

FluxiQ PIX uses an Elixir umbrella project containing 4 OTP applications, each with a dedicated responsibility and port:

```mermaid
graph LR
    subgraph Umbrella [FluxiQ PIX Umbrella]
        SHARED[shared<br/>DB, Auth, Crypto, NATS]
        DICT[dict_service<br/>:4001]
        SPI[spi_service<br/>:4002]
        SETTLE[settlement_service<br/>:4003 API Gateway]
    end
    DICT --> SHARED
    SPI --> SHARED
    SETTLE --> SHARED
    SETTLE -->|HTTP proxy| DICT
    SETTLE -->|HTTP proxy| SPI
```

| Application | Port | Endpoints | Responsibility |
|-------------|------|-----------|----------------|
| `shared` | -- | -- | PostgreSQL schemas, Ecto Repo, JWT/MFA auth, ICP-Brasil crypto, NATS connection, Redis client, BACEN HTTP client |
| `dict_service` | 4001 | ~92 | DICT v2.10.0 API -- PIX key lifecycle (create, lookup, delete, claim, portability), CID sync |
| `spi_service` | 4002 | ~95 | SPI -- ISO 20022 message processing (pacs.008, pacs.002, pacs.004, pacs.028), inbound/outbound flows |
| `settlement_service` | 4003 | ~200 | API gateway, settlement cycles, netting, reconciliation, accounting, monitoring, admin API |

## Service Communication

### Internal (Synchronous)

Settlement Service acts as the API gateway and proxies requests to Dict and SPI services via HTTP:

```
Client --> Settlement(:4003) --HTTP--> Dict(:4001)
Client --> Settlement(:4003) --HTTP--> SPI(:4002)
```

The `SettlementService.InternalClient` module handles inter-service calls with:
- Circuit breaker (5 failures -> open, 30s cooldown)
- Distributed trace propagation (`x-trace-id` header)
- Finch connection pooling (DICT: 10x2=20 conns, default: 25x2=50 conns)

### External (Asynchronous)

NATS JetStream provides durable, at-least-once delivery for event-driven communication:

```mermaid
graph LR
    SPI -->|monetarie.spi.*| NATS[NATS JetStream]
    DICT -->|monetarie.dict.*| NATS
    SETTLE -->|monetarie.settlement.*| NATS
    NATS -->|monetarie.core.*| CORE[Core Banking]
    CORE -->|monetarie.core.pix.*| NATS
```

### 7 JetStream Streams

| Stream | Subjects | Retention | Purpose |
|--------|----------|-----------|---------|
| `MONETARIE_SPI` | `monetarie.spi.>` | 7 days | SPI transaction events |
| `MONETARIE_DICT` | `monetarie.dict.>` | 7 days | DICT key management events |
| `MONETARIE_SETTLEMENT` | `monetarie.settlement.>` | 7 days | Settlement/reconciliation events |
| `MONETARIE_AUDIT` | `monetarie.audit.>` | 90 days | Audit trail |
| `MONETARIE_DLQ` | `monetarie.dlq.>` | 90 days | Dead letter queue |
| `MONETARIE_CORE` | `monetarie.core.>` | 7 days | Core Banking integration events |

## Data Architecture

### PostgreSQL Schemas (8)

| Schema | Tables | Purpose |
|--------|--------|---------|
| `monetarie_auth` | Users, sessions, MFA, institutions, groups | Authentication and authorization |
| `monetarie_dict` | PIX keys, claims, MED 2.0, CID sync | DICT directory data |
| `monetarie_spi` | Messages, payments, accounts, balances | SPI transaction data |
| `monetarie_spi_ref` | Banks, status codes, message types | Reference/lookup data |
| `monetarie_spi_msg` | Crypto keys, XML messages | Cryptographic material |
| `monetarie_audit` | XML archive, BACEN validations | Audit and compliance |
| `monetarie_settlement` | Netting, reconciliation, QR codes, GL | Settlement and accounting |
| `bacen_simulator` | Config, scenarios, test runs | BACEN simulator data |

### Redis Usage

| Purpose | Key Pattern | TTL |
|---------|-------------|-----|
| Rate limiting | `rate_limit:{ip}:{path}` | 15 min |
| Token blacklist | `blacklist:{jti}` | Remaining JWT TTL |
| Idempotency | `idempotency:{user}:{key}` | 24 hours |
| Session cache | `session:{token}` | Configurable |

## Supervision Trees

Each OTP application has its own supervision tree with restart strategies tuned for resilience:

```mermaid
graph TD
    SHARED_APP[Shared.Application<br/>one_for_one, 10/60s]
    SHARED_APP --> PG[PostgrexSupervisor]
    SHARED_APP --> REPO[Shared.Repo]
    SHARED_APP --> FINCH[Finch]
    SHARED_APP --> TEL[Telemetry]
    SHARED_APP --> RED[Redis Connection<br/>10-conn pool]
    SHARED_APP --> CERT[CertificatePool<br/>5-min refresh]
    SHARED_APP --> CHAN[ChannelRouter<br/>health tracking]
    SHARED_APP --> ERR[ErrorLookup<br/>10-min ETS refresh]
    SHARED_APP --> NATS_SUP[NATS Supervisor<br/>conditional]
    SHARED_APP --> PART[PartitionManager<br/>daily check]
```

### Worker Processing Model

NATS workers use `BaseWorker` with configurable parallelism:

| Worker | Batch Size | Poll Interval | Max Concurrency |
|--------|-----------|---------------|-----------------|
| InboundProcessor | 100 | 200ms | 10 |
| OutboundSender | 100 | 200ms | 10 |
| StatusUpdater | 100 | 200ms | 10 |
| ReturnProcessor | 100 | 200ms | 5 |
| CoreEventProcessor | 50 | 500ms | 5 |

Workers feature adaptive backpressure: full batch -> 50ms poll, empty -> 2000ms poll.

## Security Architecture

```mermaid
graph TB
    CLIENT[Client] -->|HTTPS| LB[Load Balancer / Ingress]
    LB --> GW[Settlement :4003]

    subgraph Auth Pipeline
        GW --> CSRF[CSRF Check]
        CSRF --> JWT[JWT Verify<br/>HttpOnly Cookie]
        JWT --> BL[Token Blacklist<br/>Redis]
        BL --> RBAC[RequirePermission<br/>ETS-cached]
        RBAC --> RATE[Rate Limiter<br/>Redis Token Bucket]
        RATE --> IDEMP[Idempotency<br/>Redis]
    end

    subgraph BACEN mTLS
        DICT_S[Dict Service] -->|ICP-Brasil mTLS| BACEN[BACEN RSFN]
        SPI_S[SPI Service] -->|ICP-Brasil mTLS| BACEN
    end
```

Key security features:
- **Authentication**: RSA-OAEP encrypted login, HttpOnly JWT cookies, CSRF double-submit
- **MFA**: TOTP with backup codes
- **RBAC**: ETS-cached permission checks (5-min TTL) against `monetarie_auth.group_features`
- **Rate limiting**: Redis token bucket (10 login attempts per 15 min per IP)
- **Account lockout**: Automatic block after 10 failed login attempts
- **Token revocation**: Redis-backed JWT blacklist on logout
- **Idempotency**: Redis-backed `Idempotency-Key` header (24h TTL, SHA-256 body fingerprint)

## Expected Outcome

After reading this page, you should understand:

- How the 4 umbrella applications communicate
- The role of each PostgreSQL schema and NATS stream
- How the security pipeline processes requests
- The supervision and restart strategies used for resilience
