flua — architecture

This file explains how flua works under the hood. The user guide is USAGE.md; this is the machinery. Diagrams are ASCII so they render everywhere (GitHub, VS Code, terminal).

Deeper dives, kept out of this file on purpose:

1. Overview

flua runs real Fibaro QuickApps offline. One Python process hosts a lupa runtime (Lua 5.x) and an asyncio event loop:

                 +---------------------------- flua process ----------------------------+
                 |                                                                     |
  QA files ----> |  CLI (argparse, --%% parsing, mode peek)                            |
                 |    |                                                                |
                 |    v                                                                |
                 |  LuaEngine --------------------------------------------------       |
                 |  | lupa LuaRuntime  |  virtual clock   |  api (sim/HC3)     |       |
                 |  | inbound deque    |  TimerManager    |  qa_* worker pools |       |
                 |  | outbound queue   |  env chain       |  Hc3Remote (online)|       |
                 |  | pump task (THE single Lua entry point)                    |       |
                 |  +-----------------------------------------------------------+       |
                 |        ^ post(msg)                    | enqueue_outbound(msg)          |
                 |        |                              v                              |
                 |   Lua QAs (per-QA envs)          worker threads                      |
                 |   quickapp/fibaro/net/mqtt       urllib / sockets / RFC6455 / MQTT 3.1.1
                 |                                                                       |
                 +-----------------------------------------------------------------------+

2. The single-entry discipline

The one rule everything else follows: the pump is the only code that enters the Lua VM, and it never does so while Lua is on the stack.

The two deliberate exceptions, both documented:

  1. Log lines print directly (_PY.log) — writing to stdout touches no Lua state, so it is safe at any call depth, including inside debugger-stepped code where the pump is frozen.
  2. The debugger's sockets block the main thread — that is what makes a mobdebug pause freeze the pump and the virtual clock.

3. Message flow

  Lua code                     Python engine                       Lua runtime
  ---------                    --------------                      ------------

  _PY.post({type=...})         inbound deque                       
      ----------------------->  |                                  
                                v  pump loop:                      
                                |  tick(clock)                     
                                |  timers.fire_due()               
                                |  drain inbound -> handler        
                                |     (api, timers, worker spawn)  
                                |  outbound.get() -> batch         
                                |---------------------->  _FLUA.dispatch(batch)
                                |                             handlers[msg.type](msg)
                                |                             (timer fires, callbacks,
                                |                              QA bootstrap, ...)

Every message is a dict with a mandatory string type. Functions never cross the bridge — callbacks are registered Lua-side by integer id. The full type list lives in src/flua/messages.py; adding one means a handler in engine.py (inbound) and/or lua/init.lua (outbound).

4. Layers

src/flua/
  cli.py           argument parsing, --%% config assembly, mode peek (--%%offline),
                   --run-for / --watch / --check / export / unpack
  engine.py        LuaEngine: lupa VM, queues, pump, QA lifecycle, worker pools,
                   the HC3 poller, the auth-lockout guard
  api/             the REST surface: one dispatcher, two backends
    __init__.py      Api.dispatch: regex route table -> handlers -> hybrid forward
                     (variables on HC3-namespace ids and on PROXY devices route
                     via the FluaHelper bridge — the controller owns the state)
    state.py         SimState: devices/rooms/scenes/globals, change & event feeds
    routes/*.py      pure handlers: (state, request) -> (data, status)
  hc3.py           Hc3Remote: blocking urllib client, basic auth, raw-body import
  http.py          urllib-based blocking HTTP (worker threads)
  websocket.py     minimal RFC 6455 client (stdlib sockets + ssl)
  mqtt.py          minimal MQTT 3.1.1 client (stdlib sockets + ssl)
  sync_socket.py   blocking LuaSocket-compatible TCP/UDP (the debugger's sockets)
  devices/         the HC3 device catalog (176 real captures) + skeleton builder
  config.py        --%% annotation parsing, EOH, the offline peek, env helpers
  environment.py   the os.getenv chain: process env > local .env > ~/.env
  timers.py        TimerManager on the virtual clock (per-QA attribution)
  clock.py         VirtualClock: realtime / accelerated / instant, start time
  messages.py      message type constants + builders
  bindings.py      the _PY table (post, log, api, api_hc3, net/mqtt entry points)
  lua/init.lua     the Lua runtime: sanitizer, log, timers, dispatch, QA bootstrap
  lua/quickapp.lua the QuickApp/QuickAppBase/QuickAppChild classes
  lua/fibaro.lua   the fibaro API (HC3-compatible)
  lua/net.lua      HTTPClient, TCPSocket, UDPSocket, WebSocketClient(+Tls)
  lua/mqtt.lua     mqtt.Client, mqtt.QoS, the documented event API

5. The Lua runtime (lua/init.lua)

6. The REST dispatcher (api/)

One dispatcher, three outcomes:

  api.get(path) -> Api.dispatch
    |-- /quickApp/*      engine-backed QA file management (local only)
    |-- route table      pure handlers over SimState -> (data, status)
    |       |-- resource reads (online) -> the HC3 answers; handlers merge
    |       |      the emu's local resources (emulated QAs, scene QAs) in
    |       |-- matched 404 + online + entity id < 5000 -> forward to the HC3
    |       '-- matched 404 + flua id (>= 5000)          -> local 404, never forward
    '-- no route + online                                -> forward to the HC3

7. Worker threads

The full threading model — who may block what, what counts as pending work, and the races that bit us — lives in concurrency.md. This section is the tour version.

All blocking network I/O runs in worker threads; the pump never blocks:

  Lua post {httpRequest|tcp*|udp*|ws*|mqtt*}
    -> handler spawns an asyncio task
       -> asyncio.to_thread(blocking op) on a dedicated pool
          -> result -> enqueue_outbound  (thread-safe hop: call_soon_threadsafe)
             -> pump -> dispatch -> per-QA net/mqtt handlers -> callbacks

In-flight work counts as pending work — the process stays alive until timers, queues, and open connections are all done. The debugger's sockets are the one main-thread exception (see §2).

A QA's api.* calls with a remote backend (online/proxy mode) use the same worker-thread pattern via the apiCall/apiResult messages: the Lua side yields a request table, the pump spawns a worker thread running the hybrid dispatch (serialized against other dispatches by Api's lock — the sim side is shared state), and the response resumes the QA's coroutine with (data, status). The QA stays suspended meanwhile — its own messages defer through the same sleeping/workQueues machinery as fibaro.sleep — while the pump and every other QA keep running. Offline, the synchronous _PY.api bridge remains the fast path.

The mirror image is net.*Server (flua extension, server.py): mock servers hosted on the loop for QA-side testing. The socket is bound synchronously when the QA calls listen (port 0 resolves at once), and serving is asyncio-native. Each incoming request posts a serverRequest message into the pump; the QA handler runs there, and its return value comes back through the synchronous net_server_reply bridge call (the pump runs on the loop thread), resolving the connection's future. Servers die with their QA (exit/restart) and on engine stop.

8. Virtual time

Timers run on VirtualClock (virtual seconds, epoch-aligned). Modes: realtime, --speed N accelerated, --instant (timers fire now, time jumps to each deadline). os.time()/os.date() read the virtual clock (whole seconds); os.clock() stays the real runtime clock; _FLUA.millitime() is virtual milliseconds. --start "2027/12/31 23:59:50" sets the origin, so date logic can be tested at New Year, leap days, DST changes — and the debugger pause freezes the clock (the freeze is noted around the blocking receive).

9. Config pipeline

  raw file header   ->  parse_annotations()  (--%% directives, EOH header)
  --%%include:...   ->  expand_includes(): the included files' directives
                       become defaults (QA header wins, files append, nested
                       includes resolve relative to the including file)
  --%%mode:...      ->  mode decision: --api flag > main QA's mode > online
  per-QA config     <-  CLI flags + globals + locals + .flua.lua base
  --%%var:name=expr    ->  evaluated in Lua with {config, os} in scope
  os.getenv(name)      ->  EnvChain: process env > local .env > ~/.env

The .fqa export/import round-trip reuses the pipeline: unpacked files carry generated --%% headers, so imports load like any other QA.

10. Online mode (--api remote)

Hc3Remote (stdlib urllib) speaks basic auth and the raw-body import transport (POST /quickApp/ with the fqa JSON string — the swagger's multipart description is misleading; the real transport was verified against a live HC3). The endpoints' structural reference (paths, parameters, response codes, schema fields) is docs/specs/hc3-api.json, distilled from the official swagger, which itself is Fibaro's property and not distributed. Two safety rules:

Mode selection: explicit --api > the main QA's --%%offline:true (peeked before the engine starts) > online if HC3 credentials exist in the env chain > offline.

11. The device catalog

QA devices are built from the distilled type schema (src/flua/devices/type_schemas.json, generated by scripts/extract_device_schemas.py): typed properties at their declared defaults, the type's interfaces expanded, and action metadata. The capture (devices.json — 176 real HC3 device captures, scrubbed of identity/secrets) is the demoted LAST-RESORT fallback for types the schema does not know, and the hierarchy resolves unknown types to their nearest known ancestor. The compat suite (§12) exists to catch exactly this class of drift.

12. Testing map

13. The invariants, in one place

  1. Only the pump enters Lua; never with Lua on the stack.
  2. Logs print directly (_PY.log), never queue.
  3. All bridge strings are UTF-8 (sanitizer on the way in).
  4. Functions never cross the bridge; callbacks are id-registered.
  5. flua entity ids are ≥ 5000 and are always served locally.
  6. An auth failure costs exactly one attempt, always.
  7. Worker I/O never blocks the pump; open connections are pending work.
  8. updateProperty emits an event only when the value changes.
  9. The debugger's sockets block the main thread on purpose.
  10. Tests never touch a production HC3 unless HC3_TEST=1.

Each of these (plus the identity/routing/event/exit contracts around them) is expanded with its pinning test in invariants.md.