feat: refactor core+network+protocol: use platform abstractions,
transport vtable
This commit is contained in:
@@ -5,28 +5,29 @@
|
||||
|
||||
const std = @import("std");
|
||||
const mem = std.mem;
|
||||
const time = std.time;
|
||||
const platform_time = @import("time");
|
||||
const AtomicValue = @import("sync").AtomicValue;
|
||||
const log = @import("log.zig");
|
||||
|
||||
/// Token bucket rate limiter
|
||||
pub const RateLimiter = struct {
|
||||
/// Current number of tokens
|
||||
tokens: std.atomic.Value(u64),
|
||||
tokens: AtomicValue(u64),
|
||||
/// Maximum tokens (burst capacity)
|
||||
max_tokens: u64,
|
||||
/// Token refill rate (tokens per second)
|
||||
refill_rate: u64,
|
||||
/// Last refill timestamp (nanoseconds)
|
||||
last_refill: std.atomic.Value(i64),
|
||||
last_refill: AtomicValue(i64),
|
||||
/// Mutex for non-atomic operations
|
||||
mutex: std.Thread.Mutex = .{},
|
||||
|
||||
pub fn init(config: Config) RateLimiter {
|
||||
return .{
|
||||
.tokens = std.atomic.Value(u64).init(config.burst_size),
|
||||
.tokens = AtomicValue(u64).init(config.burst_size),
|
||||
.max_tokens = config.burst_size,
|
||||
.refill_rate = config.tokens_per_second,
|
||||
.last_refill = std.atomic.Value(i64).init(@intCast(time.nanoTimestamp())),
|
||||
.last_refill = AtomicValue(i64).init(@intCast(platform_time.nanoTimestamp())),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -79,7 +80,7 @@ pub const RateLimiter = struct {
|
||||
|
||||
/// Refill tokens based on elapsed time
|
||||
fn refill(self: *RateLimiter) void {
|
||||
const now: i64 = @intCast(time.nanoTimestamp());
|
||||
const now: i64 = @intCast(platform_time.nanoTimestamp());
|
||||
const last = self.last_refill.load(.acquire);
|
||||
const elapsed_ns = now - last;
|
||||
|
||||
@@ -87,7 +88,7 @@ pub const RateLimiter = struct {
|
||||
|
||||
// Calculate tokens to add (using nanoseconds for precision)
|
||||
const elapsed_ns_u64: u64 = @intCast(elapsed_ns);
|
||||
const elapsed_seconds = elapsed_ns_u64 / time.ns_per_s;
|
||||
const elapsed_seconds = elapsed_ns_u64 / 1_000_000_000;
|
||||
if (elapsed_seconds == 0) return;
|
||||
|
||||
const new_tokens = elapsed_seconds * self.refill_rate;
|
||||
@@ -238,7 +239,7 @@ pub const ConnectionRateLimiter = struct {
|
||||
return false;
|
||||
}
|
||||
|
||||
const now = std.time.timestamp();
|
||||
const now = platform_time.timestamp();
|
||||
|
||||
// Check per-IP rate limit
|
||||
self.mutex.lock();
|
||||
|
||||
Reference in New Issue
Block a user