summaryrefslogtreecommitdiff
path: root/src/bin/timeout.zig
blob: c811c1d778ba8422038d728d8db0d6096b630ec2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const std = @import("std");
const Io = std.Io;

pub const Limits = struct {
    greeting_s: i64 = 30,
    command_s: i64 = 300,
    data_s: i64 = 180,
    session_s: i64 = 1800,
};

pub const Watchdog = struct {
    deadline_ms: std.atomic.Value(i64),
    session_end_ms: i64,
    fired: std.atomic.Value(bool) = .init(false),

    pub fn init(io: Io, session_s: i64) Watchdog {
        const end = nowMs(io) + session_s * 1000;
        return .{ .session_end_ms = end, .deadline_ms = .init(end) };
    }

    pub fn nowMs(io: Io) i64 {
        return @intCast(@divFloor(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));
    }

    pub fn arm(self: *Watchdog, io: Io, secs: i64) void {
        self.deadline_ms.store(@min(nowMs(io) + secs * 1000, self.session_end_ms), .release);
    }

    /// Call as soon as a line arrives, so slow processing isn't mistaken for idleness.
    pub fn disarm(self: *Watchdog) void {
        self.deadline_ms.store(self.session_end_ms, .release);
    }

    pub fn run(self: *Watchdog, io: Io, stream: Io.net.Stream) void {
        const tick_ms = 500;
        while (true) {
            const now = nowMs(io);
            const dl = self.deadline_ms.load(.acquire);
            if (now >= dl) {
                self.fired.store(true, .release);
                stream.shutdown(io, .recv) catch {};
                return;
            }
            io.sleep(.fromMilliseconds(@min(dl - now, tick_ms)), .awake) catch return;
        }
    }
};