robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinmaivi: proper io usage6e07b35

main
4.9 KiB190 linesraw
1const std = @import("std");
2const Io = std.Io;
3const Allocator = std.mem.Allocator;
4const http = std.http;
5const Request = http.Server.Request;
6const net = Io.net;
7const Server = net.Server;
8
9const fern = @import("fern");
10
11pub const Config = @import("config.zig");
12pub const data = @import("data.zig");
13pub const gen = @import("gen.zig");
14pub const handler = @import("handler.zig");
15const Connection = handler.Connection;
16pub const helpers = @import("helpers.zig");
17pub const lua = @import("lua/root.zig");
18pub const Router = @import("router.zig");
19
20pub var build: bool = false;
21pub var dev: bool = false;
22pub var rev: ?[]const u8 = null; // null indicates a dev build
23
24pub var config: *const Config = undefined;
25
26var socket_io: Io = undefined;
27var addr: net.IpAddress = undefined;
28pub var nserver: ?Server = null;
29var closed = false;
30
31pub var router: Router = undefined;
32
33// allocator ==================================================================
34
35pub var allocator: Allocator = undefined;
36
37pub fn init(io: Io, init_allocator: Allocator, cfg: *const Config) !void {
38    allocator = init_allocator;
39
40    config = cfg;
41
42    fern.debug().ctx("maivi.init")
43        .str("root", config.root)
44        .str("base_url", config.base_url)
45        .boolean("dev", dev)
46        .log();
47
48    router = .init();
49
50    data.init();
51    errdefer data.deinit();
52
53    try lua.init();
54    errdefer lua.deinit();
55
56    try data.load(io);
57}
58
59pub fn deinit(io: Io) void {
60    fern.trace().ctx("maivi.deinit").log();
61
62    router.deinit();
63
64    data.deinit();
65    lua.deinit();
66
67    if (nserver == null) return;
68    nserver.?.deinit(io);
69}
70
71// io handle will be used for all net handling
72pub fn server(io: Io) !void {
73    socket_io = io;
74    addr = try .resolve(socket_io, "127.0.0.1", config.port);
75    nserver = try addr.listen(socket_io, .{ .reuse_address = true });
76}
77
78fn shutdown(signo: std.os.linux.SIG) callconv(.c) void {
79    fern.info().ctx("main")
80        .fmt("sig", "{}", .{signo}).log();
81
82    if (nserver == null) return;
83    closed = true;
84    socket_io.vtable.netShutdown(socket_io.userdata, nserver.?.socket.handle, .recv) catch |e|
85        fern.err().err(e).log();
86}
87
88pub fn listen(io: Io) !void {
89    if (nserver == null) return error.ServerNotInitialized;
90
91    fern.info().ctx("maivi.listen")
92        .msg("listening")
93        .int("port", config.port)
94        .int("pid", std.c.getpid())
95        .log();
96
97    std.posix.sigaction(std.posix.SIG.INT, &.{
98        .handler = .{ .handler = shutdown },
99        .mask = std.posix.sigemptyset(),
100        .flags = 0,
101    }, null);
102    std.posix.sigaction(std.posix.SIG.TERM, &.{
103        .handler = .{ .handler = shutdown },
104        .mask = std.posix.sigemptyset(),
105        .flags = 0,
106    }, null);
107
108    var queue: Io.Queue(net.Stream) = .init(&.{});
109    var task = Io.async(io, consume, .{ io, &queue });
110    defer task.cancel(io) catch |e| {
111        fern.err().err(e).log();
112    };
113
114    while (!closed) {
115        const stream = nserver.?.accept(io) catch |e| {
116            fern.err().err(e).log();
117            continue;
118        };
119        queue.putOne(io, stream) catch |e| {
120            fern.err().err(e).log();
121            continue;
122        };
123    }
124}
125
126pub fn consume(io: Io, queue: *Io.Queue(net.Stream)) !void {
127    while (!closed) {
128        const stream = try queue.getOne(io);
129        handler.task(io, stream) catch |e| {
130            fern.err().err(e).log();
131            continue;
132        };
133    }
134}
135
136// handlers ===================================================================
137
138// try:
139//   with(router) $uri
140//   else:
141//     with(build) $uri $uri/index.html
142//     with(static) $uri
143pub fn handle(conn: *Connection) !void {
144    const request = conn.request;
145
146    try lua.trigger(conn.lua, Connection, conn, .handle, .{
147        .path = conn.path,
148        .pattern = conn.path,
149    });
150    if (conn.fallen) return;
151
152    const path = router.paths.get(conn.path) orelse return handle_fs(conn);
153
154    if (std.mem.findScalar(
155        std.http.Method,
156        path.config.allowed_methods,
157        request.head.method,
158    ) == null) return request.respond("", .{
159        .status = .method_not_allowed,
160    });
161
162    try path.action(conn);
163
164    // TODO: pre-register all static & build paths
165    // if (dev)
166    //   try handle_fs(request);
167}
168
169fn handle_fs(conn: *Connection) !void {
170    const build_dir = try Io.Dir.openDirAbsolute(conn.io, config.buildroot, .{});
171    defer build_dir.close(conn.io);
172
173    if (std.mem.eql(u8, conn.path, "/")) {
174        if (try helpers.try_path(conn, build_dir, "/index.html")) return;
175        return error.FileNotFound;
176    }
177
178    if (try helpers.try_path(conn, build_dir, null)) return;
179
180    const path = try std.mem.join(allocator, "/", &.{ conn.path, "index.html" });
181    defer allocator.free(path);
182    if (try helpers.try_path(conn, build_dir, path)) return;
183
184    const static_dir = try Io.Dir.openDirAbsolute(conn.io, config.staticroot, .{});
185    defer static_dir.close(conn.io);
186
187    if (try helpers.try_path(conn, static_dir, null)) return;
188
189    return error.FileNotFound;
190}