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:
startandresurrectprobe/health; if offline,MOOND_HOME/daemon.lockprevents concurrent races whilespawn_orphanlaunchesmoond daemon --detach. The daemon binds its control-plane port before writingtokenanddaemon.pid, ensuring a duplicate launch never clobbers a running daemon’s credentials. - Control Plane Auth & Validation: On startup, the daemon generates a
0600random token atMOOND_HOME/tokenand verifiesAuthorization: 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, andspawn_orphan. - Multi-Process Port Sharing (
socket):TcpServer/UdpServersupportreuse_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_signalshandlesSIGINTandSIGTERMcleanly for both daemon shutdown andlogs -f. - Async I/O & HTTP (
fs/http/socket): IncrementalFile::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:
- Session Detach (
setsid()): Detaches the orphan daemon from the controlling terminal. - Process & Process-Group Control (
getpid(),kill(),kill_group()): Writesdaemon.pid, validates lock liveness, and cleans up entire worker process groups on stop. - 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>/staton Linux, andGetProcessMemoryInfo/GetProcessTimeson Windows. - Local time fields are captured atomically from a single
time()+localtime_rcall to prevent cross-second tearing in timestamps and cron scheduling.
- Uses
Restart & Log Rotation Policies
- Min-Uptime Reset (
min_uptime_ms): Once a worker runs stably for at leastmin_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 exceedingmax_restarts, transitioning the worker toerrored. - Runtime Log Rotation & Incremental Tail: A background daemon loop checks log sizes every 5s and performs copytruncate rotation to
.1when exceedingmax_log_bytes.moond logs -ftracks byte offsets viaFile::at(offset)and automatically handles truncation/rotation.