# Configuration

JSON objects are strict: unknown keys, duplicate keys, wrong types, duplicate
device IDs/sink names and invalid limits are rejected before network connection.
Config input must be a regular UTF-8 file, at most 1 MiB, read incrementally.
Default limits: 256 devices, 64 outputs, 256 payload fields, rule depth 8 and
32 children per boolean rule. Individual output queue capacity is 1..65536.

## Root

`devices` and `sinks` are nonempty arrays. `duration_ms` defaults to 30000 and
must be 1..86400000. `max_events_per_device` defaults to 0 (unlimited within the
duration); otherwise 1..1000000. `retry` controls each device's lifetime reconnect
budget: `max_retries` (0..20, default 3), `initial_ms` (default 100),
`maximum_ms` (default 2000, <=60000 and >=initial). Initial attempt is additional
to retries. Backoff doubles to the cap; no infinite retry loop.

`drain_timeout_ms` defaults to 5000 and accepts 1..60000. Once collection stops,
all sinks share this time to finish delivery. At the deadline the gateway
cancels unfinished writes and counts undelivered events as drops.

## Devices

Common keys: `id`, `protocol`, `pipeline`. IDs use letters/digits/dot/dash/underscore,
1..100 characters. Protocol is `mock`, `mqtt`, `modbus_tcp`, `modbus_rtu` or `coap`.

- Mock: `count` (default 10), `interval_ms` (default 10).
- MQTT: `host`, `port` (1883), `topic`, `timeout_ms` (3000), `max_frame` (65536),
  `keep_alive_s` (30, accepts 1..65535),
  optional `username_env` and `password_env`. Topic filters are validated by the
  upstream codec. A password requires a username. Referenced environment
  variables must be set, <=1024 characters. No literal password key is accepted.
- Modbus: `host`, `port` (502), `unit` (1), `function` (3 or 4), `address` (0),
  `count` (1), `timeout_ms` (3000), `interval_ms` (1000) and nonempty `fields`.
  Each field has `name`, `offset` (register offset within the requested span),
  `type` (`u16/i16/u32/i32/f32`) and `low_word_first` (false).
- Modbus RTU (`modbus_rtu`): `serial_port`, `baud` and the Modbus register fields.
  See [serial settings and hardware setup](modbus-rtu.md).
- CoAP (`coap`): `host`, `port` (5683), `path` (for example `/sensors/t`),
  `timeout_ms` (3000), and `interval_ms` (1000, accepts 5..60000). The
  resource must return a flat JSON object with Content-Format 50.

The sample Modbus configuration uses port 1502 to avoid privileged-port setup.
Human register 40001 generally corresponds to wire address 0; consult the device
manual before choosing fields and word order.

## Pipeline

`mappings`: up to 256 objects with `from`, `to`, `conversion`, `scale`, `offset`,
`unit`. Conversion is `numeric` (default), `integer` (truncate after scaling),
`string`, `boolean` or `identity`. Numeric result is `input * scale + offset`.
Mappings read original input fields, so overlapping renames do not cascade.
Unmapped fields are retained by the built-in pipeline; `select` can project them.
Absent fields remain Missing; conversion errors drop the event and increment
`processing_errors`. Numeric conversion accepts finite numbers/numeric strings.
Boolean conversion accepts true/false, the strings "true"/"false", and 0/1.

`constraints`: objects with `field`, `required` (false), `type`
(`any/numeric/text/boolean`), optional inclusive `min` and `max`.
Invalid constraints are rejected at configuration time. `reject_invalid` defaults
to true. If false, invalid events remain marked and can route to diagnostics.
`max_age_ms` optionally checks observed time, falling back to received time;
future timestamps are stale. `select` is an optional list of output fields.

`filter` and sink `filter` use the same deterministic predicate syntax:

```json
{"op":"all","rules":[
  {"op":"gt","field":"temperature","value":30},
  {"op":"quality","value":"good"}
]}
```

Operations: `always`, `exists`, `device`, `quality`, `gt/ge/lt/le/eq/ne`,
`all`, `any`, `not` (exactly one child). Numeric comparisons require numeric
operands; text/boolean support equality only. Missing never satisfies a direct
comparison, including `ne`. An explicit `not` negates its child's Boolean result.

## Outputs

`name`, `type` (`console` or `jsonl`), optional `path` (required for JSONL),
`filter`, `capacity` (256), `overflow` (`reject_newest` default or `drop_oldest`),
`timeout_ms` (3000) and its own `retry` policy.

Create output directories first. JSONL appends and closes file handles per write.
Different route paths must not resolve to the same file; exact duplicate path
strings are rejected, but filesystem aliases are the operator's responsibility.
Files are not rotated and disk usage is not bounded by queue capacity.

JSON Lines outputs may opt into an offline journal with a `spool` object.
Set `directory` to a dedicated, trusted directory outside the output path.
Its parent must exist. Keep the directory exclusive to one destination.
`max_records` defaults to 128 (1..4096), and `record_bytes` defaults to 262144
(1..1048576). Their product may be at most 64 MiB. An interrupted write can
leave one temporary file of at most `record_bytes`. Keep limits stable while
old records remain.

The spool syncs and renames each accepted record before attempting to append
it to the output. Existing records replay in order on new arrivals. When
the spool is full and cannot replay, new writes fail and follow the route's
retry policy. With a spool enabled, the route's `delivered` counter means
accepted by the journal. If a write is canceled or the process stops after
appending but before acknowledging a record, replay can duplicate it.
The journal is designed for process restarts. Persistence across sudden power
loss depends on the filesystem and its handling of renamed directory entries.

Use `moon run cmd/moonedge --target native -- replay examples/config/offline.json`
to replay without launching collectors. The command uses the configured drain
timeout and prints the number replayed. See [the offline example](offline.md).

The final stderr report includes device state/received/errors and route
matched/delivered/failed/retried/dropped. Counters serialize as decimal strings.
Device `rejected` counts invalid readings discarded on an otherwise usable
session. They are separate from `errors` and do not count toward the event limit.
`filtered` includes processing rejects; `processing_errors` separately counts
exceptional transformations/validators. A delivered event means the sink write
returned successfully, not a durable fsync or end-to-end acknowledgement.
