1
0
Fork
You've already forked zig-lifecycle
0
Deterministic process lifecycle management for posix applications written in Zig
  • Zig 100%
Anthony Manning-Franklin c82893a4af Allow start and stop to throw
2026年03月01日 20:11:10 +08:00
src Allow start and stop to throw 2026年03月01日 20:11:10 +08:00
.gitignore Initial commit 2026年03月01日 14:08:19 +08:00
build.zig Fixed package errors 2026年03月01日 17:38:49 +08:00
build.zig.zon feedback 2026年03月01日 16:36:01 +08:00
README.md Allow start and stop to throw 2026年03月01日 20:11:10 +08:00

Zig Lifecycle

Deterministic process lifecycle management for posix applications written in Zig.

Zig Lifecycle makes you define your application's components at comptime as a tree of components.

During initialization, Zig Lifecycle performs a depth-first traversal over the tree, starting each component in sequence. When the process begins exiting, each component is stopped in the reverse sequence.

Why is this useful?:

  • Reliable: Starting/stopping each component synchronously in a deterministic order prevents race conditions during startup and shut down
  • Readable: Encourages better separation of concerns, reducing cognitive load for readers of the code
  • Declarative: More explicitly declare a program's architecture in main.zig
  • Composable: Packages, frameworks, and other reusable components can export a LifecycleNode encapsulating its startup and shut down requirements. Users of that package can decide where in their lifecycle graph to add the package's LifecycleNode.

Usage

Inside main.zig:

constlifecycle=@import("lifecycle");constDbPool=@import("./db.zig");// example lifecycle componentconstHttpServer=@import("./http.zig");// example lifecycle componentfnmain()!void{constlifecycle=lifecycle.Root.define(&[_]lifecycle.Node{lifecycle.Node.define(DbPool),lifecycle.Node.define(HttpServer),});trylifecycle.start();deferlifecycle.stop();while(lifecycle.Root.isRunning()){// do stuff}}

This process is guaranteed to start the database connection pool before serving HTTP connections. It's also guaranteed not to close the database connection pool until after HttpServer has finished closing down, allowing all in-flight requests to drain from the server.

Let's take a look inside db.zig to see how a LifecycleNode is defined:

conststd=@import("std");constpg=@import("pg");constlog=std.log.scoped(.DbPool);pubconstname="DbManager";varpool:pg.Pool=undefined;pubfnstart(allocator:Allocator)!void{pool=trypg.Pool.init(allocator,.{.size=5,.connect=.{.port=5432,.host="127.0.0.1"},.auth=.{.username="pg",.database="pg",.timeout=10_000},});}pubfnstop()!void{trypool.deinit();}

Installation

First, fetch for your project:

zig fetch --save git+https://codeberg.org/AntmanCodes/zig-lifecycle.git

Then add to build.zig:

constlifecycle_module=b.dependency("lifecycle",.{}).module("lifecycle");exe.root_module.addImport("lifecycle",lifecycle_module);