# Architecture Overview

STA Connector is an Elixir/Phoenix application that provides bidirectional file exchange with Brazil Central Bank's STA (Sistema de Transferencia de Arquivos) Web Services.

Current official `/staws` conformance and Core system-code mapping are documented in [STA Official Web Services And System Map](./sta-official-webservices-and-system-map.md).

## High-Level Architecture

```
                         ┌────────────────────────────────────────┐
                         │              BCB STA                   │
    │         Web Services REST              │
                         └───────────────┬────────────────────────┘
                                         │
                                         │ HTTPS
                                         │
                         ┌───────────────▼────────────────────────┐
                         │           STA Client                   │
                         │  • GenServer for connection pool       │
                         │  • Rate limiting (10/120)              │
                         │  • Retry with backoff                  │
                         │  • Circuit breaker                     │
                         └───────────────┬────────────────────────┘
                                         │
              ┌──────────────────────────┼──────────────────────────┐
              │                          │                          │
    ┌─────────▼─────────┐      ┌─────────▼─────────┐      ┌─────────▼─────────┐
    │    Inbound        │      │     State         │      │    Outbound       │
    │    Poller         │      │     Store         │      │    API            │
    │  • GenServer      │      │  • PostgreSQL     │      │  • Phoenix        │
    │  • Download       │      │  • Ecto schemas   │      │  • File upload    │
    │  • Route files    │      │  • Retry queue    │      │  • Status check   │
    └─────────┬─────────┘      └───────────────────┘      └─────────┬─────────┘
              │                                                      │
    ┌─────────▼─────────┐                                  ┌─────────▼─────────┐
    │    Router         │                                  │    Admin          │
    │  • Parse files    │                                  │    API            │
    │  • Deliver to     │                                  │  • Config         │
    │    FluxiQ STA     │                                  │  • Metrics        │
    └───────────────────┘                                  │  • Operations     │
                                                           └───────────────────┘
```

## Component Overview

| Component | Module | Description |
|-----------|--------|-------------|
| **Application** | `StaConnector.Application` | OTP application with supervision tree |
| **Config** | `StaConnector.Config` | Runtime configuration with hot-reload |
| **STA Client** | `StaConnector.Sta.Client` | GenServer-based REST client for BCB STA `/staws` |
| **Poller** | `StaConnector.Files.Poller` | GenServer for inbound file polling |
| **Router** | `StaConnector.Files.Router` | File routing to FluxiQ STA endpoints |
| **Parser Registry** | `StaConnector.Parsers` | BCB file format parsers |
| **State Store** | `StaConnector.Repo` | Ecto repository for PostgreSQL |
| **Outbound API** | `StaConnectorWeb.OutboundController` | Phoenix controller for file uploads |
| **Admin API** | `StaConnectorWeb.AdminController` | Management and monitoring endpoints |
| **Real-time** | `StaConnectorWeb.StatusChannel` | Phoenix Channels for live updates |

## Request Flows

### Inbound File Processing

```
┌──────────────────────────────────────────────────────────────────────────┐
│                        INBOUND FILE FLOW                                 │
└──────────────────────────────────────────────────────────────────────────┘

   Poller               STA Client            BCB STA              Repo
     │                      │                    │                    │
     │  query_available()   │                    │                    │
     │─────────────────────▶│                    │                    │
     │                      │   REST Request     │                    │
     │                      │───────────────────▶│                    │
     │                      │   File List        │                    │
     │                      │◀───────────────────│                    │
     │   {:ok, files}       │                    │                    │
     │◀─────────────────────│                    │                    │
     │                      │                    │                    │
     │   For each file:     │                    │                    │
     │   ═══════════════    │                    │                    │
     │                      │                    │                    │
     │  Files.processed?()  │                    │                    │
     │────────────────────────────────────────────────────────────────▶│
     │   false              │                    │                    │
     │◀────────────────────────────────────────────────────────────────│
     │                      │                    │                    │
     │  download_file()     │                    │                    │
     │─────────────────────▶│                    │                    │
     │                      │   REST Request     │                    │
     │                      │───────────────────▶│                    │
     │                      │   File Content     │                    │
     │                      │◀───────────────────│                    │
     │   {:ok, binary}      │                    │                    │
     │◀─────────────────────│                    │                    │
     │                      │                    │                    │
     │  Parse & Route       │                    │                    │
     │  (to FluxiQ STA)     │                    │                    │
     │                      │                    │                    │
     │  confirm_receipt()   │                    │                    │
     │─────────────────────▶│                    │                    │
     │                      │   REST Request     │                    │
     │                      │───────────────────▶│                    │
     │                      │   OK               │                    │
     │                      │◀───────────────────│                    │
     │   :ok                │                    │                    │
     │◀─────────────────────│                    │                    │
     │                      │                    │                    │
     │  Files.mark_processed()                   │                    │
     │────────────────────────────────────────────────────────────────▶│
     │   :ok                │                    │                    │
     │◀────────────────────────────────────────────────────────────────│
```

### Outbound File Upload

```
┌──────────────────────────────────────────────────────────────────────────┐
│                        OUTBOUND FILE FLOW                                │
└──────────────────────────────────────────────────────────────────────────┘

   Client               OutboundController    STA Client            BCB STA
     │                      │                    │                    │
     │  POST /api/v1/files  │                    │                    │
     │─────────────────────▶│                    │                    │
     │                      │   Validate params  │                    │
     │                      │   Decode Base64    │                    │
     │                      │                    │                    │
     │                      │  request_protocol()│                    │
     │                      │───────────────────▶│                    │
     │                      │                    │   REST Request     │
     │                      │                    │───────────────────▶│
     │                      │                    │   Protocol Number  │
     │                      │                    │◀───────────────────│
     │                      │   {:ok, protocol}  │                    │
     │                      │◀───────────────────│                    │
     │                      │                    │                    │
     │                      │  upload_file()     │                    │
     │                      │───────────────────▶│                    │
     │                      │                    │   REST Request     │
     │                      │                    │───────────────────▶│
     │                      │                    │   OK               │
     │                      │                    │◀───────────────────│
     │                      │   :ok              │                    │
     │                      │◀───────────────────│                    │
     │                      │                    │                    │
     │   201 Created        │                    │                    │
     │   {id, protocol}     │                    │                    │
     │◀─────────────────────│                    │                    │
```

## Directory Structure

```
sta-connector/
├── backend/
│   ├── lib/
│   │   ├── sta_connector/           # Business logic
│   │   │   ├── application.ex       # OTP Application & Supervision tree
│   │   │   ├── sta/                 # STA client
│   │   │   │   ├── client.ex        # GenServer REST client
│   │   │   │   ├── soap.ex          # Legacy SOAP request/response handling
│   │   │   │   ├── rate_limiter.ex  # Rate limiting GenServer
│   │   │   │   └── circuit_breaker.ex
│   │   │   ├── files/               # File processing
│   │   │   │   ├── poller.ex        # Polling GenServer
│   │   │   │   ├── processor.ex     # File processor
│   │   │   │   ├── router.ex        # Route matching
│   │   │   │   └── file.ex          # Ecto schema
│   │   │   ├── config/              # Configuration
│   │   │   │   ├── loader.ex        # Config loading
│   │   │   │   └── watcher.ex       # Hot-reload watcher
│   │   │   ├── parsers/             # BCB parsers
│   │   │   │   ├── registry.ex      # Parser registry
│   │   │   │   ├── ccs.ex           # CCS parser
│   │   │   │   ├── spi.ex           # SPI parser
│   │   │   │   ├── dict.ex          # DICT parser
│   │   │   │   └── ...
│   │   │   └── repo.ex              # Ecto Repo
│   │   └── sta_connector_web/
│   │       ├── channels/            # Phoenix Channels
│   │       │   ├── status_channel.ex
│   │       │   └── user_socket.ex
│   │       ├── controllers/         # REST API
│   │       │   ├── outbound_controller.ex
│   │       │   ├── admin_controller.ex
│   │       │   └── health_controller.ex
│   │       ├── router.ex            # Phoenix Router
│   │       └── endpoint.ex          # Phoenix Endpoint
│   ├── config/
│   │   ├── config.exs               # Base configuration
│   │   ├── dev.exs                  # Development config
│   │   ├── prod.exs                 # Production config
│   │   └── runtime.exs              # Runtime configuration
│   ├── priv/repo/migrations/        # Ecto migrations
│   └── test/                        # ExUnit tests
├── frontend/                        # Vue 3 + Vite
│   ├── src/
│   │   ├── components/
│   │   ├── views/
│   │   ├── stores/                  # Pinia stores
│   │   └── composables/
│   ├── vite.config.ts
│   └── package.json
├── docs/                            # VitePress documentation
└── homologation/                    # Test suite
```

## Technology Stack

| Layer | Technology | Purpose |
|-------|------------|---------|
| Language | Elixir 1.15+ / Erlang OTP 26+ | Backend implementation |
| Framework | Phoenix 1.7 | Web framework and real-time |
| Database | PostgreSQL 15 + Ecto | State persistence and queries |
| HTTP Client | Finch | Pooled HTTP connections to BCB |
| XML | SweetXml | Legacy SOAP request/response parsing |
| Frontend | Vue 3 + Vite | Admin portal SPA |
| Real-time | Phoenix Channels | Live updates via WebSocket |
| Styling | TailwindCSS | UI styling |
| Deployment | Docker | Containerization |

## Design Principles

### 1. Reliability via OTP

- **Supervision trees** - Processes are supervised and automatically restarted on failure
- **GenServers** - Stateful components (STA Client, Poller, Rate Limiter) use GenServer
- **Idempotent processing** - Files are tracked to prevent duplicate processing
- **State persistence** - All file states are persisted via Ecto to survive restarts
- **Graceful shutdown** - OTP handles graceful termination of supervised processes

### 2. BCB Compliance

- **Rate limiting** - GenServer enforces BCB limits (10 concurrent, 120/min)
- **Circuit breaker** - Prevents cascading failures to BCB
- **Protocol handling** - Follows BCB RSFN specifications
- **Receipt confirmation** - Confirms successful file receipt

### 3. Observability

- **Structured logging** - Logger with metadata and JSON formatting
- **Telemetry** - Phoenix.Telemetry for metrics collection
- **Health checks** - Liveness and readiness endpoints
- **Phoenix Channels** - Real-time status updates to admin portal

### 4. Security

- **Credential management** - Runtime configuration via environment variables
- **API authentication** - Plug-based authentication middleware
- **TLS** - HTTPS for all BCB communication via Finch
- **Non-root container** - Runs as unprivileged user

### 5. Operability

- **Configuration hot-reload** - Update settings without restart via Config.Watcher
- **Route management** - Enable/disable routes dynamically
- **Manual retry** - Retry failed files via Admin API
- **Docker-native** - Easy containerized deployment with releases

## Supported BCB Systems

| System | Code | Description | Direction |
|--------|------|-------------|-----------|
| CCS | `CCS` | Customer Consultation System | Inbound/Outbound |
| CIR | `CIR` | Credit Information Registry | Inbound |
| CMP | `CMP` | Means of Payment Control | Inbound |
| STR | `STR` | Reserve Transfer System | Inbound/Outbound |
| SPI | `SPI` | Instant Payment System (PIX) | Inbound/Outbound |
| CAM | `CAM` | Foreign Exchange System | Inbound |
| LDL | `LDL` | Deferred Settlement | Inbound |
| DICT | `DICT` | PIX Directory | Inbound/Outbound |

## Deployment Architecture

### Single Instance (Development)

```
┌─────────────────────────────────────────┐
│              Docker Host                │
│  ┌──────────────────────────────────┐   │
│  │       STA Connector (BEAM)       │   │
│  │  ┌────────┐  ┌────────────────┐  │   │
│  │  │Outbound│  │     Admin      │  │   │
│  │  │  API   │  │     API        │  │   │
│  │  │ :4000  │  │    :4000       │  │   │
│  │  └────────┘  └────────────────┘  │   │
│  │  ┌────────────────────────────┐  │   │
│  │  │    Phoenix Channels        │  │   │
│  │  └────────────────────────────┘  │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌──────────────────────────────────┐   │
│  │       PostgreSQL                 │   │
│  │          :5432                   │   │
│  └──────────────────────────────────┘   │
│                                         │
│  ┌──────────────────────────────────┐   │
│  │       Admin Portal (Vue)         │   │
│  │          :3000                   │   │
│  └──────────────────────────────────┘   │
└─────────────────────────────────────────┘
```

### Production (Multi-Instance)

```
                    ┌─────────────────┐
                    │  Load Balancer  │
                    └────────┬────────┘
                             │
         ┌───────────────────┼───────────────────┐
         │                   │                   │
   ┌─────▼─────┐       ┌─────▼─────┐       ┌─────▼─────┐
   │ Connector │       │ Connector │       │ Connector │
   │  Node 1   │       │  Node 2   │       │  Node 3   │
   │  (BEAM)   │       │  (BEAM)   │       │  (BEAM)   │
   └─────┬─────┘       └─────┬─────┘       └─────┬─────┘
         │                   │                   │
         └───────────────────┼───────────────────┘
                             │
                    ┌────────▼────────┐
                    │   PostgreSQL    │
                    │   (Primary)     │
                    └────────┬────────┘
                             │
                    ┌────────▼────────┐
                    │   PostgreSQL    │
                    │   (Replica)     │
                    └─────────────────┘
```

## Next Steps

- [Database Schema](/architecture/database) - Data model and persistence
- [API Reference](/api/) - REST API documentation
- [Configuration](/guide/configuration) - Configuration options
