# Monetarie STA ↔ STA Connector Design

**Version:** 1.0
**Date:** 2026-01-31
**Status:** Approved

## 1. Overview

A Go service that bridges Monetarie STA with Brazil Central Bank's STA (Sistema de Transferência de Arquivos). The connector enables bidirectional file transfer with full parsing of RSFN file layouts.

### 1.1 Goals

- Receive files from BCB via STA, parse them, and route to Monetarie STA endpoints
- Accept files from Monetarie STA, build BCB format, and upload to STA
- Support all RSFN systems (CCS, CIR, CMP, STR, SPI, CAM, LDL, DICT)
- Full file parsing with transformation to/from JSON
- Easy deployment in any infrastructure
- Configurable via file, environment variables, and runtime API

### 1.2 Architecture

```
┌─────────────────┐     ┌──────────────────────────────────┐     ┌─────────────┐
│                 │     │      STA Connector Service       │     │             │
│   Monetarie STA    │────▶│                                  │────▶│   BCB STA   │
│                 │◀────│  ┌────────┐  ┌────────────────┐  │◀────│             │
└─────────────────┘     │  │ Parser │  │ File Router    │  │     └─────────────┘
                        │  │ Engine │  │ (CCS,CIR,etc)  │  │
                        │  └────────┘  └────────────────┘  │
                        │  ┌────────┐  ┌────────────────┐  │
                        │  │ Admin  │  │ Config Manager │  │
                        │  │  API   │  │                │  │
                        │  └────────┘  └────────────────┘  │
                        └──────────────────────────────────┘
```

## 2. Components

### 2.1 STA Client

Low-level BCB STA API wrapper implementing:
- HTTP Basic Authentication
- File upload (request protocol + upload content)
- File download with SHA-256 verification
- Query available/transferred files
- Status change operations
- Rate limiting (120 queries/min, 10 concurrent transfers)
- Retry with exponential backoff

**Endpoints:**
- Homologation: `https://sta-h.bcb.gov.br/staws`
- Production: `https://sta.bcb.gov.br/staws`

### 2.2 Poller

Scheduled service that:
- Queries STA for available files (`GET /staws/arquivos/disponiveis`)
- Downloads new files
- Triggers processing pipeline
- Tracks state to prevent reprocessing

### 2.3 Parser Engine

Pluggable parser system with:
- Parser interface for each system
- Registry for parser lookup by system/file type
- Bidirectional: Parse (file → JSON) and Build (JSON → file)

**Supported Systems:**
| System | Description |
|--------|-------------|
| CCS | Cadastro de Clientes do SFN |
| CIR | MECIR - Cash management |
| CMP | Câmara Interbancária de Pagamentos |
| STR | Sistema de Transferência de Reservas |
| SPI | Sistema de Pagamentos Instantâneos (PIX) |
| CAM | Câmbio (Foreign Exchange) |
| LDL | Liquidação Diferida |
| DICT | Diretório de Identificadores PIX |

### 2.4 Router

Routes parsed files to Monetarie STA endpoints:
- Configurable URL per system
- Circuit breaker per endpoint
- Retry with exponential backoff
- HTTP POST with JSON payload

### 2.5 Outbound API

REST API for Monetarie STA to send files:
- `POST /api/v1/files` - Submit file for upload to BCB
- `GET /api/v1/files/{id}/status` - Check upload status
- `GET /api/v1/health` - Health check

### 2.6 Admin API

Management API:
- `GET/PATCH /admin/config` - View/update configuration
- `GET /admin/metrics` - Operational metrics
- `POST /admin/poller/trigger` - Manual poll trigger
- `POST /admin/retry/{id}` - Retry failed file

### 2.7 State Store

Persistent storage for:
- Processed protocols (prevent duplicates)
- Pending uploads and their status
- Retry queue
- Runtime configuration overrides

Implementations: SQLite (default), PostgreSQL (production)

## 3. Data Flows

### 3.1 Inbound Flow (BCB → Monetarie STA)

1. Poller queries STA for available files
2. Download file content, verify SHA-256 hash
3. Identify system from file type (ACCS001 → CCS)
4. Parse file using appropriate parser → JSON
5. Route to configured Monetarie STA endpoint
6. Mark file as received in STA
7. Store protocol in state DB

### 3.2 Outbound Flow (Monetarie STA → BCB)

1. Monetarie STA POSTs to `/api/v1/files`
2. Builder transforms JSON to BCB file format
3. Calculate SHA-256 hash
4. Request protocol from STA
5. Upload file content
6. Return protocol number to Monetarie STA
7. Store in state DB for tracking

## 4. Configuration

### 4.1 Priority (highest to lowest)

1. Admin API runtime changes
2. Environment variables
3. Config file (config.yaml)
4. Defaults

### 4.2 Config File Structure

```yaml
service:
  name: "sta-connector"
  log_level: "info"

sta:
  environment: "homologation"
  username: "${STA_USERNAME}"
  password: "${STA_PASSWORD}"
  institution_code: "12345"
  timeout_seconds: 30

poller:
  enabled: true
  interval_seconds: 30
  systems: ["CCS", "CIR", "CMP", "STR", "SPI", "CAM", "LDL", "DICT"]

outbound_api:
  enabled: true
  port: 8080
  auth:
    type: "api_key"
    api_key: "${OUTBOUND_API_KEY}"

admin_api:
  enabled: true
  port: 8081

routes:
  CCS:
    url: "https://staapi-planner.monetarie.com.br/api/ccs"
    headers:
      Authorization: "Bearer ${MONETARIE_STA_TOKEN}"
  # ... other systems

state_store:
  type: "sqlite"
  sqlite:
    path: "./data/state.db"
```

## 5. Project Structure

```
monetarie-connector-stawebservice/
├── cmd/connector/main.go
├── internal/
│   ├── config/
│   ├── sta/
│   ├── poller/
│   ├── parser/
│   │   ├── registry.go
│   │   └── systems/{ccs,cir,cmp,str,spi,cam,ldl,dict}/
│   ├── router/
│   ├── api/{outbound,admin}/
│   └── store/
├── pkg/hash/
├── configs/
├── deployments/
├── docs/plans/
├── Claude.md
└── README.md
```

## 6. API Specifications

### 6.1 Outbound API

**POST /api/v1/files**
```json
Request:
{
  "system": "CCS",
  "file_type": "ACCS001",
  "destination": { "unit": "99999", "dependency": "0001" },
  "data": { }
}

Response (201):
{
  "id": "uuid",
  "protocol": "123456789",
  "status": "uploaded",
  "created_at": "2026-01-31T12:00:00Z"
}
```

**GET /api/v1/files/{id}/status**
```json
{
  "id": "uuid",
  "protocol": "123456789",
  "status": "accepted",
  "sta_state": { "code": 35, "description": "Arquivo aceito" }
}
```

### 6.2 Admin API

- `GET /admin/config` - Current configuration
- `PATCH /admin/config` - Update configuration
- `GET /admin/metrics` - Operational metrics
- `POST /admin/poller/trigger` - Trigger poll
- `POST /admin/retry/{id}` - Retry failed file

## 7. Parser Interface

```go
type Parser interface {
    System() string
    SupportedFileTypes() []string
    Parse(content []byte, fileType string) (*ParseResult, error)
    Build(data any, fileType string) ([]byte, error)
}

type ParseResult struct {
    System   string       `json:"system"`
    FileType string       `json:"file_type"`
    Data     any          `json:"data"`
    Metadata FileMetadata `json:"metadata"`
}
```

## 8. Implementation Phases

### Phase 1: Core Infrastructure
- Project setup, configuration system, state store, logging

### Phase 2: STA Client
- HTTP client, all STA operations, rate limiting, retry logic

### Phase 3: Inbound Pipeline
- Poller, download/verify, parser registry, router

### Phase 4: Outbound Pipeline
- REST API, file builder, upload to STA

### Phase 5: System Parsers
- CCS, CIR, CMP, STR, SPI, CAM, LDL, DICT parsers

### Phase 6: Admin & Operations
- Admin API, metrics, Docker, documentation

### Phase 7: Testing & Hardening
- Unit tests, integration tests, security review

## 9. References

- [STA Web Services Manual v1.5](../Manual_STA_Web_Services.pdf)
- [BCB RSFN File Layouts](https://www.bcb.gov.br/estabilidadefinanceira/leiautearquivosrsfn)
- [BCB Digital Certificates](https://www.bcb.gov.br/estabilidadefinanceira/certificacaodigital)
