~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
118 lines · 4.6 KB Raw History
//! Fixed-window per-source-IP limiter for expensive status-page repo actions.
//! Semantics match upstream Jetstream V2's internal/web implementation.

const std = @import("std");

const Io = std.Io;
const Allocator = std.mem.Allocator;

pub const max_entries: usize = 4096;
pub const default_limit: usize = 4;
pub const default_window_us: i64 = std.time.us_per_min;

const Bucket = struct {
    window_start_us: ?i64 = null,
    last_seen_us: i64,
    used: usize = 0,
};

pub const Limiter = struct {
    mutex: Io.Mutex = .init,
    entries: std.StringHashMapUnmanaged(Bucket) = .empty,
    limit: usize = default_limit,
    window_us: i64 = default_window_us,

    pub fn deinit(self: *Limiter, allocator: Allocator) void {
        var it = self.entries.keyIterator();
        while (it.next()) |key| allocator.free(key.*);
        self.entries.deinit(allocator);
        self.* = .{};
    }

    pub fn allow(self: *Limiter, allocator: Allocator, io: Io, ip: []const u8, now_us: i64) !bool {
        self.mutex.lockUncancelable(io);
        defer self.mutex.unlock(io);

        if (self.entries.count() >= max_entries) self.pruneLocked(allocator, now_us);
        if (self.entries.count() >= max_entries) self.evictOldestLocked(allocator);

        const bucket = self.entries.getPtr(ip) orelse bucket: {
            const owned_ip = try allocator.dupe(u8, ip);
            errdefer allocator.free(owned_ip);
            try self.entries.put(allocator, owned_ip, .{ .last_seen_us = now_us });
            break :bucket self.entries.getPtr(owned_ip).?;
        };
        if (bucket.window_start_us == null or now_us - bucket.window_start_us.? >= self.window_us) {
            bucket.window_start_us = now_us;
            bucket.used = 0;
        }
        bucket.last_seen_us = now_us;
        if (bucket.used >= self.limit) return false;
        bucket.used += 1;
        return true;
    }

    fn pruneLocked(self: *Limiter, allocator: Allocator, now_us: i64) void {
        var it = self.entries.iterator();
        while (it.next()) |entry| {
            if (now_us - entry.value_ptr.last_seen_us < 2 * self.window_us) continue;
            const owned_ip = entry.key_ptr.*;
            _ = self.entries.remove(owned_ip);
            allocator.free(owned_ip);
            it = self.entries.iterator();
        }
    }

    fn evictOldestLocked(self: *Limiter, allocator: Allocator) void {
        var oldest_ip: ?[]const u8 = null;
        var oldest_seen: i64 = 0;
        var it = self.entries.iterator();
        while (it.next()) |entry| {
            if (oldest_ip == null or entry.value_ptr.last_seen_us < oldest_seen) {
                oldest_ip = entry.key_ptr.*;
                oldest_seen = entry.value_ptr.last_seen_us;
            }
        }
        if (oldest_ip) |ip| {
            _ = self.entries.remove(ip);
            allocator.free(ip);
        }
    }
};

test "repo action limiter matches upstream fixed-window behavior" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var limiter: Limiter = .{};
    defer limiter.deinit(testing.allocator);

    for (0..default_limit) |_| try testing.expect(try limiter.allow(testing.allocator, io, "203.0.113.10", 1));
    try testing.expect(!try limiter.allow(testing.allocator, io, "203.0.113.10", default_window_us - 1));
    try testing.expect(try limiter.allow(testing.allocator, io, "203.0.113.11", default_window_us - 1));
    try testing.expect(try limiter.allow(testing.allocator, io, "203.0.113.10", default_window_us + 1));
}

test "repo action limiter prunes stale entries and bounds cardinality" {
    const testing = std.testing;
    var threaded: Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const io = threaded.io();
    var limiter: Limiter = .{ .window_us = 1_000_000_000 };
    defer limiter.deinit(testing.allocator);

    var ip_buf: [64]u8 = undefined;
    for (0..max_entries) |index| {
        const ip = try std.fmt.bufPrint(&ip_buf, "source-{d}", .{index});
        try testing.expect(try limiter.allow(testing.allocator, io, ip, @intCast(index)));
    }
    try testing.expectEqual(max_entries, limiter.entries.count());
    try testing.expect(try limiter.allow(testing.allocator, io, "newest", @intCast(max_entries)));
    try testing.expectEqual(max_entries, limiter.entries.count());
    try testing.expect(!limiter.entries.contains("source-0"));

    limiter.window_us = 1;
    try testing.expect(try limiter.allow(testing.allocator, io, "after-prune", 2 * @as(i64, max_entries) + 10));
    try testing.expectEqual(@as(usize, 1), limiter.entries.count());
}