Design

Architecture & Implementation

Single-binary design built on MoonBit core/async, supervision policies, and thin C FFI boundaries.

Single-Binary Architecture

moond compiles into a single Native executable that acts as both the CLI client and the background daemon (moond daemon):

moond start / ls / logs / reload / scale / apply / save ...
          │
          │  HTTP (127.0.0.1:19876) + Bearer Token (constant-time)
          ▼
    moond daemon (detached via setsid)
      ├── TaskGroup supervision loops & per-app Semaphore lock
      ├── Built-in L4 TCP reverse proxy (--proxy-port round-robin + failover)
      ├── Health probes (3s timeout), memory guard, cron & file watcher
      ├── Streaming log rotation (MOOND_HOME/logs/)
      └── Atomic state persistence (MOOND_HOME/state.json)
  • Auto-Spawn & Safe Startup Ordering: start and resurrect probe /health; if offline, MOOND_HOME/daemon.lock prevents concurrent races while spawn_orphan launches moond daemon --detach. The daemon binds its control-plane port before writing token and daemon.pid, ensuring a duplicate launch never clobbers a running daemon’s credentials.
  • Control Plane Auth & Validation: On startup, the daemon generates a 0600 random token at MOOND_HOME/token and verifies Authorization: Bearer <token> in constant time. App names are restricted to [A-Za-z0-9._-] to prevent path traversal or selector ambiguity.

Built on moonbitlang/core/async

MoonBit’s official async runtime has moved into the standard library moonbitlang/core/async, targeting Native event loops (Linux epoll, macOS kqueue, Windows IOCP). moond builds directly on its primitives:

  • Process Supervision (process): Cmd::spawn, wait, graceful_cancel, ProcessOutput::AppendFile, and spawn_orphan.
  • Multi-Process Port Sharing (socket): TcpServer / UdpServer support reuse_port_lb=true (SO_REUSEPORT), allowing multiple MoonBit workers on Linux to bind the same port with kernel-level load balancing.
  • Graceful Signals (signal): set_global_cancellation_signals handles SIGINT and SIGTERM cleanly for both daemon shutdown and logs -f.
  • Async I/O & HTTP (fs / http / socket): Incremental File::at(offset) tailing and local HTTP control server.

Thin C FFI Boundary (src/sys)

A small, self-contained C shim in src/sys/stub.c covers OS calls not yet exposed in the standard library:

  1. Session Detach (setsid()): Detaches the orphan daemon from the controlling terminal.
  2. Process & Process-Group Control (getpid(), kill(), kill_group()): Writes daemon.pid, validates lock liveness, and cleans up entire worker process groups on stop.
  3. Cross-Platform Metrics & Atomic Local Time (process_rss_bytes(), process_cpu_ms(), local_time()):
    • Uses proc_pidinfo(PROC_PIDTASKINFO) with a 50ms per-PID cache on macOS (avoiding duplicate syscalls when sampling RSS + CPU), /proc/<pid>/statm + /proc/<pid>/stat on Linux, and GetProcessMemoryInfo / GetProcessTimes on Windows.
    • Local time fields are captured atomically from a single time() + localtime_r call to prevent cross-second tearing in timestamps and cron scheduling.

Restart & Log Rotation Policies

  • Min-Uptime Reset (min_uptime_ms): Once a worker runs stably for at least min_uptime_ms (default 10s), consecutive crash counts reset to 0.
  • Exponential Backoff: Rapid crashes wait restart_delay_ms * 2^(n-1) (capped at 30s) until exceeding max_restarts, transitioning the worker to errored.
  • Runtime Log Rotation & Incremental Tail: A background daemon loop checks log sizes every 5s and performs copytruncate rotation to .1 when exceeding max_log_bytes. moond logs -f tracks byte offsets via File::at(offset) and automatically handles truncation/rotation.