|
|
||
|---|---|---|
| src | Allow start and stop to throw | |
| .gitignore | Initial commit | |
| build.zig | Fixed package errors | |
| build.zig.zon | feedback | |
| README.md | Allow start and stop to throw | |
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);