robin/maivi

a tiny cute lua web framework

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

robinmaivi: proper io usage6e07b35

push-srxvuswpkqxx
5.9 KiB194 linesraw
1const std = @import("std");
2const Io = std.Io;
3const http = std.http;
4const Request = http.Server.Request;
5
6const fern = @import("fern");
7
8const helpers = @import("helpers.zig");
9const maivi = @import("root.zig");
10const Lua = maivi.lua.Lua;
11
12pub fn task(io: Io, stream: Io.net.Stream) error{Canceled}!void {
13    defer stream.close(io);
14
15    var arena: std.heap.ArenaAllocator = .init(maivi.allocator);
16    defer arena.deinit();
17    const allocator = arena.allocator();
18
19    var recv_buffer: [0x1000]u8 = undefined;
20    var send_buffer: [0x1000]u8 = undefined;
21
22    var connection_reader = stream.reader(io, &recv_buffer);
23    var connection_writer = stream.writer(io, &send_buffer);
24
25    var server: std.http.Server = .init(&connection_reader.interface, &connection_writer.interface);
26
27    var request = server.receiveHead() catch return;
28
29    const ret = blk: {
30        const path = helpers.sanitize(allocator, request.head.target) catch |err| switch (err) {
31            error.TrailingSlash => return {
32                _ = helpers.redirect(
33                    allocator,
34                    &request,
35                    request.head.target[0 .. request.head.target.len - 1],
36                    .temporary_redirect,
37                ) catch |e| break :blk e;
38            },
39            else => break :blk err,
40        };
41        var conn: Connection = .{
42            .request = &request,
43            .io = io,
44            .handle = stream.socket.handle,
45            .path = path,
46            .arena = allocator,
47            .lua = maivi.lua.thread(),
48        };
49        const timer = Io.Timestamp.now(io, .cpu_thread);
50        defer {
51            const elapsed = Io.Timestamp.durationTo(timer, Io.Timestamp.now(io, .cpu_thread)).toMilliseconds();
52            fern.debug().ctx("handler.dispatch")
53                .msg("response")
54                .str("path", conn.path)
55                .int("elapsed", elapsed).log();
56        }
57        dispatch(&conn) catch |e| break :blk e;
58    };
59    ret catch |e| {
60        fern.err().ctx("handler.task").err(e).log();
61        return error.Canceled;
62    };
63}
64
65pub const Connection = struct {
66    request: *Request,
67    io: Io,
68    handle: Io.net.Socket.Handle,
69    path: []const u8,
70    arena: std.mem.Allocator,
71    lua: *Lua,
72    fallen: bool = false,
73    ref: ?i32 = null, // reusable lua ref for hooks
74
75    pub fn toLua(self: @This(), l: *Lua) !void {
76        // { path = ..., req = ... }
77        l.createTable(0, 2);
78
79        {
80            // path
81            _ = l.pushString(self.path);
82            l.setField(-2, "path");
83        }
84
85        {
86            // request ============================================================
87            // { headers = ..., head = ... }
88            l.createTable(0, 2);
89
90            {
91                // headers
92                l.newTable();
93                var it = self.request.iterateHeaders();
94                while (it.next()) |header| {
95                    _ = l.pushString(header.name);
96                    _ = l.pushString(header.value);
97                    l.setTable(-3); // header
98                }
99
100                l.setField(-2, "headers");
101            }
102
103            {
104                // head
105                try l.pushAny(self.request.head);
106                l.setField(-2, "head");
107            }
108
109            l.setField(-2, "request");
110        }
111
112        // metatable
113        try maivi.lua.setMethodTable(l, MT);
114    }
115
116    const MT = struct {
117        pub fn redirect(l: *Lua) !i32 {
118            l.argCheck(l.isTable(1), 1, "ctx");
119            l.argCheck(l.isString(2), 2, "string");
120            l.argCheck(l.isNil(3) or l.isNumber(3), 3, "optional number");
121            // -1 => code, -2 => uri, -3 => ctx
122
123            const conn = blk: {
124                const ltype_ptr = l.getField(1, "ptr");
125                defer l.pop(1);
126                if (ltype_ptr != .light_userdata) return error.InvalidPtr;
127                break :blk try l.toUserdata(Connection, -1);
128            };
129
130            const uri = try l.toString(2);
131
132            const code: ?http.Status = if (l.getTop() == 3 and !l.isNil(3))
133                @enumFromInt(try l.toNumeric(u10, 3))
134            else
135                null;
136
137            _ = try helpers.redirect(conn.arena, conn.request, uri, code);
138            conn.fallen = true;
139
140            return 0;
141        }
142    };
143};
144
145pub fn dispatch(conn: *Connection) !void {
146    const request = conn.request;
147
148    var l = fern.debug().ctx("handler.dispatch")
149        .msg("request")
150        .fmt("method", "{}", .{request.head.method})
151        .str("path", conn.path);
152    var it = request.iterateHeaders();
153    while (it.next()) |header| l = l.str(header.name, header.value);
154    l.log();
155
156    maivi.handle(conn) catch |e| switch (e) {
157        error.FileNotFound => try returnNotFound(conn),
158        else => try returnInternalErr(request, e),
159    };
160}
161
162const NOTFOUND_MSG = "path not found :(";
163const INTERNALERR_MSG = "internal server error x_x";
164
165fn returnNotFound(conn: *Connection) !void {
166    withNotFound(conn, "/404.html") catch |err| switch (err) {
167        error.IsDirectory => return withNotFound(conn, "/404/index.html") catch |e| switch (e) {
168            error.FileNotFound => return try respondNotFound(conn),
169            else => return try returnInternalErr(conn.request, err),
170        },
171        error.FileNotFound => return try respondNotFound(conn),
172        else => return try returnInternalErr(conn.request, err),
173    };
174}
175
176fn withNotFound(conn: *Connection, try_path: []const u8) !void {
177    const dir = try Io.Dir.openDirAbsolute(conn.io, maivi.config.buildroot, .{});
178    defer dir.close(conn.io);
179    try helpers.sendfile(conn, dir, try_path);
180}
181
182inline fn respondNotFound(conn: *Connection) !void {
183    try conn.request.respond(NOTFOUND_MSG, .{
184        .status = .not_found,
185    });
186}
187
188fn returnInternalErr(request: *Request, err: anyerror) !void {
189    fern.err().err(err).log();
190    const status = helpers.statusFromErr(err) orelse return err;
191    try request.respond(INTERNALERR_MSG, .{
192        .status = status,
193    });
194}