// runtime — process-wide Io singletons. // // Two Io.Threaded instances are stood up in main(). Most code should NOT // reach into this module; the discipline is: // // - services are structs that hold `io: Io` as a field; methods use self.io // - utility fns take `io: Io` as a parameter // // The one legal escape hatch is zap request handlers (and signal handlers): // zap's callback model is static fn pointers with no user-data slot, so a // handler reaching `runtime.app_io` is unavoidable. Any other reach into // this module is a smell. // // Future std.Io API changes touch a small surface: // - the field types here // - the `io: Io` field on each service struct // - the `io: Io` parameter on utility fns // Nothing scans for "Thread.Mutex" callsites — the discipline localizes the // blast radius. const std = @import("std"); /// Threaded runtime backing `app_io`. Initialized in main() (or lazily for tests). pub var app_io_backend: std.Io.Threaded = undefined; /// Application Io — passed explicitly to services and utility fns. /// Only zap request handlers (and signal handlers) read this directly. /// /// Initialized by main(). Tests that import code touching app_io should call /// `runtime.init(std.testing.allocator)` in a setup step or rely on lazy init /// (which uses `smp_allocator`). pub var app_io: std.Io = undefined; var initialized: bool = false; /// Lazy accessor — used by sync.globalIo() while sync.zig is still around, /// and by any callsite that runs before main() has had a chance to init /// (notably std test runners). Production paths should call init() explicitly. pub fn appIo() std.Io { if (initialized) return app_io; init(std.heap.smp_allocator); return app_io; } /// Threaded runtime backing the debug Io. Required so std.debug.print /// is thread-safe when multiple OS threads exist (zap workers + services). pub var debug_io_backend: std.Io.Threaded = undefined; /// Override std.Options.debug_io with our explicit Threaded instance. /// Add this to main.zig's `pub const std_options`: /// /// pub const std_options_debug_threaded_io: ?*std.Io.Threaded = &runtime.debug_io_backend; /// pub const std_options_debug_threaded_io: ?*std.Io.Threaded = &debug_io_backend; /// Initialize both Io runtimes. Must be called once, very early in main(). pub fn init(allocator: std.mem.Allocator) void { if (initialized) return; app_io_backend = std.Io.Threaded.init(allocator, .{}); app_io = app_io_backend.io(); debug_io_backend = std.Io.Threaded.init(allocator, .{}); initialized = true; } pub fn deinit() void { if (!initialized) return; if (!simulated) { app_io_backend.deinit(); debug_io_backend.deinit(); } initialized = false; simulated = false; } var simulated: bool = false; /// Deterministic simulation only: every `appIo()` reader gets `io` — the /// clock, sleeps and randomness all come from the simulator. pub fn initSimulated(io: std.Io) void { app_io = io; initialized = true; simulated = true; }