# Shared Runtime Features

This page summarizes runtime features that are implemented in shared code and reused by multiple BaSyx Go components.

## Health Endpoint

The shared endpoint helper registers:

- `GET {contextPath}/health`

It returns HTTP `200` with:

```json
{"status":"UP"}
```

The basic health handler confirms that the HTTP process can respond. It does not probe PostgreSQL or guarantee that API operations will succeed. The AAS Environment adds a startup-readiness check and returns `503 Service Unavailable` with status `DOWN` until its startup preconfiguration has completed. For example:

```bash
curl -i http://localhost:8084/health
```

Use the component's port and prefix `/health` with its configured context path. Use `curl.exe` in PowerShell.

## CORS Middleware

Shared CORS middleware is configured from the `cors` config block:

- `allowedOrigins`
- `allowedMethods`
- `allowedHeaders`
- `allowCredentials`

## Context Path Handling

Components can be served below a configurable `server.contextPath`. Shared helpers use this base path when registering common endpoints (for example Swagger UI and health).

## Conditional Requests

Single-resource reads provide ETags. Clients can use `If-Match` to protect writes and `If-None-Match` to revalidate cached reads or make a PUT create-only. See [Conditional Requests](conditional_requests) for route coverage, `412` and `428` responses, and configuration.

## Error Responses

API errors use the AAS `Result` object with a `messages` array:

```json
{
  "messages": [
    {
      "messageType": "Error",
      "text": "Explanation of the failure",
      "code": "400",
      "correlationId": "example-correlation-id",
      "timestamp": "2026-10-16T08:00:00Z"
    }
  ]
}
```

Message timestamps are UTC and `correlationId` is limited to 128 characters. DPP API errors also supply a non-empty correlation ID.

`correlationId` helps identify the component and operation associated with an error. Include it with the error message and timestamp when reporting a problem. It is not necessarily unique to a request.

## Shared Configuration Loading

All components using `internal/common` benefit from:

- YAML + environment-variable configuration loading
- default values for common settings
- startup configuration logging with sensitive values redacted

## Logging and Request Correlation

All commands use structured, severity-filtered logging on standard error. HTTP
services also provide canonical request and correlation IDs and emit one
access-log event per request. See [Observability](observability) for the logging
contract and header behavior.

## Optional OpenTelemetry Telemetry

HTTP services can create OpenTelemetry server spans and correlate contextual
logs with trace and span IDs. They can also export shared PostgreSQL
connection-pool metrics. Tracing and metrics are disabled independently by
default and configured through standard OpenTelemetry environment variables.
See [Observability](observability) for activation, propagation, sampling,
metric interpretation, and backend integration.

## Experimental Eventing

The AAS Repository, Submodel Repository, and AAS Environment can emit
CloudEvents for model changes through a retained REST Event Feed, MQTT 5,
Kafka, or AMQP 1.0. Event capture and broker outbox writes participate in the
model mutation transaction. See [Eventing](eventing) for supported mutations,
configuration, delivery guarantees, and security boundaries.

## Shared Security Building Blocks

The common configuration and security packages provide reusable building blocks for:

- OIDC trustlist-based issuer configuration (`oidc.trustlistPath`)
- ABAC enablement and model configuration (`abac.*`)
- startup security middleware setup that reads trustlist / access-rules files when ABAC is enabled
- experimental relationship-based access control on top of ABAC (`rebac.*`, see [ReBAC](rebac))

See [Runtime Security](security) for token validation, claim mapping, anonymous
requests, ABAC evaluation, and resource-filtering behavior.

## Shared PostgreSQL Configuration Pattern

Multiple components reuse the same PostgreSQL configuration structure and connection pool settings:

- `postgres.host`
- `postgres.port`
- `postgres.dbname`
- `postgres.user`
- `postgres.password`
- `postgres.applicationName`
- `postgres.maxOpenConnections`
- `postgres.maxIdleConnections`
- `postgres.connMaxLifetimeMinutes`
- `postgres.connMaxIdleTimeMinutes`

Each service process or Kubernetes pod owns a separate pool. The common defaults are:

| Setting | Default | Zero value |
| --- | --- | --- |
| `maxOpenConnections` | `50` | Uses the default. |
| `maxIdleConnections` | `25` | Uses the default, capped at a smaller explicit open limit. |
| `connMaxLifetimeMinutes` | `5` | Uses the default. |
| `connMaxIdleTimeMinutes` | `0` | Disables idle-time recycling. |

An explicitly configured idle limit greater than the effective open limit is rejected at startup. Size each PostgreSQL primary independently: add the open limits of every BaSyx pod and other application pool connected to that primary, using the maximum concurrent replica count during rolling updates. Reserve capacity for administration, monitoring, schema migration, and failover.

If `applicationName` and the DSN do not define a PostgreSQL `application_name`, the service name is used automatically. Explicit values are preserved. This makes per-service connections visible in `pg_stat_activity`.

See [General Configuration](configuration) for the full PostgreSQL configuration and budgeting guidance.

## Optional PostgreSQL Reader Routing

BaSyx Go can open an independent PostgreSQL reader pool for eligible reads.
Without reader configuration, the writer pool is reused and
the behavior remains unchanged. With a reader configured, mutations and
consistency-sensitive work stay on the writer while eligible reads can be
served by a standby or other read endpoint.

Reader routing is based on consistency requirements, not on how many database
queries a request executes. Results from a replicated reader are eventually
consistent between requests, including authorization-relevant resource changes.
When one response requires multiple SQL queries, those queries use one
read-only repeatable-read transaction so that the response is assembled from
one reader snapshot. See
[General Configuration](configuration.md#optional-postgresql-reader) for the
supported components, routing guarantees, security considerations, connection
variables, and independent pool-sizing guidance.
