╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const ui = @import("./ui.zig"); 5 const pg = @import("./page.zig"); 6 7 const Asset = struct { 8 path: []const u8, 9 content_type: []const u8, 10 body: []const u8, 11 }; 12 13 const assets = [_]Asset{ 14 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("assets/index.html") }, 15 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("assets/script.js") }, 16 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("assets/term.ttf") }, 17 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("assets/haxy.wasm") }, 18 }; 19 20 pub fn run( 21 io: std.Io, 22 allocator: std.mem.Allocator, 23 net_server: *std.Io.net.Server, 24 tasks: *std.Io.Group, 25 admin_repo_path: []const u8, 26 err: *std.Io.Writer, 27 ) void { 28 const Listener = struct { 29 io: std.Io, 30 allocator: std.mem.Allocator, 31 net_server: *std.Io.net.Server, 32 tasks: *std.Io.Group, 33 admin_repo_path: []const u8, 34 err: *std.Io.Writer, 35 36 fn run(ctx: @This()) void { 37 while (true) { 38 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 39 if (accept_err == error.Canceled) return; 40 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 41 continue; 42 }; 43 44 const Connection = struct { 45 io: std.Io, 46 allocator: std.mem.Allocator, 47 stream: std.Io.net.Stream, 48 admin_repo_path: []const u8, 49 err: *std.Io.Writer, 50 51 fn run(conn: @This()) void { 52 defer conn.stream.close(conn.io); 53 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.err) catch |request_err| { 54 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 55 }; 56 } 57 }; 58 59 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 60 .io = ctx.io, 61 .allocator = ctx.allocator, 62 .stream = stream, 63 .admin_repo_path = ctx.admin_repo_path, 64 .err = ctx.err, 65 }}); 66 } 67 } 68 }; 69 70 tasks.async(io, Listener.run, .{Listener{ 71 .io = io, 72 .allocator = allocator, 73 .net_server = net_server, 74 .tasks = tasks, 75 .admin_repo_path = admin_repo_path, 76 .err = err, 77 }}); 78 } 79 80 fn renderIndexHtml(io: std.Io, allocator: std.mem.Allocator, admin_repo_path: []const u8) ![]const u8 { 81 const template = (findAsset("/index.html") orelse return error.MissingIndexAsset).body; 82 83 // open the admin repo to read live user/repo data; if it doesn't exist 84 // yet (e.g. a fresh `haxy serve` with no admin repo) fall back to empty. 85 const repo_opts: rp.RepoOpts(.xit) = .{}; 86 const Repo = rp.Repo(.xit, repo_opts); 87 var repo_or_err = Repo.open(io, allocator, .{ .path = admin_repo_path }); 88 var page_arena = std.heap.ArenaAllocator.init(allocator); 89 defer page_arena.deinit(); 90 const page: pg.Page = if (repo_or_err) |*repo| blk: { 91 defer repo.deinit(io, allocator); 92 break :blk .{ .user_repo = try .init(repo_opts, &page_arena, repo) }; 93 } else |_| .{ .user_repo = .empty() }; 94 95 var root = try ui.initRoot(allocator, &page); 96 defer root.deinit(); 97 98 const content = try ui.generateHtml(allocator, &root); 99 defer allocator.free(content); 100 101 // serialize the page so the wasm side can parse it back without making 102 // a second request. base64-encoded so the json can be embedded in html. 103 var json: std.Io.Writer.Allocating = .init(allocator); 104 defer json.deinit(); 105 try std.json.Stringify.value(page, .{}, &json.writer); 106 107 const b64 = std.base64.standard.Encoder; 108 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 109 defer allocator.free(json_b64); 110 _ = b64.encode(json_b64, json.written()); 111 112 var out: std.ArrayList(u8) = .empty; 113 errdefer out.deinit(allocator); 114 { 115 var cursor: usize = 0; 116 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 117 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 118 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 119 }) |sub| { 120 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 121 try out.appendSlice(allocator, template[cursor..idx]); 122 try out.appendSlice(allocator, sub.replacement); 123 cursor = idx + sub.needle.len; 124 } 125 try out.appendSlice(allocator, template[cursor..]); 126 } 127 return try out.toOwnedSlice(allocator); 128 } 129 130 fn handleConnection( 131 io: std.Io, 132 allocator: std.mem.Allocator, 133 stream: std.Io.net.Stream, 134 admin_repo_path: []const u8, 135 err: *std.Io.Writer, 136 ) !void { 137 var send_buffer = [_]u8{0} ** 4096; 138 var recv_buffer = [_]u8{0} ** 4096; 139 var conn_br = stream.reader(io, &recv_buffer); 140 var conn_bw = stream.writer(io, &send_buffer); 141 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 142 143 while (http_server.reader.state == .ready) { 144 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 145 error.HttpConnectionClosing => break, 146 error.ReadFailed => break, 147 else => |e| return e, 148 }; 149 150 handleRequest(io, &http_server, &request, allocator, admin_repo_path) catch |request_err| { 151 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 152 try err.flush(); 153 if (http_server.reader.state == .received_head) { 154 http_server.reader.state = .ready; 155 } 156 try writeSimpleResponse(&http_server, 500, "Internal Server Error", "text/plain", @errorName(request_err)); 157 }; 158 try http_server.out.flush(); 159 break; 160 } 161 } 162 163 fn handleRequest( 164 io: std.Io, 165 http_server: *std.http.Server, 166 request: *std.http.Server.Request, 167 allocator: std.mem.Allocator, 168 admin_repo_path: []const u8, 169 ) !void { 170 const method = if (request.head.method == .HEAD) .GET else request.head.method; 171 if (method != .GET) { 172 if (http_server.reader.state == .received_head) { 173 http_server.reader.state = .ready; 174 } 175 try writeSimpleResponse(http_server, 405, "Method Not Allowed", "text/plain", "method not allowed"); 176 return; 177 } 178 179 const uri = try std.Uri.parseAfterScheme("", request.head.target); 180 const path = uri.path.percent_encoded; 181 182 if (std.mem.eql(u8, path, "/favicon.ico")) { 183 if (http_server.reader.state == .received_head) { 184 http_server.reader.state = .ready; 185 } 186 try writeStaticResponse(http_server, 204, "No Content", "image/x-icon", "", true); 187 return; 188 } 189 190 const asset = findAsset(path) orelse { 191 if (http_server.reader.state == .received_head) { 192 http_server.reader.state = .ready; 193 } 194 try writeSimpleResponse(http_server, 404, "Not Found", "text/plain", "not found"); 195 return; 196 }; 197 198 if (http_server.reader.state == .received_head) { 199 http_server.reader.state = .ready; 200 } 201 202 if (std.mem.eql(u8, asset.path, "index.html")) { 203 const index_html = try renderIndexHtml(io, allocator, admin_repo_path); 204 defer allocator.free(index_html); 205 try writeStaticResponse(http_server, 200, "OK", asset.content_type, index_html, request.head.method == .HEAD); 206 } else { 207 try writeStaticResponse(http_server, 200, "OK", asset.content_type, asset.body, request.head.method == .HEAD); 208 } 209 } 210 211 fn findAsset(request_path: []const u8) ?Asset { 212 const path = if (std.mem.eql(u8, request_path, "/")) 213 "index.html" 214 else if (request_path.len > 1 and request_path[0] == '/') 215 request_path[1..] 216 else 217 return null; 218 219 for (assets) |asset| { 220 if (std.mem.eql(u8, path, asset.path)) return asset; 221 } 222 return null; 223 } 224 225 fn writeSimpleResponse( 226 http_server: *std.http.Server, 227 code: u16, 228 message: []const u8, 229 content_type: []const u8, 230 body: []const u8, 231 ) !void { 232 try http_server.out.print( 233 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n{s}", 234 .{ code, message, content_type, body.len, body }, 235 ); 236 } 237 238 fn writeStaticResponse( 239 http_server: *std.http.Server, 240 code: u16, 241 message: []const u8, 242 content_type: []const u8, 243 body: []const u8, 244 head_only: bool, 245 ) !void { 246 try http_server.out.print( 247 "HTTP/1.1 {d} {s}\r\nContent-Type: {s}\r\nContent-Length: {d}\r\n\r\n", 248 .{ code, message, content_type, body.len }, 249 ); 250 if (!head_only) { 251 try http_server.out.writeAll(body); 252 } 253 } 254 255 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 256 err.print(fmt, args) catch return; 257 err.flush() catch {}; 258 } 259