tcp: use unix:// or tcp:// as config values for tcp binding

This commit is contained in:
Aarnav Tale
2024-04-20 19:33:44 -04:00
parent 545844ecf8
commit 26935db97b
2 changed files with 13 additions and 36 deletions

View File

@ -58,36 +58,6 @@ pub fn init(
};
}
const BindError = error{
NoAddress,
InvalidAddress,
};
/// Tries to generate a valid address to bind to
/// TODO: Maybe unix sockets should start with unix://
pub fn parseAddress(raw_addr: ?[:0]const u8) BindError!std.net.Address {
const addr = raw_addr orelse {
return BindError.NoAddress;
};
if (addr.len == 0) {
return BindError.NoAddress;
}
var iter = std.mem.splitScalar(u8, addr, ':');
const host = iter.next() orelse return BindError.InvalidAddress;
const port = iter.next() orelse return BindError.InvalidAddress;
const numPort = std.fmt.parseInt(u16, port, 10) catch {
return std.net.Address.initUnix(addr) catch BindError.InvalidAddress;
};
const ip = std.net.Address.parseIp4(host, numPort) catch {
return std.net.Address.initUnix(addr) catch BindError.InvalidAddress;
};
return ip;
}
/// Deinitializes the server
pub fn deinit(self: *Server) void {
log.info("shutting down server", .{});

View File

@ -14,7 +14,7 @@ const log = std.log.scoped(.tcp_thread);
alloc: std.mem.Allocator,
/// The TCP server for handling incoming connections.
server: tcp.Server,
server: ?tcp.Server,
/// Initialize the thread. This does not START the thread. This only sets
/// up all the internal state necessary prior to starting the thread. It
@ -26,7 +26,10 @@ pub fn init(alloc: Allocator) !Thread {
const parsedAddr = tcp.Server.parseAddress(addr) catch |err| {
log.err("failed to parse address addr={any} err={any}", .{ addr, err });
return err;
return Thread{
.alloc = alloc,
.server = undefined,
};
};
log.debug("parsed address addr={any}", .{parsedAddr});
@ -42,7 +45,9 @@ pub fn init(alloc: Allocator) !Thread {
/// Clean up the thread. This is only safe to call once the thread
/// completes executing; the caller must join prior to this.
pub fn deinit(self: *Thread) void {
self.server.deinit();
if (self.server) |*server| {
server.deinit();
}
}
/// The main entrypoint for the thread.
@ -53,7 +58,9 @@ pub fn threadMain(self: *Thread) void {
}
fn threadMain_(self: *Thread) !void {
if (self.server) |*server| {
log.debug("starting tcp thread", .{});
try self.server.start();
errdefer log.debug("tcp thread exited", .{});
defer log.debug("tcp thread exited", .{});
try server.start();
}
}