robin/maivi

a tiny cute lua web framework

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

robinmaivi: proper io usage6e07b35

main
4.4 KiB165 linesraw
1const std = @import("std");
2const http = std.http;
3const Request = http.Server.Request;
4
5const fern = @import("fern");
6const httpz = @import("httpz");
7const zlua = @import("zlua");
8const Lua = zlua.Lua;
9
10const fragment = @import("fragment.zig");
11const handler = @import("handler.zig");
12const Connection = handler.Connection;
13const helpers = @import("helpers.zig");
14const maivi = @import("root.zig");
15
16const Self = @This();
17
18pub const Path = struct {
19    action: Action,
20    config: Config,
21
22    pub fn init(action: Action, cfg: ?Config) Path {
23        return .{ .action = action, .config = cfg orelse .{} };
24    }
25
26    pub const Action = *const fn (conn: *Connection) anyerror!void;
27    pub const Config = struct {
28        allowed_methods: []const http.Method = &.{.GET},
29    };
30    // pub const Error = error{} || Request.ExpectContinueError;
31};
32
33pub const LuaPath = struct {
34    f: i32,
35    props: i32,
36};
37
38paths: std.hash_map.StringHashMap(Path),
39luapaths: std.hash_map.StringHashMap(LuaPath),
40
41pub fn init() Self {
42    return .{
43        .paths = .init(maivi.allocator),
44        .luapaths = .init(maivi.allocator),
45    };
46}
47
48pub fn deinit(self: *Self) void {
49    self.paths.deinit();
50    self.luapaths.deinit();
51}
52
53pub fn add(self: *Self, path: []const u8, action: Path.Action, cfg: ?Path.Config) !void {
54    fern.debug().ctx("router").msg("adding router path").str("path", path).log();
55    return try self.paths.put(path, .init(action, cfg));
56}
57
58// lua ========================================================================
59
60pub fn lua_openrouter(l: *Lua) !i32 {
61    l.createTable(0, 1);
62
63    l.pushFunction(zlua.wrap(lua_add));
64    l.setField(-2, "add");
65
66    return 1;
67}
68
69fn lua_add(l: *Lua) !i32 {
70    fern.trace().ctx("router").msg("lua_add").log();
71
72    l.argCheck(l.isTable(1), 1, "table");
73    l.argCheck(l.isString(2), 2, "string");
74    l.argCheck(l.isFunction(3), 3, "function");
75    const noprops = l.getTop() < 4 or l.isNil(4);
76    l.argCheck(noprops or l.isTable(4), 4, "table?");
77    // stack: -1 => props -2 => function -3 => string -4 => router (empty table)
78
79    const path = try l.toString(2);
80
81    const f = maivi.lua.toRef(l, 3);
82
83    const props = blk: {
84        if (noprops)
85            l.newTable()
86        else
87            l.pushValue(-1);
88
89        // set props.url
90        _ = l.pushString(path);
91        l.setField(-2, "url");
92
93        break :blk maivi.lua.toRef(l, null);
94    };
95
96    try maivi.router.add(path, handle_lua, .{});
97
98    if (maivi.router.luapaths.contains(path)) return error.Clobber;
99    try maivi.router.luapaths.put(path, .{
100        .f = f,
101        .props = props,
102    });
103
104    return 0;
105}
106
107// TODO:
108// - set content
109// - caching?
110pub fn handle_lua(conn: *Connection) !void {
111    const request = conn.request;
112
113    const content_type = helpers.content_type_for_file(conn.path) orelse .html;
114
115    var wbuf: [0x4000]u8 = undefined;
116    var b = try maivi.helpers.respond(request, &wbuf, .{
117        // .content_length = size,
118        .content_type = content_type,
119    });
120
121    const data = maivi.router.luapaths.get(conn.path) orelse return error.FileNotFound;
122    try get(conn.lua, conn, &b.writer, data);
123    try b.end();
124}
125
126pub fn get(l: *Lua, conn: *Connection, writer: *std.Io.Writer, data: LuaPath) !void {
127    // call handler function
128    _ = l.getIndexRaw(zlua.registry_index, data.f);
129    if (!l.isFunction(-1)) return error.LuaValueNotAFunction;
130    _ = l.getIndexRaw(zlua.registry_index, data.props);
131    if (!l.isTable(-1)) return error.LuaValueNotATable;
132
133    // read content
134    try blk: {
135        // stack: -1 => getIndexRaw(props)
136        const stack_size_on_entry = l.getTop();
137        const filepath = filepath: {
138            const ltype_path = l.getField(-1, "path");
139            defer l.pop(1); // pops "path"
140            if (ltype_path != .string) break :blk;
141            break :filepath try l.toString(-1);
142        };
143
144        try maivi.lua.read_data(l, conn.io, filepath);
145        l.setField(-2, "content");
146
147        if (l.getTop() != stack_size_on_entry) break :blk error.UnexpectedStackSize;
148    };
149
150    // prepare ctx
151    try blk: {
152        // stack: -1 => getIndexRaw(props)
153        const stack_size_on_entry = l.getTop();
154        try maivi.lua.pushCtx(l, Connection, conn);
155        l.pushValue(-3);
156        l.setField(-2, "props");
157        l.setGlobal("ctx");
158
159        if (l.getTop() != stack_size_on_entry) break :blk error.UnexpectedStackSize;
160    };
161
162    try maivi.lua.pcall(l, .{ .args = 1, .results = 1 });
163
164    try fragment.render(l, writer);
165}