-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.zig
More file actions
3191 lines (3064 loc) · 147 KB
/
Copy pathserver.zig
File metadata and controls
3191 lines (3064 loc) · 147 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const c = std.c;
const builtin = @import("builtin");
const windows = std.os.windows;
const win32 = struct {
extern "kernel32" fn CreateEventW(?*anyopaque, i32, i32, ?[*:0]const u16) callconv(.winapi) ?windows.HANDLE;
extern "kernel32" fn SetEvent(windows.HANDLE) callconv(.winapi) i32;
extern "kernel32" fn WaitForSingleObject(windows.HANDLE, u32) callconv(.winapi) u32;
extern "kernel32" fn Sleep(u32) callconv(.winapi) void;
extern "kernel32" fn GetCurrentProcess() callconv(.winapi) windows.HANDLE;
extern "kernel32" fn TerminateProcess(windows.HANDLE, u32) callconv(.winapi) i32;
};
const assert = std.debug.assert;
const transport = @import("transport.zig");
const http = @import("http.zig");
const HandoffSocket = if (builtin.os.tag == .windows) @import("transport_windows.zig").DetachedSocket else usize;
const AcceptedSocket = struct { socket: HandoffSocket, accepted_at: u64 };
const HandoffQueue = @import("handoff.zig").Queue(AcceptedSocket);
pub const api = @import("api.zig");
pub const Budget = @import("budget.zig").Budget;
pub const backend_name = transport.name;
/// Inline handlers execute on the sole I/O owner and must be bounded and
/// nonblocking. The framework cannot preempt or isolate a violating callback.
/// Inline mode is the default and reserves no application threads. Applications
/// with blocking callbacks explicitly select the fixed worker execution mode.
pub const Execution = enum { workers, inline_event_loop };
pub const Config = struct {
execution: Execution = .inline_event_loop,
gather_send: bool = true,
/// Finished responses retained per connection before a drain; each is a
/// range of the connection's output arena plus an optional borrowed span.
response_batch_limit: u16 = 128,
port: u16 = 8080,
connections: u16 = 128,
workers: u16 = 0,
max_body: u32 = 65536,
max_header: u32 = 16384,
max_headers: u16 = 64,
/// Contiguous output arena per connection: response heads, generated
/// bodies, chunk framing and copied small borrows of one batch.
output_bytes: u32 = 65536,
/// Free output required before initial callback dispatch. The low-level
/// default reserves a head; one-shot applications reserve their full draft
/// so earlier batched output drains before application side effects run.
callback_output_reserve: u32 = api.header_reserve_bytes,
/// Borrowed spans up to this size are copied into the arena; 0 disables.
borrow_copy_threshold: u32 = 256,
/// Inline callbacks per event-loop turn; 0 selects connections × batch
/// limit, capped. Reported in Stats.
callbacks_per_turn: u32 = 0,
/// Exact per-callback queue/handler timing costs two clock reads each.
callback_timing: bool = false,
/// Interval of the full deadline sweep; touched slots are checked sooner.
deadline_sweep_ms: u32 = 100,
/// Submit queued sends after this many drains within a turn so responses
/// leave before the turn ends; 0 submits only when the turn polls. Measured
/// on omarx1 (2026-09-05): no throughput change at any depth, more CPU.
submit_batch: u16 = 0,
/// Arm the next receive while a batch is still being sent. Measured
/// 2026-09-05: no change on io_uring, 6-16% slower on kqueue where the
/// early receive costs two syscalls that find no data yet. Off by default.
prearm_receive: bool = false,
/// I/O owners. 0 selects one per allowed CPU on Linux and 1 elsewhere.
shards: u8 = 0,
/// Pin shard i to the i-th CPU the process may use (Linux only).
shard_affinity: bool = false,
max_response_bytes: usize = 16 * 1024 * 1024,
timeout_ms: u32 = 5000,
shutdown_ms: u32 = 5000,
duration_ms: u32 = 0,
send_chunk: u32 = 65536,
socket_send_buffer_bytes: u32 = 65536,
worker_stack_bytes: usize = 1024 * 1024,
memory_budget_bytes: usize = 512 * 1024 * 1024,
/// Set by the cluster for every shard beyond the first; never by users.
reuse_port: bool = false,
pub const max_callbacks_per_turn_auto: u32 = 8192;
pub fn wireBytes(self: Config) !usize {
const body = try std.math.mul(usize, self.max_body, 2);
return std.math.add(usize, try std.math.add(usize, body, self.max_header), 4096);
}
pub fn effectiveBatchLimit(self: Config) usize {
return if (self.execution == .inline_event_loop) self.response_batch_limit else 1;
}
pub fn effectiveCallbacksPerTurn(self: Config) usize {
if (self.callbacks_per_turn != 0) return self.callbacks_per_turn;
return @min(@as(usize, self.connections) * self.effectiveBatchLimit(), max_callbacks_per_turn_auto);
}
/// Gather vectors one batch can describe: arena runs around every borrow.
pub fn maxSendParts(self: Config) usize {
return 2 * self.effectiveBatchLimit() + 1;
}
/// Exact requested bytes for the framework allocator's startup allocations.
/// Kernel mappings, allocator metadata, application allocations and pthread
/// bookkeeping remain outside this metric; requested stacks are separate.
pub fn heapBytes(self: Config) !usize {
const count: usize = self.connections;
const cells = try std.math.mul(usize, count, self.effectiveBatchLimit());
const storage = try std.math.mul(usize, count, try std.math.add(usize, try self.wireBytes(), self.output_bytes));
const vectors = try std.math.mul(usize, count, try std.math.mul(usize, 2 * self.maxSendParts(), @sizeOf(c.iovec_const)));
var total: usize = @sizeOf(Server);
for ([_]usize{
storage,
try std.math.mul(usize, count, @sizeOf(Slot)),
try std.math.mul(usize, cells, @sizeOf(Cell)),
vectors,
try std.math.mul(usize, count, 2 * @sizeOf(u32)),
try std.math.mul(usize, self.workers, @sizeOf(Worker)),
try transport.backendHeapBytes(self.connections),
}) |bytes| total = try std.math.add(usize, total, bytes);
return total;
}
pub fn validate(self: Config) !void {
const invalid_workers = switch (self.execution) {
.workers => self.workers == 0,
.inline_event_loop => self.workers != 0,
};
if (self.connections == 0 or self.connections > 4096 or invalid_workers or
self.workers > 64 or self.workers > self.connections or self.max_header < 128 or
self.max_header > 65536 or self.max_body > 16 * 1024 * 1024 or
self.output_bytes < 1024 or self.output_bytes > 1024 * 1024 or self.timeout_ms == 0 or
self.callback_output_reserve < api.header_reserve_bytes or self.callback_output_reserve > self.output_bytes or
self.shutdown_ms == 0 or self.send_chunk == 0 or self.socket_send_buffer_bytes == 0 or
self.socket_send_buffer_bytes > 16 * 1024 * 1024 or self.max_headers == 0 or
self.max_headers > 1024 or self.worker_stack_bytes < 65536 or
self.response_batch_limit == 0 or self.response_batch_limit > 511 or
self.borrow_copy_threshold > 4096 or self.callbacks_per_turn > 1 << 20 or
self.deadline_sweep_ms == 0 or self.deadline_sweep_ms > 1000 or self.shards > 64 or
self.submit_batch > 4096)
return error.InvalidConfiguration;
assert(self.maxSendParts() <= transport.max_vectors);
const stacks = try std.math.mul(usize, self.worker_stack_bytes, self.workers);
if (try std.math.add(usize, try self.heapBytes(), stacks) > self.memory_budget_bytes)
return error.MemoryBudgetExceeded;
}
};
pub const Stats = struct {
execution: Execution = .inline_event_loop,
gather_send: bool = true,
response_batch_limit: usize = 128,
callbacks_per_turn: usize = 0,
shards: u16 = 1,
response_batches: u64 = 0,
batched_finished_responses: u64 = 0,
max_batch_responses: usize = 0,
scalar_send_operations: u64 = 0,
gather_send_operations: u64 = 0,
/// Gather-mode operations whose batch formed one contiguous span.
single_span_send_operations: u64 = 0,
borrow_copies: u64 = 0,
response_draft_copy_bytes: u64 = 0,
send_completions: u64 = 0,
short_send_completions: u64 = 0,
gather_cancel_requests: u64 = 0,
gather_canceled_completions: u64 = 0,
/// Frozen response cells retained when cancellation of a pending gather is
/// successfully requested. The target may still complete normally in a race.
max_canceled_batch_responses: usize = 0,
max_send_parts: usize = 0,
max_send_bytes: usize = 0,
max_inline_callbacks_per_turn: usize = 0,
inline_dispatches: u64 = 0,
worker_dispatches: u64 = 0,
accepted: u64 = 0,
/// Socket metadata transfers between Windows owners; no request bytes move.
handoffs_sent: u64 = 0,
handoffs_received: u64 = 0,
/// Received queue entries closed before adoption succeeds.
handoffs_closed: u64 = 0,
max_handoff_delay_ns: u64 = 0,
completed: u64 = 0,
rejected: u64 = 0,
timeouts: u64 = 0,
flushes: u64 = 0,
resumed: u64 = 0,
bytes_received: u64 = 0,
bytes_sent: u64 = 0,
pipeline_copy_bytes: u64 = 0,
live_connections: usize = 0,
peak_connections: usize = 0,
live_operations: usize = 0,
peak_operations: usize = 0,
max_loop_ns: u64 = 0,
/// Event-loop turns and polls that found nothing ready and had to wait.
turns: u64 = 0,
idle_polls: u64 = 0,
/// Receives armed while the previous batch was still being sent.
prearmed_receives: u64 = 0,
max_handler_ns: u64 = 0,
max_queue_ns: u64 = 0,
max_request_ns: u64 = 0,
workers: u16 = 0,
allocation_calls_after_start: usize = 0,
framework_heap_peak_bytes: usize = 0,
framework_heap_limit_bytes: usize = 0,
/// Sum counters and take maxima; used when several shards report together.
pub fn merge(self: *Stats, other: Stats) void {
inline for (@typeInfo(Stats).@"struct".fields) |field| {
const name = field.name;
if (comptime std.mem.startsWith(u8, name, "max_")) {
@field(self, name) = @max(@field(self, name), @field(other, name));
} else if (comptime std.mem.eql(u8, name, "execution") or std.mem.eql(u8, name, "gather_send") or
std.mem.eql(u8, name, "response_batch_limit") or std.mem.eql(u8, name, "callbacks_per_turn") or
std.mem.eql(u8, name, "shards") or std.mem.eql(u8, name, "framework_heap_peak_bytes") or
std.mem.eql(u8, name, "framework_heap_limit_bytes") or std.mem.eql(u8, name, "allocation_calls_after_start"))
{
// Configuration and process-wide accounting are not summed.
} else {
@field(self, name) += @field(other, name);
}
}
}
};
// Only result ends the callback borrow. Both streaming phases retain its stack.
const Phase = enum(u8) { io, ready, running, stream_ready, stream_wait, result };
const SendMode = enum { response, interim, reject };
const Kind = enum(u8) { accept = 1, recv, send, cancel_recv, cancel_send, cancel_accept };
const accept_token: u64 = @intFromEnum(Kind.accept);
const cancel_accept_token: u64 = @intFromEnum(Kind.cancel_accept);
const BatchNext = enum { parse, resume_flush, resume_timer, close };
/// One finished or flushed response snapshot: a range of the connection's
/// arena, with an optional borrowed span logically inserted at `borrow_at`.
/// Arena bytes and the borrow stay frozen until the batch's terminal send
/// completion; the request input they borrow stays immutable as well.
const Cell = struct {
begin: u32 = 0,
end: u32 = 0,
borrow_at: u32 = 0,
borrowed: []const u8 = "",
finished: bool = false,
request_started: u64 = 0,
};
const Slot = struct {
phase: std.atomic.Value(Phase) = .init(.io),
cancelled: std.atomic.Value(bool) = .init(false),
in_use: bool = false,
in_ready: bool = false,
generation: u32 = 0,
fd: transport.Socket = -1,
input: []u8,
received: usize = 0,
input_cursor: usize = 0,
request_active: bool = false,
arena: []u8,
arena_used: usize = 0,
cells: []Cell,
batch_count: usize = 0,
batch_next: BatchNext = .parse,
parser: http.Parser,
request: http.Request = undefined,
writer: api.Writer,
/// Worker callbacks read this exclusive snapshot, never the owner's mutable
/// once-per-second cache. Inline callbacks use the owner cache directly.
worker_header_cache: api.HeaderCache = .{},
state: [8]usize = @splat(0),
action: api.Action = .close,
event: api.Event = .request,
notify_cancel: bool = false,
resume_at: ?u64 = null,
wait_delay_ns: ?u64 = null,
await_notification: bool = false,
notification: api.Notification.Cell = .{},
/// A receive into the free input tail and a send of the frozen batch may
/// be in flight together; each has its own cell and cancel cell.
recv_pending: bool = false,
/// Peer write-half closure ends input, not pending response output.
recv_eof: bool = false,
recv_token: u64 = 0,
recv_cancel_pending: bool = false,
send_pending: bool = false,
send_token: u64 = 0,
send_cancel_pending: bool = false,
/// Some frozen cell borrows request input, so the input must not move.
batch_borrows_input: bool = false,
closing: bool = false,
deadline: u64 = 0,
request_started: u64 = 0,
queued_at: u64 = 0,
queue_ns: u64 = 0,
handler_ns: u64 = 0,
interim_sent: bool = false,
logical_written: usize = 0,
/// Wire parts of the batch being sent: arena runs and borrowed spans.
parts: []c.iovec_const,
part_count: usize = 0,
/// The bounded selection submitted by the current send operation.
selection: []c.iovec_const,
part: usize = 0,
part_offset: usize = 0,
send_submitted_bytes: usize = 0,
send_is_gather: bool = false,
send_mode: SendMode = .response,
};
const Worker = struct {
server: *Server,
index: usize,
read_fd: if (builtin.os.tag == .windows) i32 else c.fd_t = -1,
write_fd: if (builtin.os.tag == .windows) i32 else c.fd_t = -1,
event: ?windows.HANDLE = null,
thread: ?std.Thread = null,
fn init(server: *Server, index: usize) !Worker {
if (builtin.os.tag == .windows) {
// One startup auto-reset event per worker; notifications coalesce.
const event = win32.CreateEventW(null, 0, 0, null) orelse return error.WorkerEventFailed;
return .{ .server = server, .index = index, .event = event };
}
var fds: [2]c.fd_t = undefined;
if (c.pipe(&fds) != 0) return error.WorkerPipeFailed;
errdefer transport.closeFd(fds[0]);
errdefer transport.closeFd(fds[1]);
try transport.setFlags(fds[0], false);
try transport.setFlags(fds[1], true);
return .{ .server = server, .index = index, .read_fd = fds[0], .write_fd = fds[1] };
}
fn deinit(self: Worker) void {
assert(self.thread == null);
if (builtin.os.tag == .windows) {
windows.CloseHandle(self.event.?);
} else {
transport.closeFd(self.read_fd);
transport.closeFd(self.write_fd);
}
}
fn wake(self: *Worker) void {
if (builtin.os.tag == .windows) {
assert(win32.SetEvent(self.event.?) != 0);
return;
}
const byte = [_]u8{1};
const result = c.write(self.write_fd, &byte, 1);
if (result < 0) assert(c.errno(result) == .AGAIN or c.errno(result) == .INTR);
}
fn run(self: *Worker) void {
_ = self.server.ready_workers.fetchAdd(1, .release);
defer _ = self.server.exited_workers.fetchAdd(1, .release);
while (!self.server.stop_workers.load(.acquire)) {
self.wait();
if (self.server.stop_workers.load(.acquire)) break;
var index = self.index;
while (index < self.server.slots.len) : (index += self.server.workers.len) {
const slot = &self.server.slots[index];
if (slot.phase.cmpxchgStrong(.ready, .running, .acquire, .monotonic) != null)
continue;
self.server.invokeHandler(slot);
self.server.backend.wake();
}
}
}
fn wait(self: *Worker) void {
// The phase owns work; finite waits make coalesced wakeups harmless.
if (builtin.os.tag == .windows) {
const result = win32.WaitForSingleObject(self.event.?, 10);
assert(result == 0 or result == 258); // signaled or timeout
} else {
var ready = [_]c.pollfd{.{ .fd = self.read_fd, .events = c.POLL.IN, .revents = 0 }};
const polled = c.poll(&ready, 1, 10);
if (polled < 0) {
assert(c.errno(polled) == .INTR);
return;
}
if (polled > 0) {
var bytes: [64]u8 = undefined;
const read = c.read(self.read_fd, &bytes, bytes.len);
assert(read > 0 or (read < 0 and c.errno(read) == .INTR));
}
}
}
};
/// One I/O owner: listener, transport, slots, arenas, operation cells, clock
/// and counters. Several shards run several independent Servers.
pub const Server = struct {
allocator: std.mem.Allocator,
config: Config,
handler: api.Handler,
application: ?*anyopaque,
backend: transport.Backend,
slots: []Slot,
workers: []Worker,
storage: []u8,
response_cells: []Cell,
vectors: []c.iovec_const,
/// Free connection slots as a stack; accept pops, release pushes.
free_slots: []u32,
free_count: usize = 0,
/// Slots with a published callback or result, in FIFO order.
ready: []u32,
ready_head: usize = 0,
ready_count: usize = 0,
stop_requested: std.atomic.Value(bool) = .init(false),
stop_workers: std.atomic.Value(bool) = .init(false),
ready_workers: std.atomic.Value(u32) = .init(0),
exited_workers: std.atomic.Value(u32) = .init(0),
accept_pending: bool = false,
accept_cancel_pending: bool = false,
accept_cancel_requested: bool = false,
stopping: bool = false,
stop_deadline: u64 = 0,
started_at: u64 = 0,
started: bool = false,
safe_to_destroy: bool = true,
stats: Stats = .{},
inline_budget: usize = 0,
/// Turn clock: sampled per turn, after polling and every 16 callbacks.
now: u64 = 0,
clock_budget: u32 = 0,
last_sweep: u64 = 0,
next_timer: ?u64 = null,
header_cache: api.HeaderCache = .{},
date: [29]u8 = undefined,
date_second: u64 = std.math.maxInt(u64),
/// Shared process-wide ceiling when running as a shard; null standalone.
admission: ?*Admission = null,
/// Windows multi-shard distribution. Null preserves the direct accept path.
handoff_cluster: ?*Cluster = null,
shard_index: u8 = 0,
/// Drains since the last explicit submission within the current turn.
drains_since_flush: u16 = 0,
const clock_refresh_callbacks: u32 = 16;
pub fn init(allocator: std.mem.Allocator, config: Config, handler: api.Handler, application: ?*anyopaque) !*Server {
return initWith(allocator, config, handler, application, .direct);
}
const AcceptMode = enum { direct, distribute, receive };
fn initWith(allocator: std.mem.Allocator, config: Config, handler: api.Handler, application: ?*anyopaque, accept_mode: AcceptMode) !*Server {
try config.validate();
const self = try allocator.create(Server);
errdefer allocator.destroy(self);
var backend = if (builtin.os.tag == .windows) switch (accept_mode) {
.direct => try transport.Backend.init(allocator, config.connections, config.port, config.reuse_port),
.distribute => try transport.Backend.initAcceptor(allocator, config.connections, config.port),
.receive => try transport.Backend.initDestination(allocator, config.connections),
} else try transport.Backend.init(allocator, config.connections, config.port, config.reuse_port);
errdefer backend.deinit();
if (config.gather_send) try backend.enableGather();
const slots = try allocator.alloc(Slot, config.connections);
errdefer allocator.free(slots);
const workers = try allocator.alloc(Worker, config.workers);
errdefer allocator.free(workers);
const wire = try config.wireBytes();
const batch_limit = config.effectiveBatchLimit();
const response_cells = try allocator.alloc(Cell, config.connections * batch_limit);
errdefer allocator.free(response_cells);
const parts_per_slot = config.maxSendParts();
const vectors = try allocator.alloc(c.iovec_const, config.connections * 2 * parts_per_slot);
errdefer allocator.free(vectors);
const free_slots = try allocator.alloc(u32, config.connections);
errdefer allocator.free(free_slots);
const ready = try allocator.alloc(u32, config.connections);
errdefer allocator.free(ready);
const per_slot = wire + config.output_bytes;
const storage = try allocator.alloc(u8, per_slot * config.connections);
errdefer allocator.free(storage);
@memset(storage, 0);
self.* = .{
.allocator = allocator,
.config = config,
.handler = handler,
.application = application,
.backend = backend,
.slots = slots,
.workers = workers,
.storage = storage,
.response_cells = response_cells,
.vectors = vectors,
.free_slots = free_slots,
.ready = ready,
.stats = .{
.workers = config.workers,
.execution = config.execution,
.gather_send = config.gather_send,
.response_batch_limit = batch_limit,
.callbacks_per_turn = config.effectiveCallbacksPerTurn(),
},
};
for (slots, 0..) |*slot, index| {
const base = storage[index * per_slot ..][0..per_slot];
const arena = base[wire..][0..config.output_bytes];
slot.* = .{
.cells = response_cells[index * batch_limit ..][0..batch_limit],
.input = base[0..wire],
.arena = arena,
.parts = vectors[index * 2 * parts_per_slot ..][0..parts_per_slot],
.selection = vectors[index * 2 * parts_per_slot + parts_per_slot ..][0..parts_per_slot],
.parser = http.Parser.init(.{
.max_header_bytes = config.max_header,
.max_header_count = config.max_headers,
.max_body_bytes = config.max_body,
.max_wire_bytes = @intCast(wire),
.max_target_bytes = 8192,
}),
.writer = api.Writer.init(arena, &self.header_cache, config.borrow_copy_threshold),
};
@memset(slot.cells, .{});
// Higher slots go in first so accept pops the lowest free index.
free_slots[index] = @intCast(config.connections - 1 - index);
}
self.free_count = config.connections;
var initialized: usize = 0;
errdefer for (workers[0..initialized]) |worker| worker.deinit();
for (workers, 0..) |*worker, index| {
worker.* = try Worker.init(self, index);
initialized += 1;
}
return self;
}
pub fn start(self: *Server) !void {
assert(!self.started);
errdefer {
self.stop_workers.store(true, .release);
for (self.workers) |*worker| if (worker.thread) |thread| {
worker.wake();
thread.join();
worker.thread = null;
};
}
for (self.workers) |*worker| worker.thread = try std.Thread.spawn(.{
.stack_size = self.config.worker_stack_bytes,
.allocator = self.allocator,
}, Worker.run, .{worker});
const startup_deadline = nowNs() + @as(u64, self.config.shutdown_ms) * 1_000_000;
while (self.ready_workers.load(.acquire) != self.workers.len) {
// A thread that never reaches its entry point cannot safely be
// reclaimed in-process. The demo's outer watchdog also covers spawn.
if (nowNs() >= startup_deadline) failFast(70);
std.Thread.yield() catch {};
}
self.started = true;
self.safe_to_destroy = false;
self.started_at = nowNs();
self.now = self.started_at;
self.last_sweep = self.started_at;
self.refreshDate();
}
pub fn requestStop(self: *Server) void {
self.stop_requested.store(true, .release);
self.backend.wake();
}
fn recvCell(self: *const Server, index: usize) u32 {
assert(index < self.slots.len);
return @intCast(index);
}
fn sendCell(self: *const Server, index: usize) u32 {
assert(index < self.slots.len);
return @intCast(self.slots.len + index);
}
fn recvCancelCell(self: *const Server, index: usize) u32 {
assert(index < self.slots.len);
return @intCast(2 * self.slots.len + index);
}
fn sendCancelCell(self: *const Server, index: usize) u32 {
assert(index < self.slots.len);
return @intCast(3 * self.slots.len + index);
}
fn acceptCell(self: *const Server) u32 {
return @intCast(4 * self.slots.len);
}
fn cancelAcceptCell(self: *const Server) u32 {
return @intCast(4 * self.slots.len + 1);
}
fn sampleClock(self: *Server) void {
self.now = nowNs();
self.clock_budget = clock_refresh_callbacks;
}
fn pushReady(self: *Server, index: usize) void {
const slot = &self.slots[index];
if (slot.in_ready) return;
assert(self.ready_count < self.ready.len);
self.ready[(self.ready_head + self.ready_count) % self.ready.len] = @intCast(index);
self.ready_count += 1;
slot.in_ready = true;
}
fn popReady(self: *Server) usize {
assert(self.ready_count > 0);
const index = self.ready[self.ready_head];
self.ready_head = (self.ready_head + 1) % self.ready.len;
self.ready_count -= 1;
self.slots[index].in_ready = false;
return index;
}
pub fn run(self: *Server) !void {
assert(self.started);
// Completion means no further queue publication, including on error.
// A failed backend still retains its operation storage until process exit.
defer if (builtin.os.tag == .windows) {
if (self.handoff_cluster) |cluster| {
if (self.shard_index == 0) {
cluster.producer_done.store(true, .release);
for (cluster.shards[1..]) |server| server.backend.wake();
}
}
};
var completions: [512]transport.Completion = undefined;
const sweep_ns = @as(u64, self.config.deadline_sweep_ms) * 1_000_000;
while (true) {
self.inline_budget = self.stats.callbacks_per_turn;
self.drains_since_flush = 0;
self.sampleClock();
const turn_start = self.now;
if (self.config.duration_ms != 0 and
turn_start - self.started_at >= @as(u64, self.config.duration_ms) * 1_000_000)
self.stop_requested.store(true, .release);
if (self.stop_requested.load(.acquire) and !self.stopping) {
self.stopping = true;
self.stop_deadline = turn_start + @as(u64, self.config.shutdown_ms) * 1_000_000;
// A receiver must stop the producer before waiting for its end.
if (builtin.os.tag == .windows) {
if (self.handoff_cluster) |cluster| cluster.requestStop();
}
}
if (self.stopping and self.accept_pending and !self.accept_cancel_requested) {
try self.backend.cancel(self.cancelAcceptCell(), cancel_accept_token, self.acceptCell());
self.accept_cancel_pending = true;
self.accept_cancel_requested = true;
self.operationAdded();
}
const accepts = builtin.os.tag != .windows or self.handoff_cluster == null or self.shard_index == 0;
if (accepts and !self.stopping and !self.accept_pending) {
try self.backend.accept(self.acceptCell(), accept_token);
self.accept_pending = true;
self.operationAdded();
}
try self.receiveHandoffs();
self.refreshDate();
if (self.stopping or turn_start - self.last_sweep >= sweep_ns) {
self.last_sweep = turn_start;
for (self.slots) |*slot| {
if (!slot.in_use) continue;
if (slot.closing) {
self.maybeFree(slot);
} else if (self.stopping or turn_start >= slot.deadline) {
if (!self.stopping) self.stats.timeouts += 1;
try self.beginClose(slot);
}
}
}
try self.serviceNotifications();
try self.serviceTimers();
switch (self.config.execution) {
.inline_event_loop => {
// One pass over the slots that were ready when the turn
// began; anything readied meanwhile waits for the next turn.
var remaining = self.ready_count;
while (remaining > 0 and self.inline_budget > 0) : (remaining -= 1) {
try self.serviceSlot(self.popReady());
}
},
.workers => for (self.slots, 0..) |*slot, index| {
if (slot.in_use) try self.serviceSlot(index);
},
}
const control_ns = nowNs() - turn_start;
self.stats.max_loop_ns = @max(self.stats.max_loop_ns, control_ns);
if (self.stopping and self.stats.live_connections == 0 and
self.stats.live_operations == 0 and self.handoffsFinished()) break;
if (self.stopping and self.now >= self.stop_deadline) return error.ShutdownStalled;
const local_ready = self.ready_count > 0 or (self.config.execution == .workers and self.anyResult()) or self.handoffsReady();
self.stats.turns += 1;
const count = try self.backend.poll(&completions, if (local_ready) 0 else 10);
if (count == 0 and !local_ready) self.stats.idle_polls += 1;
self.sampleClock();
const processing_start = self.now;
for (completions[0..count]) |completion| try self.onCompletion(completion);
assert(self.inline_budget <= self.stats.callbacks_per_turn);
self.stats.max_inline_callbacks_per_turn = @max(self.stats.max_inline_callbacks_per_turn, self.stats.callbacks_per_turn - self.inline_budget);
self.stats.max_loop_ns = @max(self.stats.max_loop_ns, control_ns + nowNs() - processing_start);
}
self.stop_workers.store(true, .release);
for (self.workers) |*worker| worker.wake();
while (self.exited_workers.load(.acquire) != self.workers.len) {
if (nowNs() >= self.stop_deadline) return error.ShutdownStalled;
const count = try self.backend.poll(&completions, 10);
assert(count == 0);
}
for (self.workers) |*worker| if (worker.thread) |thread| {
thread.join();
worker.thread = null;
};
self.safe_to_destroy = true;
}
/// Each connection supplies one startup-reserved notification cell.
/// A pending signal stays armed through callbacks and transport borrows.
fn serviceNotifications(self: *Server) !void {
for (self.slots, 0..) |*slot, index| {
if (!slot.in_use or slot.phase.load(.acquire) != .io or !slot.await_notification or slot.send_pending)
continue;
assert(slot.request_active);
if (slot.closing or self.stopping or self.now >= slot.deadline) {
if (!slot.closing and !self.stopping) self.stats.timeouts += 1;
try self.beginClose(slot);
} else if (slot.notification.consume()) {
slot.await_notification = false;
slot.resume_at = null;
slot.event = .notified;
self.dispatch(index);
}
}
}
/// Timer storage belongs to slots. A due timer causes one bounded slot scan.
fn serviceTimers(self: *Server) !void {
const next = self.next_timer orelse return;
if (self.now < next) return;
self.next_timer = null;
for (self.slots, 0..) |*slot, index| {
const at = slot.resume_at orelse continue;
assert(slot.in_use and slot.request_active and slot.phase.load(.acquire) == .io);
if (slot.closing or self.stopping or self.now >= slot.deadline) {
if (!slot.closing and !self.stopping) self.stats.timeouts += 1;
try self.beginClose(slot);
} else if (slot.send_pending) {
// The preceding batch still owns output. Completion rearms the timer.
} else if (at <= self.now) {
slot.resume_at = null;
slot.await_notification = false;
slot.event = .timer;
self.dispatch(index);
} else {
self.next_timer = @min(self.next_timer orelse at, at);
}
}
}
fn anyResult(self: *Server) bool {
for (self.slots) |*slot| {
if (!slot.in_use) continue;
const phase = slot.phase.load(.acquire);
if (phase == .result or phase == .stream_ready) return true;
}
return false;
}
/// Run the callbacks a slot has ready and process each published result.
fn serviceSlot(self: *Server, index: usize) !void {
const slot = &self.slots[index];
if (!slot.in_use) return;
if (!slot.closing and (self.stopping or self.now >= slot.deadline)) {
if (!self.stopping) self.stats.timeouts += 1;
try self.beginClose(slot);
}
// At most one configured batch worth of callbacks per slot and visit.
// Empty flushes also consume this finite progress budget.
const batch_limit = self.config.effectiveBatchLimit();
for (0..batch_limit) |iteration| {
if (self.config.execution == .inline_event_loop and
slot.phase.load(.acquire) == .ready and self.inline_budget > 0)
{
// Preceding callbacks may have consumed time since the turn
// clock was sampled; the clock refreshes every few callbacks.
if (!slot.closing and (self.stop_requested.load(.acquire) or self.now >= slot.deadline)) {
if (!self.stop_requested.load(.acquire)) self.stats.timeouts += 1;
try self.beginClose(slot);
}
self.invokeInline(slot);
}
const phase = slot.phase.load(.acquire);
if (phase == .stream_ready) {
assert(self.config.execution == .workers and slot.action == .flush);
// The worker still owns its stack, request and application state.
// Only the frozen writer snapshot transfers to the I/O owner.
slot.phase.store(.stream_wait, .release);
if (slot.closing or self.stop_requested.load(.acquire) or self.now >= slot.deadline) {
if (!slot.closing and !self.stop_requested.load(.acquire)) self.stats.timeouts += 1;
try self.beginClose(slot);
} else {
try self.prepareResponse(index, false);
}
break;
}
if (phase != .result) break;
if (self.config.callback_timing) {
self.stats.max_handler_ns = @max(self.stats.max_handler_ns, slot.handler_ns);
self.stats.max_queue_ns = @max(self.stats.max_queue_ns, slot.queue_ns);
}
slot.phase.store(.io, .release);
if (slot.closing or slot.action == .close) {
try self.beginClose(slot);
} else if (self.stop_requested.load(.acquire) or self.now >= slot.deadline) {
if (!self.stop_requested.load(.acquire)) self.stats.timeouts += 1;
try self.beginClose(slot);
} else if (slot.action == .wait) {
if (slot.wait_delay_ns) |delay| {
const at = nowNs() +| delay;
slot.resume_at = at;
self.next_timer = @min(self.next_timer orelse at, at);
} else if (!slot.await_notification) {
try self.beginClose(slot);
break;
}
if (slot.batch_count != 0) {
// Initial waits cannot retain earlier finished responses in the arena.
assert(!slot.writer.began);
slot.writer.frozen = true;
try self.drainBatch(index, .resume_timer);
}
} else {
try self.prepareResponse(index, iteration + 1 < batch_limit);
}
}
if (slot.closing) self.maybeFree(slot);
// A budget-exhausted or re-dispatched slot is serviced next turn.
if (self.config.execution == .inline_event_loop and slot.in_use) {
const phase = slot.phase.load(.acquire);
if (phase == .ready or phase == .result) self.pushReady(index);
}
}
pub fn deinit(self: *Server) void {
assert(self.safe_to_destroy);
assert(self.stats.live_operations == 0 and self.stats.live_connections == 0);
for (self.workers) |worker| worker.deinit();
self.backend.deinit();
self.allocator.free(self.storage);
self.allocator.free(self.ready);
self.allocator.free(self.free_slots);
self.allocator.free(self.vectors);
self.allocator.free(self.response_cells);
self.allocator.free(self.slots);
self.allocator.free(self.workers);
const allocator = self.allocator;
allocator.destroy(self);
}
fn operationAdded(self: *Server) void {
self.stats.live_operations += 1;
self.stats.peak_operations = @max(self.stats.peak_operations, self.stats.live_operations);
assert(self.stats.live_operations <= transport.cellCount(self.config.connections));
}
fn tokenFor(slot: *const Slot, index: usize, kind: Kind) u64 {
return (@as(u64, slot.generation) << 32) | (@as(u64, index) << 8) | @intFromEnum(kind);
}
fn distributeAccepted(self: *Server, socket: transport.Socket) !void {
if (builtin.os.tag != .windows) unreachable;
const cluster = self.handoff_cluster.?;
assert(self.shard_index == 0 and !cluster.producer_done.load(.monotonic));
if (self.stop_requested.load(.acquire) or !cluster.admission.admit()) {
self.backend.close(self.acceptCell(), socket);
if (!self.stop_requested.load(.acquire)) self.stats.rejected += 1;
return;
}
var value: ?AcceptedSocket = .{
.socket = self.backend.exportAccepted(socket) catch |err| {
self.backend.close(self.acceptCell(), socket);
cluster.admission.release();
return err;
},
.accepted_at = self.now,
};
const destination = cluster.next_destination;
cluster.next_destination = (destination + 1) % cluster.shards.len;
if (destination == 0) {
try self.adoptHandoff(&value.?);
value = null;
return;
}
// The new admission charge proves fewer than C earlier items remain
// anywhere in the cluster. A queue with capacity C must have room.
const published = cluster.handoffs[destination - 1].push(&value);
assert(published and value == null);
self.stats.handoffs_sent += 1;
cluster.shards[destination].backend.wake();
}
fn adoptHandoff(self: *Server, value: *AcceptedSocket) !void {
if (builtin.os.tag != .windows) unreachable;
const cluster = self.handoff_cluster.?;
assert(self.free_count > 0);
// Refresh once per adoption, including during a full queue drain.
// Request callbacks continue to use the existing turn-clock policy.
self.sampleClock();
const deadline = value.accepted_at + @as(u64, self.config.timeout_ms) * 1_000_000;
self.stats.max_handoff_delay_ns = @max(self.stats.max_handoff_delay_ns, self.now - value.accepted_at);
if (self.stop_requested.load(.acquire) or self.now >= deadline) {
value.socket.close();
cluster.admission.release();
if (self.shard_index != 0) self.stats.handoffs_closed += 1;
if (!self.stop_requested.load(.acquire)) self.stats.timeouts += 1;
return;
}
const socket = self.backend.importAccepted(&value.socket) catch {
// Association failure preserves the detached handle for closure.
value.socket.close();
cluster.admission.release();
if (self.shard_index != 0) self.stats.handoffs_closed += 1;
self.stats.rejected += 1;
return;
};
if (!try self.adoptSocket(socket, value.accepted_at) and self.shard_index != 0) self.stats.handoffs_closed += 1;
}
fn receiveHandoffs(self: *Server) !void {
if (builtin.os.tag != .windows) return;
const cluster = self.handoff_cluster orelse return;
if (self.shard_index == 0) return;
const queue = &cluster.handoffs[self.shard_index - 1];
// A producer can refill while we drain. Cap work at C per loop turn.
for (0..self.config.connections) |_| {
var value = queue.pop() orelse break;
self.stats.handoffs_received += 1;
try self.adoptHandoff(&value);
}
}
fn handoffsFinished(self: *Server) bool {
if (builtin.os.tag != .windows) return true;
const cluster = self.handoff_cluster orelse return true;
if (self.shard_index == 0) return true;
// Completion must be acquired BEFORE the final empty observation.
// Otherwise a final publication could fall between the two reads.
if (!cluster.producer_done.load(.acquire)) return false;
return cluster.handoffs[self.shard_index - 1].empty();
}
fn handoffsReady(self: *Server) bool {
if (builtin.os.tag != .windows) return false;
const cluster = self.handoff_cluster orelse return false;
if (self.shard_index == 0) return false;
return !cluster.handoffs[self.shard_index - 1].empty();
}
/// The caller already owns any shared admission charge.
fn adoptSocket(self: *Server, socket: transport.Socket, accepted_at: u64) !bool {
assert(self.free_count > 0);
const index = self.free_slots[self.free_count - 1];
const slot = &self.slots[index];
assert(!slot.in_use and slot.phase.load(.acquire) == .io);
slot.generation = try std.math.add(u32, slot.generation, 1);
slot.fd = socket;
transport.setSendBuffer(&self.backend, slot.fd, self.config.socket_send_buffer_bytes) catch {
self.backend.close(self.acceptCell(), slot.fd);
slot.fd = -1;
self.stats.rejected += 1;
if (self.admission) |admission| admission.release();
return false;
};
self.free_count -= 1;
slot.in_use = true;
slot.closing = false;
slot.cancelled.store(false, .release);
slot.received = 0;
slot.recv_eof = false;
slot.input_cursor = 0;
slot.request_active = false;
slot.batch_count = 0;
slot.arena_used = 0;
slot.batch_borrows_input = false;
slot.part_count = 0;
slot.part = 0;
slot.part_offset = 0;
slot.parser.reset();
slot.interim_sent = false;
slot.logical_written = 0;
slot.deadline = accepted_at + @as(u64, self.config.timeout_ms) * 1_000_000;
slot.request_started = accepted_at;
self.stats.accepted += 1;
self.stats.live_connections += 1;
self.stats.peak_connections = @max(self.stats.peak_connections, self.stats.live_connections);
assert(self.stats.live_connections <= self.slots.len);
try self.receive(index);
return true;
}
fn onCompletion(self: *Server, completion: transport.Completion) !void {
assert(self.stats.live_operations > 0);
self.stats.live_operations -= 1;
const kind: Kind = @enumFromInt(@as(u8, @truncate(completion.token)));
if (kind == .cancel_accept) {
assert(self.accept_cancel_pending);
self.accept_cancel_pending = false;
return;
}
if (kind == .accept) {