# Adapters: the in-process bridge pattern

How an integrator writes an **adapter** — the glue
between an external system (MQTT broker, REST API,
camera detector, serial device, anything) and
libds's C API. Adapters run **in-process** with
libds and use its typed-callback surface; there is
no wire, no peer layer, no protobuf.

This doc describes the **mechanics** of building an
adapter against libds. The **contract** an adapter
promises to rule authors — the schemas it emits, the
services it offers, when it emits — lives in the
language tree at [LADP]. The two docs pair: LADP is what authors see;
NADP is what the adapter implementer wires up.

## What this is not

- Not the language-side adapter contract (schemas
  emitted, service shapes, declared filters). See
  LADP.
- Not specific to any one external system; each
  adapter has its own implementation tree.
- Not a code library — libds doesn't ship adapters.
  Each integrator builds the adapter that fits their
  deployment.

---

(NADP-1)=
## What an adapter is [NADP.1]

(NADP-1-1)=
[NADP.1.1] An adapter is **integrator code** that:

1. Connects to an external system at startup
   (subscribes to HA's state machine, opens an MQTT
   client, schedules a weather-fetch loop, etc.).
2. Registers libds callbacks for the action verbs
   the source system handles: `call` for service dispatch, `cache_*` for a
   storage backend, the stream callback for cross-tier bridging.
3. On source-system events, translates the event to
   slot values and calls `ds_engine_assert` to drive
   facts into working memory.
4. On registered callbacks firing, performs the
   adapter-side work. Where the service answers, it asserts
   response facts via `ds_engine_assert` once the call that fired
   the callback has returned ([NADP.4.2.2]).
5. Pumps the engine on whatever cadence suits the
   integrator's runtime (asyncio loop, dedicated
   thread, embedded scheduler, anything).

*see also:* [NADP.4.2.2](#NADP-4-2-2)

(NADP-1-2)=
[NADP.1.2] Adapters run **in the same process** as
libds. Cross-process bridging — HA running in a
separate process, MQTT broker on another host —
happens at the adapter's outer edge (HA-bridge talks
to HA over the WebSocket API; MQTT-bridge talks to
the broker via its native protocol). libds sees only
the C-API calls the adapter makes.

(NADP-1-3)=
[NADP.1.3] An integrator typically has **multiple
adapters** running against one engine: an entity-
state bridge for device state, a message-bus bridge
for the local broker, a polling adapter for REST APIs,
a sensor adapter for hardware events. Each is its own
translation surface; they share the engine.

(NADP-1-4)=
[NADP.1.4] One engine, many adapters. Per IARC.1.11
multiple engines may also coexist, but a typical
deployment runs one engine with several adapters
plugged into it.

---

*see also:* [IARC.1.11](#IARC-1-11)

(NADP-2)=
## Adapter startup [NADP.2]

(NADP-2-1)=
[NADP.2.1] Order of operations at adapter startup:

1. **Engine ready.** The engine is created and the
   adapter has a `ds_engine_t *` to call against.
2. **Load the program.** Every fact type arrives with
   `ds_engine_load_dsc`, the adapter's own included: they
   are declared in the program ([NFCT.1.1]). Load in this
   setup step, never after the first assert, retract or
   pump. See [NFCT.1].
3. **Register callbacks.** For every action verb the
   adapter handles, register the typed callback. The
   most common pair is the call callback (D6+C2,
   handles outbound service requests) plus the stream
   callback (audit / cross-tier bridging). Cache
   callbacks too, and the storage library's services in
   the call callback, if the adapter owns storage.
4. **Connect to the source system.** Subscribe,
   poll, or otherwise begin receiving events.
5. **Begin pumping.** The integrator's runtime drives
   `ds_engine_pump` on the chosen cadence; the
   adapter's source-event-handler calls
   `ds_engine_assert` from the integrator's pump
   thread when source events arrive.

*see also:* [NFCT.1](#NFCT-1), [NFCT.1.1](#NFCT-1-1)

(NADP-2-2)=
[NADP.2.2] **Schemas a rule references must exist when
the rule loads.** Loading a compiled rule set with
`ds_engine_load_dsc` registers its schemas as part of
the same load — nothing extra to do. A schema an adapter
supplies facts of is declared in the program like any other
([NFCT.1.1]).

*see also:* [NFCT.1.1](#NFCT-1-1)

(NADP-2-3)=
[NADP.2.3] **Callbacks are per-engine, not per-adapter.** Each callback
setter (`ds_engine_set_call_callback`, etc.) replaces the previous
registration. If two adapters both want to handle `call`, they share **one**
registered callback that dispatches by `service` name internally.

---

(NADP-3)=
## Inbound: source events → facts [NADP.3]

(NADP-3-1)=
[NADP.3.1] The core adapter loop translates source-
system events to slot values and calls\n`ds_engine_assert`.

(NADP-3-2)=
[NADP.3.2] **Lifecycle picking (LADP / LFAC).** Every
schema declares LOGICAL or TTL. The adapter picks per
emitted fact type:

| Fact kind                                  | Lifecycle |
|---|---|
| Entity state (device state, retained topics) | LOGICAL — retract-and-replace on meaningful change |
| Entity events (transient events, non-retained messages) | TTL — one event one fact, expires after the schema's ttl_ns |
| Service-call responses (the response fact / CallError) | TTL — the response schema must be, see [LCRS.4.3.2] |

*see also:* [LCRS.4.3.2](#LCRS-4-3-2), [LHYD.4](#LHYD-4)

(NADP-3-3)=
[NADP.3.3] **No-op reassertion is the engine's job
(LFAC.2.5.1).** The adapter is encouraged to re-emit
on every source change without filtering — the
engine dedups exact-and-tolerance equal reassertions.
Adapters that suppress at the source (comparing against
last-emitted state) make fewer calls into the engine at the
cost of slightly more code; engine-side dedup is the
correctness contract.

*see also:* [LFAC.2.5.1](#LFAC-2-5-1)

(NADP-3-4)=
[NADP.3.4] **Entity removal.** When the source system reports an entity is
gone, the adapter should retract the matching fact with `ds_engine_retract`.
Retracting needs the fact's handle, so an adapter that mirrors entities keeps
the handle each assert returned ([NFCT.2.5]) for as long as the fact is live.

*see also:* [NFCT.2.5](#NFCT-2-5)

(NADP-3-5)=
[NADP.3.5] Per [NFCT.3], retracted fact
pointers are invalid after `ds_engine_retract`
returns; null them defensively.

---

*see also:* [NFCT.3](#NFCT-3)

(NADP-4)=
## Outbound: action-verb callbacks [NADP.4]

(NADP-4-1)=
[NADP.4.1] Action verbs that need adapter-side logic
route through registered typed callbacks. The big
one is `call` (D6+C2): an author writes `call
light.turn_on entity_id: ...` and the adapter's call cb
dispatches the request.

(NADP-4-2)=
### Call dispatch [NADP.4.2]

(NADP-4-2-1)=
[NADP.4.2.1] The adapter's call cb sees the typed request
`ds_call_request_t`, declared in `runtime/include/libds.h`: the `service` the
author named, the `correlation` ([NCBK.6.3]), and the call's typed arguments ([NCBK.6.10]).

*see also:* [NCBK.6.10](#NCBK-6-10), [NCBK.6.3](#NCBK-6-3)

(NADP-4-2-2)=
[NADP.4.2.2] **Sync vs async work.** The cb runs on
the pump's stack per IARC.1.10 (no internal threads);
it must not block. It must not assert either: every call on the engine that
fired it returns `DS_ERR_STATE` ([RARC.13.16], [NCBK.1.2]). So the response fact
is asserted once that call has returned ([NCBK.6.4]). Two patterns:

- **Sync — fast services.** The adapter performs
  the work inline (a quick HA state-machine call,
  for instance), keeps the result, and returns DS_OK.
  Once the pump has returned, it asserts the response
  fact via `ds_engine_assert`.
- **Async — slow / latency-unbounded services.**
  The adapter queues the work onto its own runtime
  (asyncio task, thread pool, message broker
  publish) and returns DS_OK without asserting. The
  response arrives later when the queued work
  completes; the adapter's runtime then asserts the
  response fact from whichever thread the integrator
  pumps the engine on. A service declaring `no response`
  asserts nothing on success.

*see also:* [IARC.1.10](#IARC-1-10), [NCBK.1.2](#NCBK-1-2), [NCBK.6.4](#NCBK-6-4), [RARC.13.16](#RARC-13-16)

(NADP-4-2-3)=
[NADP.4.2.3] **Async caveat.** `ds_engine_assert` is
NOT thread-safe; it must run on the same thread that
pumps the engine. Adapters with async work that
completes on a different thread must marshal the
result back to the pump thread (queue + post-event,
asyncio future, etc.) before asserting.

(NADP-4-3)=
### Cooldown + supersede [NADP.4.3]

(NADP-4-3-1)=
[NADP.4.3.1] Neither cooldown nor supersede-on-correlation is the adapter's.
The engine suppresses a call inside its cooldown window before the call
reaches the adapter ([LCRS.8.2]), so an adapter keeps no cooldown map; an
adapter's own argument-dedup LRU, if it has one, is a safety net and nothing
more. The engine retracts the prior response fact and `CallError` before the
call reaches the adapter ([LCRS.6.2.1]), and the adapter must not retract
them itself.

*see also:* [LCRS.6.2.1](#LCRS-6-2-1), [LCRS.8.2](#LCRS-8-2)

(NADP-4-4)=
### Cache and stored facts [NADP.4.4]

(NADP-4-4-1)=
[NADP.4.4.1] If the adapter owns a storage backend
(e.g. a recorder DB, a Redis-backed cache), it registers the cache callbacks
(`ds_engine_cache_callbacks`). The facts plane it might also serve is deferred
([NSTG.3]).
Storage adapters and rule-side adapters are
typically separate; the HA-bridge handles HA
service calls but doesn't own a cache plane.

*see also:* [NSTG.3](#NSTG-3)

(NADP-4-4-2)=
[NADP.4.4.2] One process can host multiple
storage-owning adapters provided they don't both
claim the same callback slot. Each callback setter
replaces the previous registration; integrators
needing per-key routing register a shared dispatcher
cb that internally splits.

---

(NADP-5)=
## Lifecycle [NADP.5]

(NADP-5-1)=
### Connection state [NADP.5.1]

(NADP-5-1-1)=
[NADP.5.1.1] Adapters maintain their own connection
state; libds has no concept of "adapter
disconnected." The adapter:

- On disconnect, **continues to receive callbacks**
  from the engine (rules don't pause when an
  adapter disconnects). The cb returns a `CallError`
  with an `adapter.*` code ([LECC.4.3]) per LCRS.4.2.3 +
  LCRS.10.6 instead of attempting the operation.
  Author rules that expect timely responses use the
  absence idiom ([LCRS.7.1]).
- On reconnect, **re-publish LOGICAL state** the
  source system has (re-fetch all entity states;
  subscribe to retained topics; etc.) so the
  engine's working memory matches the source again. Adapter does this by walking the source's
  current state and asserting facts; engine-side
  no-op-reassertion-dedup absorbs unchanged values.

*see also:* [LCRS.10.6](#LCRS-10-6), [LCRS.4.2.3](#LCRS-4-2-3), [LCRS.7.1](#LCRS-7-1), [LECC.4.3](#LECC-4-3)

(NADP-5-1-2)=
[NADP.5.1.2] An adapter **may** surface its connection state to rules as a
fact it asserts on each transition: for example, a `logical` schema keyed by
the adapter's id, with a `Bool` slot that says whether it is connected. Rules
gate on that fact like any other. The engine itself has no notion of an
adapter's connection ([NADP.5.1.1]).

*see also:* [NADP.5.1.1](#NADP-5-1-1)

(NADP-5-2)=
### Shutdown [NADP.5.2]

(NADP-5-2-1)=
[NADP.5.2.1] On shutdown the adapter:

1. Stops accepting new source-system events.
2. Drains in-flight outbound work (or cancels with
   `CallError ruleset_reload` / `engine_shutdown`).
3. Unregisters its callbacks (set cb = NULL on the
   relevant `ds_engine_set_*_callback` calls).
4. Closes the source-system connection.
5. The engine itself is freed by the integrator
   after all adapters have unregistered, via
   `ds_engine_free`.

(NADP-5-2-2)=
[NADP.5.2.2] **Orderly shutdown matters.** A cb that
fires after the adapter starts tearing down its
internal state risks reading freed memory. Either
unregister callbacks first (so the engine stops
calling them) or guard each cb with an "is shutting
down" flag.

---

(NADP-6)=
## Three concrete patterns [NADP.6]

(NADP-6-1)=
### Entity-state adapter [NADP.6.1]

(NADP-6-1-1)=
[NADP.6.1.1] Translates a source system's entity model into LOGICAL facts,
and routes outbound service calls back through the source's API, asserting
each reply as a fact of the service's response schema.

(NADP-6-1-2)=
[NADP.6.1.2] Schemas this adapter registers: per LADP
the source system's fact catalogue (`Sensor`,
`BinarySensor`, `Switch`, `Climate`, etc.). One
LOGICAL fact per live entity.

(NADP-6-2)=
### Bridge adapter (MQTT, ZigBee, Matter) [NADP.6.2]

(NADP-6-2-1)=
[NADP.6.2.1] Subscribes to a message broker, translates
each message to a fact. Two flavours:

- **Retained topics → LOGICAL facts.** Retained
  topics are state; treat them as entity facts.
- **Non-retained → TTL facts.** Each message is an
  event; assert a TTL fact whose schema's ttl_ns
  matches how long downstream rules might want to
  react.

(NADP-6-2-2)=
[NADP.6.2.2] The adapter typically has a small
schema-registration table mapping topic-pattern →
schema, and a publish helper for outbound calls.

(NADP-6-3)=
### Polling adapter (REST API, calendar) [NADP.6.3]

(NADP-6-3-1)=
[NADP.6.3.1] Polls an external HTTP API on a
schedule, translates each response payload to facts.

(NADP-6-3-2)=
[NADP.6.3.2] A polling adapter has no inbound subscribe
loop — its source events come from its own scheduler.
Adapter's run-loop runs on the pump thread (typically)
or on a separate thread that posts events back via
`ds_engine_assert` from the pump thread.

---

(NADP-7)=
## Errors you'll surface [NADP.7]

(NADP-7-1)=
[NADP.7.1] The taxonomy is [NERR], with the impl-side detail at
[IERR.2]; the specific codes the adapter cb is expected
to return:

| Code | Cause |
|---|---|
| `DS_OK` | request accepted: the result is kept to assert after the pump returns, or async work is queued ([NADP.4.2.2]) |
| `DS_ERR_NOT_FOUND` | service name doesn't match anything this adapter handles |
| `DS_ERR_INVAL` | call body is malformed for this service |
| `DS_ERR_STORAGE_UNAVAILABLE` | source system unreachable; the adapter may instead assert a `CallError` with an `adapter.*` code ([LECC.4.3]) |

*see also:* [IERR.2](#IERR-2), [LECC.4.3](#LECC-4-3), [NADP.4.2.2](#NADP-4-2-2)

(NADP-7-2)=
[NADP.7.2] Returning `DS_ERR_NOT_FOUND` is the
right answer when the cb is a shared dispatcher
(NADP.2.3) and the request's service prefix isn't
this adapter's responsibility. The shared cb either
forwards to another adapter's handler or, if no
handler exists, returns NOT_FOUND.

*see also:* [NADP.2.3](#NADP-2-3)

(NADP-7-3)=
[NADP.7.3] Cb errors propagate through the engine's
pending slot per IDSP.1.3; the calling rule's pump
returns the cb's status. The author can also write
a `CallError` matcher rule per LCRS to react.

---

*see also:* [IDSP.1.3](#IDSP-1-3)

