dotfiles/scripts/mzteinit/src/sock/Server.zig

62 lines
1.8 KiB
Zig
Raw Normal View History

2023-10-31 20:40:56 +01:00
const std = @import("std");
const message = @import("message.zig");
const Mutex = @import("../mutex.zig").Mutex;
2023-11-03 22:10:54 +01:00
const log = std.log.scoped(.server);
2023-10-31 20:40:56 +01:00
alloc: std.mem.Allocator,
env: *Mutex(std.process.EnvMap),
ss: std.net.StreamServer,
const Server = @This();
pub fn init(alloc: std.mem.Allocator, sockpath: []const u8, env: *Mutex(std.process.EnvMap)) !Server {
var ss = std.net.StreamServer.init(.{});
try ss.listen(try std.net.Address.initUnix(sockpath));
return .{ .alloc = alloc, .ss = ss, .env = env };
}
pub fn run(self: *Server) !void {
while (true) {
const con = try self.ss.accept();
errdefer con.stream.close();
(try std.Thread.spawn(.{}, handleConnection, .{ self, con })).detach();
}
}
pub fn handleConnection(self: *Server, con: std.net.StreamServer.Connection) !void {
2023-11-03 22:10:54 +01:00
defer con.stream.close();
2023-10-31 20:40:56 +01:00
while (true) {
2023-11-03 22:10:54 +01:00
const msg = message.Serverbound.read(con.stream.reader(), self.alloc) catch |e| {
2023-10-31 20:40:56 +01:00
switch (e) {
2023-11-03 22:10:54 +01:00
error.EndOfStream => return,
2023-10-31 20:40:56 +01:00
else => return e,
}
};
2023-11-03 22:10:54 +01:00
defer msg.deinit(self.alloc);
2023-10-31 20:40:56 +01:00
switch (msg) {
2023-11-03 22:10:54 +01:00
.ping => {
log.info("got ping!", .{});
try (message.Clientbound{ .pong = .{} }).write(con.stream.writer());
},
2023-10-31 20:40:56 +01:00
.getenv => |key| {
self.env.mtx.lock();
defer self.env.mtx.unlock();
2023-11-03 22:10:54 +01:00
log.info("env var '{s}' requested", .{key.data});
const payload = message.Clientbound{ .getenv_res = .{
.inner = if (self.env.data.get(key.data)) |v|
.{ .data = v }
else
null,
} };
try payload.write(con.stream.writer());
2023-10-31 20:40:56 +01:00
},
}
}
}