# Troubleshooting

This guide covers common issues and their solutions when running STA Connector.

## Quick Diagnostics

### Health Check

```bash
# Outbound API health
curl http://localhost:8080/api/v1/health

# Admin API health
curl -u admin:password http://localhost:8081/admin/health

# Phoenix health check (Elixir)
curl http://localhost:4000/api/health
```

### View Logs

```bash
# Docker
docker logs sta-connector -f

# Kubernetes
kubectl logs -f deployment/sta-connector -n sta-connector

# Binary
./sta-connector --config config.yaml 2>&1 | tee connector.log

# Phoenix/Elixir
mix phx.server 2>&1 | tee phoenix.log
# Or with IEx
iex -S mix phx.server
```

### Check Metrics

```bash
curl -u admin:password http://localhost:8081/admin/metrics
```

---

## Startup Issues

### Configuration File Not Found

**Symptom:**
```
Error: config file not found: /app/configs/config.yaml
```

**Solution:**
1. Verify the config file path:
   ```bash
   ls -la /app/configs/config.yaml
   ```
2. Check volume mounts (Docker):
   ```yaml
   volumes:
     - ./config.yaml:/app/configs/config.yaml:ro
   ```
3. Verify config path argument:
   ```bash
   ./sta-connector --config /correct/path/config.yaml
   ```

### Invalid Configuration

**Symptom:**
```
Error: config validation failed: STA username cannot be empty
```

**Solution:**
1. Check environment variables are set:
   ```bash
   echo $STA_USERNAME
   ```
2. Verify `.env` file is loaded (Docker):
   ```bash
   docker-compose config
   ```
3. Check variable syntax in config:
   ```yaml
   sta:
     username: "${STA_USERNAME}"  # Must use quotes
   ```

### Database Connection Failed

**Symptom:**
```
Error: failed to open database: unable to open database file
```

**Solution:**
1. Ensure data directory exists:
   ```bash
   mkdir -p ./data
   chmod 755 ./data
   ```
2. Check file permissions:
   ```bash
   ls -la ./data/state.db
   ```
3. For Docker, check volume:
   ```bash
   docker volume inspect deployments_connector-data
   ```

### Port Already in Use

**Symptom:**
```
Error: listen tcp :8080: bind: address already in use
```

**Solution:**
1. Find the process using the port:
   ```bash
   lsof -i :8080
   ```
2. Kill the process or use different port:
   ```yaml
   outbound_api:
     port: 8082  # Different port
   ```

---

## Phoenix Startup Issues (Elixir)

### Port 4000 Already in Use

**Symptom:**
```
** (RuntimeError) could not start ranch listener :http, :eaddrinuse
```

**Solution:**
1. Find the process using port 4000:
   ```bash
   lsof -i :4000
   # Or on Linux
   ss -tlnp | grep 4000
   ```
2. Kill the process:
   ```bash
   kill -9 <PID>
   ```
3. Or change Phoenix port in `config/dev.exs`:
   ```elixir
   config :sta_connector, StaConnectorWeb.Endpoint,
     http: [port: 4001]
   ```
4. Or set via environment variable:
   ```bash
   PORT=4001 mix phx.server
   ```

### SECRET_KEY_BASE Missing

**Symptom:**
```
** (ArgumentError) secret_key_base is not configured
```

**Solution:**
1. Generate a new secret:
   ```bash
   mix phx.gen.secret
   ```
2. Set in environment:
   ```bash
   export SECRET_KEY_BASE="generated_secret_here"
   ```
3. Or in `config/runtime.exs`:
   ```elixir
   config :sta_connector, StaConnectorWeb.Endpoint,
     secret_key_base: System.fetch_env!("SECRET_KEY_BASE")
   ```
4. For development, check `config/dev.exs` has a secret configured

### Missing Dependencies

**Symptom:**
```
** (Mix) Could not find hex, which is needed to build dependency :phoenix
```

**Solution:**
1. Install Hex and Rebar:
   ```bash
   mix local.hex --force
   mix local.rebar --force
   ```
2. Fetch dependencies:
   ```bash
   mix deps.get
   ```
3. Compile:
   ```bash
   mix compile
   ```

### Erlang/Elixir Version Mismatch

**Symptom:**
```
** (RuntimeError) Elixir requires Erlang/OTP 24 or later
```

**Solution:**
1. Check versions:
   ```bash
   elixir --version
   erl -version
   ```
2. Use asdf or kerl to manage versions:
   ```bash
   asdf install erlang 26.0
   asdf install elixir 1.15.0-otp-26
   asdf local erlang 26.0
   asdf local elixir 1.15.0-otp-26
   ```

---

## Ecto/PostgreSQL Issues (Elixir)

### Database Connection Refused

**Symptom:**
```
** (DBConnection.ConnectionError) tcp connect (localhost:5432): connection refused
```

**Solution:**
1. Verify PostgreSQL is running:
   ```bash
   # macOS
   brew services list | grep postgresql

   # Linux
   systemctl status postgresql

   # Docker
   docker ps | grep postgres
   ```
2. Check connection settings in `config/dev.exs`:
   ```elixir
   config :sta_connector, StaConnector.Repo,
     username: "postgres",
     password: "postgres",
     hostname: "localhost",
     port: 5432,
     database: "sta_connector_dev"
   ```
3. Test connection manually:
   ```bash
   psql -h localhost -U postgres -d sta_connector_dev
   ```

### Migration Errors

**Symptom:**
```
** (Postgrex.Error) ERROR 42P01 (undefined_table) relation "files" does not exist
```

**Solution:**
1. Run pending migrations:
   ```bash
   mix ecto.migrate
   ```
2. Check migration status:
   ```bash
   mix ecto.migrations
   ```
3. Reset database (development only):
   ```bash
   mix ecto.reset
   ```
4. If migration is stuck, check `schema_migrations` table:
   ```sql
   SELECT * FROM schema_migrations ORDER BY version DESC LIMIT 10;
   ```

### Migration Conflict

**Symptom:**
```
** (Ecto.MigrationError) migration 20260131000001 is already up
```

**Solution:**
1. Rollback the conflicting migration:
   ```bash
   mix ecto.rollback --step 1
   ```
2. Fix the migration file
3. Re-run migrations:
   ```bash
   mix ecto.migrate
   ```

### Database Does Not Exist

**Symptom:**
```
** (Postgrex.Error) FATAL 3D000 (invalid_catalog_name) database "sta_connector_dev" does not exist
```

**Solution:**
1. Create the database:
   ```bash
   mix ecto.create
   ```
2. Or manually:
   ```bash
   createdb -h localhost -U postgres sta_connector_dev
   ```

### Repo Not Started

**Symptom:**
```
** (RuntimeError) could not lookup Ecto repo StaConnector.Repo because it was not started
```

**Solution:**
1. Ensure Repo is in your application supervision tree in `lib/sta_connector/application.ex`:
   ```elixir
   children = [
     StaConnector.Repo,
     StaConnectorWeb.Endpoint,
     # other children...
   ]
   ```
2. Check `config/config.exs` has Ecto repos configured:
   ```elixir
   config :sta_connector,
     ecto_repos: [StaConnector.Repo]
   ```

---

## Phoenix Channels / WebSocket Issues

### WebSocket Connection Failed

**Symptom:**
```
WebSocket connection to 'ws://localhost:4000/socket/websocket' failed
```

**Solution:**
1. Verify endpoint configuration in `lib/sta_connector_web/endpoint.ex`:
   ```elixir
   socket "/socket", StaConnectorWeb.UserSocket,
     websocket: true,
     longpoll: false
   ```
2. Check CORS settings for cross-origin requests:
   ```elixir
   socket "/socket", StaConnectorWeb.UserSocket,
     websocket: [check_origin: ["//localhost:3000"]]
   ```
3. For production, ensure WebSocket is allowed through load balancer/proxy

### Channel Join Failed

**Symptom:**
```javascript
// Client-side error
{reason: "unmatched topic"}
```

**Solution:**
1. Verify channel is registered in `user_socket.ex`:
   ```elixir
   channel "sta:*", StaConnectorWeb.StaChannel
   ```
2. Check topic pattern matches:
   ```elixir
   # In StaChannel
   def join("sta:" <> system_id, _params, socket) do
     {:ok, socket}
   end
   ```
3. Debug in IEx:
   ```elixir
   iex> StaConnectorWeb.Endpoint.config(:pubsub_server)
   ```

### Channel Timeout

**Symptom:**
```
** (exit) exited in: GenServer.call(#PID<0.123.0>, {:push, ...}, 5000)
    ** (EXIT) time out
```

**Solution:**
1. Increase channel timeout:
   ```elixir
   socket "/socket", StaConnectorWeb.UserSocket,
     websocket: [timeout: 45_000]
   ```
2. Handle long operations asynchronously:
   ```elixir
   def handle_in("heavy_operation", params, socket) do
     Task.start(fn -> perform_heavy_operation(params, socket) end)
     {:noreply, socket}
   end
   ```

### PubSub Issues

**Symptom:**
```
** (ArgumentError) no pubsub configured for StaConnectorWeb.Endpoint
```

**Solution:**
1. Ensure PubSub is configured in `config/config.exs`:
   ```elixir
   config :sta_connector, StaConnectorWeb.Endpoint,
     pubsub_server: StaConnector.PubSub
   ```
2. Add PubSub to supervision tree:
   ```elixir
   children = [
     {Phoenix.PubSub, name: StaConnector.PubSub},
     # ...
   ]
   ```

---

## STA Connection Issues

### Authentication Failed

**Symptom:**
```
Error: STA authentication failed: invalid credentials
```

**Solution:**
1. Verify Sisbacen credentials are correct
2. Check for typos in username/password
3. Ensure no special characters need escaping
4. Test credentials with BCB directly

### Connection Timeout

**Symptom:**
```
Error: STA request timeout: context deadline exceeded
```

**Solution:**
1. Check network connectivity:
   ```bash
   curl -I https://sta-h.bcb.gov.br/staws
   ```
2. Verify firewall allows HTTPS outbound
3. Increase timeout:
   ```yaml
   sta:
     timeout_seconds: 60
   ```
4. Check BCB status page for outages

### Certificate Error

**Symptom:**
```
Error: x509: certificate signed by unknown authority
```

**Solution:**
1. Ensure CA certificates are installed:
   ```bash
   # Alpine
   apk add ca-certificates

   # Ubuntu
   apt-get install ca-certificates
   ```
2. Update CA certificates:
   ```bash
   update-ca-certificates
   ```

### Rate Limited

**Symptom:**
```
Error: STA rate limit exceeded (429)
```

**Solution:**
1. Reduce polling frequency:
   ```yaml
   poller:
     interval_seconds: 60  # Increase from 30
     batch_size: 5         # Reduce from 10
   ```
2. Wait for rate limit window to reset (1 minute)
3. Monitor rate limit in metrics:
   ```bash
   curl -u admin:password http://localhost:8081/admin/metrics | jq '.sta_client.rate_limit_remaining'
   ```

---

## Finch HTTP Client Issues (Elixir)

### Finch Pool Not Started

**Symptom:**
```
** (ArgumentError) unknown registry: StaConnector.Finch
```

**Solution:**
1. Ensure Finch is in your supervision tree:
   ```elixir
   children = [
     {Finch, name: StaConnector.Finch},
     # ...
   ]
   ```
2. Verify the name matches your request calls:
   ```elixir
   Finch.build(:get, url)
   |> Finch.request(StaConnector.Finch)
   ```

### SSL/TLS Connection Error

**Symptom:**
```
** (Mint.TransportError) {:tls_alert, {:handshake_failure, ...}}
```

**Solution:**
1. Configure SSL options in Finch:
   ```elixir
   {Finch,
    name: StaConnector.Finch,
    pools: %{
      "https://sta-h.bcb.gov.br" => [
        conn_opts: [
          transport_opts: [
            cacertfile: CAStore.file_path(),
            verify: :verify_peer,
            depth: 3
          ]
        ]
      ]
    }}
   ```
2. For development/testing (not recommended for production):
   ```elixir
   transport_opts: [verify: :verify_none]
   ```

### Connection Pool Exhausted

**Symptom:**
```
** (Finch.Error) connection pool exhausted
```

**Solution:**
1. Increase pool size:
   ```elixir
   {Finch,
    name: StaConnector.Finch,
    pools: %{
      default: [size: 50, count: 4]
    }}
   ```
2. Reduce concurrent requests
3. Add connection timeout handling:
   ```elixir
   Finch.request(req, StaConnector.Finch, receive_timeout: 30_000)
   ```

### Request Timeout

**Symptom:**
```
** (Finch.Error) request timeout
```

**Solution:**
1. Increase timeout in request:
   ```elixir
   Finch.build(:post, url, headers, body)
   |> Finch.request(StaConnector.Finch, receive_timeout: 60_000)
   ```
2. For streaming responses:
   ```elixir
   Finch.stream(req, StaConnector.Finch, acc, fun, receive_timeout: 120_000)
   ```

---

## Common Elixir Errors

### GenServer Timeout

**Symptom:**
```
** (exit) exited in: GenServer.call(#PID<0.456.0>, :some_call, 5000)
    ** (EXIT) time out
```

**Solution:**
1. Increase call timeout:
   ```elixir
   GenServer.call(pid, :some_call, 30_000)
   ```
2. Use cast for fire-and-forget operations:
   ```elixir
   GenServer.cast(pid, :some_async_operation)
   ```
3. Investigate why the GenServer is slow:
   ```elixir
   :sys.get_state(pid)
   :sys.get_status(pid)
   ```
4. Check for blocking operations in handle_call

### Supervision Tree Restart Loop

**Symptom:**
```
[error] GenServer StaConnector.Worker terminating
** (RuntimeError) some error
...
[error] Child StaConnector.Worker of Supervisor StaConnector.Supervisor terminated
** Restarting
```

**Solution:**
1. Check supervisor strategy:
   ```elixir
   Supervisor.init(children, strategy: :one_for_one, max_restarts: 3, max_seconds: 5)
   ```
2. Add error handling in the child process
3. Use `:transient` restart for expected exits:
   ```elixir
   {StaConnector.Worker, restart: :transient}
   ```
4. Debug with Observer:
   ```elixir
   :observer.start()
   ```

### Process Mailbox Overflow

**Symptom:**
```
[warning] Process #PID<0.789.0> has a large mailbox: 100000 messages
```

**Solution:**
1. Check for slow message processing
2. Add flow control or back-pressure:
   ```elixir
   def handle_info(:process_batch, state) do
     {batch, remaining} = Enum.split(state.queue, 100)
     process_batch(batch)
     if remaining != [], do: send(self(), :process_batch)
     {:noreply, %{state | queue: remaining}}
   end
   ```
3. Use GenStage for producer-consumer patterns

### ETS Table Does Not Exist

**Symptom:**
```
** (ArgumentError) argument error
    (stdlib) :ets.lookup(:my_table, "key")
```

**Solution:**
1. Ensure ETS table is created before use:
   ```elixir
   def init(_) do
     :ets.new(:my_table, [:named_table, :public, read_concurrency: true])
     {:ok, %{}}
   end
   ```
2. Check if the process owning the table crashed
3. Create table in application start for global tables

### Module Not Found

**Symptom:**
```
** (UndefinedFunctionError) function StaConnector.SomeModule.function/1 is undefined
    (module StaConnector.SomeModule is not available)
```

**Solution:**
1. Recompile the project:
   ```bash
   mix compile --force
   ```
2. Check module name matches file path
3. Ensure file is not in `.gitignore` or excluded from compilation

---

## Elixir Debugging Commands

### Observer - Visual Process Inspector

```elixir
# Start the graphical observer
:observer.start()

# Shows:
# - System information (memory, CPU, processes)
# - Application supervision trees
# - Process list with message queue sizes
# - ETS tables
# - Trace processes
```

### Inspecting Process State

```elixir
# Get the state of a GenServer
:sys.get_state(pid)
:sys.get_state(StaConnector.Worker)

# Get full status including ancestors
:sys.get_status(pid)

# Trace a process (see all messages)
:sys.trace(pid, true)
# ... observe output ...
:sys.trace(pid, false)

# Statistics
:sys.statistics(pid, true)
# ... run some operations ...
:sys.statistics(pid, :get)
```

### Logger Configuration

```elixir
# Change log level at runtime
Logger.configure(level: :debug)

# Add metadata to logs
Logger.metadata(request_id: "abc123")

# Log with metadata
require Logger
Logger.info("Processing file", file_id: 123, system: "CCS")

# Configure in config/config.exs
config :logger, :console,
  format: "$time $metadata[$level] $message\n",
  metadata: [:request_id, :file_id, :system]
```

### Process Information

```elixir
# List all processes
Process.list()

# Get info about a process
Process.info(pid)
Process.info(pid, :message_queue_len)
Process.info(pid, :current_stacktrace)

# Find registered processes
Process.registered()
Process.whereis(:some_name)

# Find processes by name pattern
for {name, pid, _, _} <- Supervisor.which_children(StaConnector.Supervisor) do
  {name, pid}
end
```

### Remote Debugging

```elixir
# Connect to a running node
iex --sname debug --remsh sta_connector@hostname

# Or attach to a running release
./bin/sta_connector remote

# Debug in production (use with caution)
:debugger.start()
:int.ni(StaConnector.SomeModule)
:int.break(StaConnector.SomeModule, 42)  # line 42
```

### Memory and Performance

```elixir
# Memory usage
:erlang.memory()
:erlang.memory(:total)
:erlang.memory(:processes)

# Process memory
Process.info(pid, :memory)

# Recon library (add {:recon, "~> 2.5"} to deps)
:recon.proc_count(:memory, 10)  # Top 10 by memory
:recon.proc_count(:message_queue_len, 10)  # Top 10 by mailbox size
:recon.bin_leak(10)  # Find binary memory leaks

# Scheduler utilization
:scheduler.utilization(1000)  # Sample for 1 second
```

---

## File Processing Issues

### Files Not Being Discovered

**Symptom:** Poller runs but no files are found.

**Solution:**
1. Verify poller is enabled:
   ```yaml
   poller:
     enabled: true
   ```
2. Check system IDs are correct:
   ```yaml
   poller:
     systems:
       - "CCS"
       - "SPI"  # Must match BCB codes
   ```
3. Trigger manual poll:
   ```bash
   curl -u admin:password -X POST http://localhost:8081/admin/poller/trigger
   ```
4. Check STA connectivity in logs

### File Download Failed

**Symptom:**
```
Error: failed to download file: protocol not found
```

**Solution:**
1. Verify protocol number is valid
2. Check if file was already downloaded (duplicate)
3. Review STA response in debug logs
4. Ensure institution has access to the file

### File Parsing Error

**Symptom:**
```
Error: failed to parse file: unexpected format
```

**Solution:**
1. Verify file type matches expected format
2. Check for corrupted download
3. Review parser configuration for the system
4. Enable debug logging to see raw content

### Delivery Failed

**Symptom:**
```
Error: failed to deliver file: connection refused
```

**Solution:**
1. Verify destination URL is correct:
   ```yaml
   routes:
     CCS:
       url: "https://staapi-planner.monetarie.com.br/api/v1/ccs"
   ```
2. Test destination is reachable:
   ```bash
   curl -I https://staapi-planner.monetarie.com.br/api/v1/ccs
   ```
3. Check authentication token is valid
4. Increase timeout if destination is slow:
   ```yaml
   routes:
     CCS:
       timeout_seconds: 60
   ```

### File Stuck in Retrying

**Symptom:** File stays in `retrying` status indefinitely.

**Solution:**
1. Check retry count in Admin API:
   ```bash
   curl -u admin:password "http://localhost:8081/admin/files?status=retrying"
   ```
2. Review error message for root cause
3. Fix underlying issue (network, auth, etc.)
4. Manually retry or skip file

---

## API Issues

### 401 Unauthorized

**Symptom:**
```json
{"error": "Unauthorized"}
```

**Solution:**
1. Check API key for Outbound API:
   ```bash
   curl -H "Authorization: Bearer ${API_KEY}" http://localhost:8080/api/v1/health
   ```
2. Check credentials for Admin API:
   ```bash
   curl -u admin:password http://localhost:8081/admin/health
   ```
3. Verify auth configuration:
   ```yaml
   outbound_api:
     auth:
       type: "api_key"
       api_key: "${OUTBOUND_API_KEY}"
   ```

### 400 Bad Request

**Symptom:**
```json
{"error": "validation_error", "message": "..."}
```

**Solution:**
1. Review the error message for specific field
2. Check request body format:
   ```bash
   curl -X POST http://localhost:8080/api/v1/files \
     -H "Content-Type: application/json" \
     -d '{"system": "CCS", ...}'
   ```
3. Validate base64 encoding of content
4. Ensure required fields are present

### 429 Too Many Requests

**Symptom:**
```json
{"error": "rate_limited", "retry_after": 30}
```

**Solution:**
1. Implement backoff in your client
2. Reduce request frequency
3. Wait for `retry_after` seconds before retrying

### 502 Bad Gateway

**Symptom:**
```json
{"error": "sta_error", "message": "..."}
```

**Solution:**
1. Check STA connection status
2. Review STA error message
3. Verify BCB systems are operational
4. Check network connectivity

---

## Performance Issues

### High Memory Usage

**Symptom:** Container memory keeps growing.

**Solution:**
1. Reduce batch size:
   ```yaml
   poller:
     batch_size: 5
   ```
2. Check for memory leaks in logs
3. Increase memory limit:
   ```yaml
   resources:
     limits:
       memory: 1Gi
   ```
4. Restart container to clear memory

### High CPU Usage

**Symptom:** CPU consistently at 100%.

**Solution:**
1. Reduce polling frequency:
   ```yaml
   poller:
     interval_seconds: 60
   ```
2. Check for stuck goroutines in logs
3. Increase CPU limit:
   ```yaml
   resources:
     limits:
       cpu: "2"
   ```

### Slow Response Times

**Symptom:** API responses take several seconds.

**Solution:**
1. Check database performance
2. Verify STA latency:
   ```bash
   curl -u admin:password http://localhost:8081/admin/metrics | jq '.sta_client.avg_latency_ms'
   ```
3. Reduce concurrent operations
4. Use PostgreSQL instead of SQLite for production

### Queue Depth Growing

**Symptom:** Pending files keep increasing.

**Solution:**
1. Increase batch size if under rate limit:
   ```yaml
   poller:
     batch_size: 20
   ```
2. Check for processing errors
3. Verify destination endpoints are healthy
4. Scale up replicas (with PostgreSQL)

---

## Database Issues

### SQLite Locked

**Symptom:**
```
Error: database is locked
```

**Solution:**
1. Only run one connector instance with SQLite
2. Switch to PostgreSQL for multiple instances:
   ```yaml
   state_store:
     type: "postgres"
   ```
3. Check for stuck processes:
   ```bash
   lsof ./data/state.db
   ```

### PostgreSQL Connection Pool Exhausted

**Symptom:**
```
Error: too many connections
```

**Solution:**
1. Increase max connections in PostgreSQL
2. Reduce connector replicas
3. Add connection pooler (PgBouncer)
4. Review application connection usage

### Migration Failed

**Symptom:**
```
Error: failed to run migrations
```

**Solution:**
1. Check database permissions
2. Verify connection string is correct
3. Run migrations manually if needed
4. Check for schema conflicts

---

## Docker Issues

### Container Keeps Restarting

**Symptom:** Container restarts repeatedly.

**Solution:**
1. Check logs for error:
   ```bash
   docker logs sta-connector
   ```
2. Verify configuration is valid
3. Check health check isn't too strict:
   ```yaml
   healthcheck:
     start_period: 30s
   ```

### Volume Permission Denied

**Symptom:**
```
Error: permission denied opening file
```

**Solution:**
1. Fix host directory permissions:
   ```bash
   sudo chown -R 1000:1000 ./data
   ```
2. Or use named volumes:
   ```yaml
   volumes:
     - connector-data:/app/data
   ```

### Network Issues

**Symptom:** Containers can't communicate.

**Solution:**
1. Check network exists:
   ```bash
   docker network ls
   ```
2. Verify services are on same network
3. Use service names, not localhost:
   ```yaml
   DB_HOST: postgres  # Not localhost
   ```

---

## Kubernetes Issues

### Pod CrashLoopBackOff

**Symptom:** Pod keeps crashing and restarting.

**Solution:**
1. Check logs:
   ```bash
   kubectl logs deployment/sta-connector -n sta-connector --previous
   ```
2. Describe pod for events:
   ```bash
   kubectl describe pod -l app=sta-connector -n sta-connector
   ```
3. Verify ConfigMap and Secrets exist
4. Check resource limits aren't too low

### Readiness Probe Failing

**Symptom:** Pod never becomes ready.

**Solution:**
1. Test health endpoint:
   ```bash
   kubectl exec deployment/sta-connector -n sta-connector -- wget -qO- http://localhost:8080/api/v1/health
   ```
2. Increase initial delay:
   ```yaml
   readinessProbe:
     initialDelaySeconds: 30
   ```
3. Check application logs for startup errors

### Service Not Reachable

**Symptom:** Cannot connect to service.

**Solution:**
1. Verify service exists:
   ```bash
   kubectl get svc -n sta-connector
   ```
2. Check endpoints:
   ```bash
   kubectl get endpoints sta-connector -n sta-connector
   ```
3. Port forward to test:
   ```bash
   kubectl port-forward svc/sta-connector 8080:8080 -n sta-connector
   ```

---

## Debug Mode

Enable debug logging for more information:

```yaml
service:
  log_level: "debug"
```

Or via Admin API:

```bash
curl -u admin:password -X PATCH http://localhost:8081/admin/config \
  -H "Content-Type: application/json" \
  -d '{"service": {"log_level": "debug"}}'
```

Debug logs include:
- Full STA request/response
- File processing steps
- Retry attempts
- Configuration changes

---

## Getting Help

If you can't resolve an issue:

1. **Check existing issues** on GitHub
2. **Search documentation** for similar problems
3. **Enable debug logging** and collect logs
4. **Open a new issue** with:
   - Connector version
   - Configuration (redact secrets)
   - Full error message
   - Steps to reproduce
   - Debug logs

---

## Next Steps

- [Configuration](/guide/configuration) - Configuration reference
- [Admin API](/api/admin) - API for management
- [Docker Deployment](/deployment/docker) - Docker setup
