m0serve Realtime from a synchronous Python app

The host

What a Mojo application's main hands over: handlers and producers, workers, threads and a handler pool, flags, the doctor, every refusal and exit code.

m0_host is what a Mojo application's main calls. It owns the listener, the workers, the signals and the drain; the application supplies a handler and, if it has work on a cadence, a producer.

from m0_host.flags import host_config
from m0_host.host import ViewsApp, serve

from views import Items

def main() raises:
    serve[ViewsApp[Items]](host_config())

What an application supplies

serve[H, P](config) takes two types.

H: AppHandler is an HTTPService with a static make(ctx). The host calls make once per worker, after the fork, so each worker builds its own handler. Four more static methods have defaults:

method default what it declares
page_slots(workers) -> Int 0 words of shared memory, created before the fork and handed to every make as ctx.page
max_workers() -> Int 0, any number the most processes this application serves from
max_threads() -> Int max_workers() the most loops in one process
pool_state_routes() raises -> List[String] none the routes, as METHOD /pattern, whose views read or write in-memory state on a pool thread, which pool-vs-application reads; ViewsApp names them from its table

An application whose state lives in the handler answers max_workers() -> 1. M0_WORKERS=2 is then refused at startup: two workers would hold two different copies.

ViewsApp[S] is the AppHandler for an application that is a views table. S: ViewState has make(ctx) and urls(); page_slots, max_workers and max_threads as above; and the four stream hooks and the tick, with the handler's defaults, so a state that holds a stream (a Feed, a DatastarStream) forwards them to it. The fourth, take_ready_streams, is for a loop that holds many streams. A state that forwards it to its stream's take_ready and answers True has each pass drain only the streams with something to send. The views, board and auth scaffolds are ViewsApp; live, whose handler owns a DatastarStream and a producer, is an AppHandler of its own.

P: Producer is work on a cadence, off the event loop: make(ctx), and step(mut self, mut out: Publisher) -> Int, which returns the nanoseconds until the next step. One producer runs, on a thread of worker 0, and out.publish(channel, id, frame) reaches every worker's streams. Number frames with out.next_id(): the counter is shared memory, so it survives a worker being replaced. publish returns False for a frame a channel refused; count those. NoProducer is the default.

A view sends too, through a DatastarStream the state or the handler holds: a frame it publishes reaches the subscribers of the worker that answered the request. Every other worker's are reached once make has called stream.enable_bus(ctx.bus, ctx.worker, ctx.id_addr) and the handler forwards sse_peer_frame to deliver_peer; ViewsApp forwards the other stream hooks and not that one, so this takes an AppHandler of the application's own, which apps/datastar_todo is. Without the bus a frame stays in its process, the board scaffold's shape (max_workers() -> 1).

HostContext, the argument to every make:

field meaning
worker, workers this worker's index and the count; processes or loops
threaded whether the workers are loops on threads of one process
thread -1 for the loop's own handler, 0 upward for a pool thread's
capacity the connection capacity; a stream registry needs at least this many slots
page address of the application's shared page, or 0
id_addr the shared event-id word every worker numbers from; enable_bus takes it
bus every worker's channel, for a handler that publishes to its peers
config the resolved configuration

ctx.tick_owner() is true on worker 0, and ctx.on_loop() on the loop's own instance.

A make that raises, in a handler or a producer, ends the process with exit 78 and its message. It is not retried.

Execution modes

One loop in one process is the default, and on one vCPU it is the whole answer (Deploy). A loop holds 1024 connections by default, and --max-connections (M0_MAX_CONNECTIONS) sets 1 to 65536; streams take all but a sixteenth of them, at most 16: the stream after that is answered 503 with Retry-After, so the health path is still answered while streams hold the rest. A connection that finds every slot in use takes one back from the connection idle longest between requests, or else from the one longest sending its head (answered 408), each once that is a second, and is refused only when neither is there. Each is said once on stderr, naming the setting that moves it. More streams are a larger count or more loops. The host raises its own open-file limit to what its loops need before it binds; where the hard limit stops it short, each loop holds what the limit leaves, its stream reserve kept from that, and the host says so. The doctor reports max_connections_per_loop, stream_limit_per_loop and descriptor_limit.

M0_THREADS=N runs N loops on N threads of one process, and is the way to more than one core. Nothing is forked, so the loops share an address space and a runtime that cannot survive a fork works: MAX's parallel runtime, Core ML, CoreFoundation. There is no supervisor: a loop that dies takes the process, and the platform restarts it. Refused beside M0_WORKERS above 1.

M0_WORKERS=N forks N processes that share the listener. A worker that dies is replaced. The worker that wins an accept hands the connection to the least-loaded sibling, so keep-alive load spreads. Refused when the binary links MAX's parallel runtime (libAsyncRTMojoBindings, what max.algorithm.parallelize needs): fork() copies the calling thread alone, and a parallelize in a forked worker never returns. On macOS a binary built beside an installed max-core links that runtime whether or not it imports MAX, so there the refusal covers every build in a MAX venv (known issues).

Measured against each other, threads and workers are level on throughput (0.95x to 1.03x) and on the tail, and threads use a fifth to a third less memory. Workers are for an application that links no MAX and wants a supervisor. ctx.worker and ctx.workers count either, so an application runs under both unchanged.

M0_BLOCKING_THREADS=N puts N handler threads behind each loop, and composes with either mode. The loop keeps accepting and parsing while a slow view runs on a pool thread. Each pool thread builds its own handler with make (ctx.thread says which). A view registered with add_loop, or on_loop=True, is answered on the loop and never queued. A stream must be opened on the loop: one begun on a pool thread is refused with 409.

Configuration

A flag overrides its M0_ variable, which overrides the default.

flag variable default
--host ADDR M0_HOST 127.0.0.1
--port N M0_PORT 8080
--workers N M0_WORKERS 1
--threads N M0_THREADS 1
--blocking-threads N M0_BLOCKING_THREADS 0
--access-log M0_ACCESS_LOG off
--sse-heartbeat-ms N M0_SSE_HEARTBEAT_MS 15000
--app-tick-ms N M0_APP_TICK_MS 0, off
--max-keepalive-requests N M0_MAX_KEEPALIVE_REQUESTS 1000
--max-connections N M0_MAX_CONNECTIONS 1024 per loop, 1 to 65536
--qos M0_QOS off; macOS, keeps the loop on performance cores
--spawn-workers M0_SPAWN_WORKERS m0serve's; refused here
--doctor print the configuration, start nothing
--help

Read from the environment alone: M0_BASE_URL (config.base_url, http://localhost:PORT by default), M0_SSE_FLUSH_MS (the comment that follows an SSE event; 150, 0 off), M0_STREAM_KEEPALIVE_S (TCP keepalive on a stream's socket; 15, 0 off), and M0_LIBSQLITE3, M0_LIBPQ and M0_LIBZSTD, which name a library file outright.

A variable the host cannot read, such as M0_PORT=80eighty or a number too large for an Int, falls back to its default without a word: unlike m0serve, the host does not name a value it could not read.

host_config() is an AppConfig with the command line applied, for an application that prints its own address before serving. serve(AppConfig()) applies the flags itself.

Exit codes and refusals

code meaning
0 served, then drained on SIGTERM or SIGINT
1 a failure while starting or serving: the address cannot be bound, a loop raised, a loop did not finish its drain
2 a command line that cannot be read: an unknown flag, a value that is not a number
78 a configuration that was read and will not be served

The host prints to stderr every line but --help, the doctor's report, the listening line and the access log, which are stdout's. Every 78 is said there, on lines that open with host:: a check's refusal is one line, what was found and then the fix in parentheses, and a make that raises is refused with its own error. The checks, in the order the host applies them:

check refused when
port M0_PORT is outside 1-65535
address the listen address does not parse, such as a % (an IPv6 zone) in M0_HOST
workers-count M0_WORKERS is below 1
workers-vs-application M0_WORKERS is above the application's max_workers()
threads-count M0_THREADS is below 1
workers-vs-threads M0_WORKERS and M0_THREADS are both above 1
threads-vs-application M0_THREADS is above the application's max_threads()
max-connections M0_MAX_CONNECTIONS is 0 or above 65536: one loop holds 1 to 65536 connections
pool-vs-application M0_BLOCKING_THREADS is above 0, the application's max_threads() is 1, and a view given the state is left on the pool: each pool thread builds a state of its own, so that view would answer from its thread's copy
spawn-workers M0_SPAWN_WORKERS is set: the host forks without exec
spawned-marker M0_WORKER_SPAWNED is inherited from an m0serve worker
workers-vs-parallel-runtime M0_WORKERS is above 1 and the binary links MAX's parallel runtime

A count or a port is refused the same way whether it came from a flag or a variable.

The doctor

bin/server --doctor prints one JSON object as the last line of stdout and binds nothing. It holds the resolved configuration, where each value came from (flag, env or default), the topology that adds up to, what the application declares (max_workers, max_threads, page_slots), and a checks array in which every failure carries its fix. It exits with the code serving would exit with for the same arguments, because serve and the doctor read the same list of checks.

m0's toolchain checks are platform, mojo-installed, mojo-gated, max-gated, c-compiler, patchelf, project. uv run m0 doctor runs every one but patchelf, which only m0 build --release asks, then this one.

Shutdown

SIGTERM and SIGINT drain: in-flight requests finish, held streams are closed from the server, and the process exits 0. The drain, the handler pool's join and the producer's join share one five-second bound. A thread still running after it is named on stderr and the process exits anyway, so docker stop never waits for SIGKILL. The binary runs correctly as PID 1.

The capability rows are E21 to E32 and E42, C20, C21 and C23 to C25 for a loop's connections, and M31 for the listen address, in Capabilities. The design is recorded in the Mojo host, loops on threads and flags and a doctor for the host.