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

64 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),
2024-03-09 19:37:52 +01:00
ss: std.net.Server,
2023-10-31 20:40:56 +01:00
const Server = @This();
pub fn init(alloc: std.mem.Allocator, sockpath: []const u8, env: *Mutex(std.process.EnvMap)) !Server {
2024-03-09 19:37:52 +01:00
return .{
.alloc = alloc,
.ss = try (try std.net.Address.initUnix(sockpath)).listen(.{}),
.env = env,
};
2023-10-31 20:40:56 +01:00
}
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();
}
}
2024-03-09 19:37:52 +01:00
pub fn handleConnection(self: *Server, con: std.net.Server.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
},
}
}
}