search for standard sites pub-search.waow.tech
search zig blog atproto
at multi-platform-schema 72 lines 2.2 kB view raw
1const std = @import("std"); 2const net = std.net; 3const posix = std.posix; 4const Thread = std.Thread; 5const db = @import("db/mod.zig"); 6const activity = @import("activity.zig"); 7const server = @import("server.zig"); 8const tap = @import("tap.zig"); 9 10const MAX_HTTP_WORKERS = 16; 11const SOCKET_TIMEOUT_SECS = 30; 12 13pub fn main() !void { 14 var gpa = std.heap.GeneralPurposeAllocator(.{}){}; 15 defer _ = gpa.deinit(); 16 const allocator = gpa.allocator(); 17 18 // init turso 19 try db.init(); 20 21 // start activity tracker 22 activity.init(); 23 24 // start tap consumer in background 25 const tap_thread = try Thread.spawn(.{}, tap.consumer, .{allocator}); 26 defer tap_thread.join(); 27 28 // init thread pool for http connections 29 var pool: Thread.Pool = undefined; 30 try pool.init(.{ 31 .allocator = allocator, 32 .n_jobs = MAX_HTTP_WORKERS, 33 }); 34 defer pool.deinit(); 35 36 // start http server 37 const port: u16 = blk: { 38 const port_str = posix.getenv("PORT") orelse "3000"; 39 break :blk std.fmt.parseInt(u16, port_str, 10) catch 3000; 40 }; 41 42 const address = try net.Address.parseIp("0.0.0.0", port); 43 var listener = try address.listen(.{ .reuse_address = true }); 44 defer listener.deinit(); 45 46 std.debug.print("leaflet-search listening on http://0.0.0.0:{d} (max {} workers)\n", .{ port, MAX_HTTP_WORKERS }); 47 48 while (true) { 49 const conn = listener.accept() catch |err| { 50 std.debug.print("accept error: {}\n", .{err}); 51 continue; 52 }; 53 54 setSocketTimeout(conn.stream.handle, SOCKET_TIMEOUT_SECS) catch |err| { 55 std.debug.print("failed to set socket timeout: {}\n", .{err}); 56 }; 57 58 pool.spawn(server.handleConnection, .{conn}) catch |err| { 59 std.debug.print("pool spawn error: {}\n", .{err}); 60 conn.stream.close(); 61 }; 62 } 63} 64 65fn setSocketTimeout(fd: posix.fd_t, secs: u32) !void { 66 const timeout = std.mem.toBytes(posix.timeval{ 67 .sec = @intCast(secs), 68 .usec = 0, 69 }); 70 try posix.setsockopt(fd, posix.SOL.SOCKET, posix.SO.RCVTIMEO, &timeout); 71 try posix.setsockopt(fd, posix.SOL.SOCKET, posix.SO.SNDTIMEO, &timeout); 72}