Repository navigation
Expand file tree
/
Copy pathapi.zig
More file actions
963 lines (898 loc) · 43.1 KB
/
Copy pathapi.zig
File metadata and controls
963 lines (898 loc) · 43.1 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
const std = @import("std");
pub const http = @import("http.zig");
const assert = std.debug.assert;
pub const Action = enum { flush, finish, close, wait };
pub const Event = enum { request, flushed, timer, notified, cancelled };
pub const Handler = *const fn (*Context) Action;
pub const FlushError = error{ BlockingFlushUnavailable, InvalidState, Cancelled };
/// A producer handle signals one request. Signals coalesce until the request consumes them.
/// The producer must stop before Server.deinit releases the cell storage.
/// A stale handle is safe only while that server storage remains allocated.
pub const Notification = struct {
cell: *Cell,
generation: u64,
pub const Result = enum { notified, coalesced, stale };
/// Signal from any thread without allocation or waiting for the request callback.
/// Success records a wakeup; it does not acknowledge application processing.
pub fn signal(self: Notification) Result {
const ready = self.generation | Cell.active;
const observed = self.cell.state.load(.acquire);
if (observed == ready | Cell.pending) return .coalesced;
if (observed != ready) return .stale;
if (self.cell.state.cmpxchgStrong(ready, ready | Cell.pending, .acq_rel, .acquire)) |changed| {
return if (changed == ready | Cell.pending) .coalesced else .stale;
}
return .notified;
}
/// The scheduler owns activation and consumption. Producers only call signal().
pub const Cell = struct {
state: std.atomic.Value(u64) = .init(0),
const active: u64 = 1;
const pending: u64 = 2;
const flags: u64 = active | pending;
/// Advance once per request, including requests on persistent connections.
/// Exhaustion permanently retires the cell instead of reusing a generation.
pub fn activate(self: *Cell) error{NotificationGenerationExhausted}!void {
const previous = self.state.load(.acquire);
assert(previous & flags == 0);
const generation = std.math.add(u64, previous, flags + 1) catch
return error.NotificationGenerationExhausted;
self.state.store(generation | active, .release);
}
pub fn handle(self: *Cell) ?Notification {
const observed = self.state.load(.acquire);
if (observed & active == 0) return null;
return .{ .cell = self, .generation = observed & ~flags };
}
pub fn deactivate(self: *Cell) void {
_ = self.state.fetchAnd(~flags, .acq_rel);
}
/// Only the request owner consumes signals, while no callback runs.
pub fn consume(self: *Cell) bool {
const observed = self.state.fetchAnd(~pending, .acq_rel);
return observed & flags == flags;
}
};
};
pub const Context = struct {
request: *const http.Request,
writer: *Writer,
event: Event,
/// Eight startup-reserved words, zeroed for each new request.
state: *[8]usize,
application: ?*anyopaque,
cancelled: *const std.atomic.Value(bool),
/// The scheduler supplies this hook only for an existing application worker.
blocking_flush: ?BlockingFlush = null,
/// Internal callback result metadata. Use requestCancellation() and wait().
notify_cancel: bool = false,
resume_after_ns: ?u64 = null,
await_notification: bool = false,
notification_cell: ?*Notification.Cell = null,
/// Scheduler-owned target for setRequestTimeout; null when Config.max_timeout_ms is zero.
requested_timeout_ms: ?*u32 = null,
max_timeout_ms: u32 = 0,
/// Request one cancellation callback if this callback returns flush or wait.
/// Cancellation runs on the configured application executor after kernel borrows end.
/// Its writer is unavailable. Return close after releasing application state.
/// Finish and close require local cleanup and never receive this callback.
pub fn requestCancellation(self: *Context) void {
self.notify_cancel = true;
}
/// Return this action to release the worker until a monotonic timer expires.
/// The original request deadline still applies. Wakeups can arrive late.
/// Publish pending response bytes with flush before waiting.
pub fn wait(self: *Context, delay_ns: u64) error{ InvalidState, Cancelled }!Action {
if (self.cancelled.load(.acquire)) return error.Cancelled;
if (self.writer.frozen or self.writer.reserved != 0 or self.writer.borrowed != null or
(self.writer.began and (!self.writer.headers_committed or self.writer.bodyBytes() != 0)))
return error.InvalidState;
self.resume_after_ns = delay_ns;
self.await_notification = false;
return .wait;
}
/// Replace this request's deadline with `timeout_ms` after the request started.
/// Config.max_timeout_ms bounds the value and must be nonzero to allow overrides.
/// The server adopts the value when this callback returns or flushes.
/// A later call in the same request replaces an earlier one. The next request
/// on the connection uses Config.timeout_ms again.
pub fn setRequestTimeout(self: *Context, timeout_ms: u32) error{ RequestTimeoutUnavailable, InvalidRequestTimeout, Cancelled }!void {
if (self.cancelled.load(.acquire)) return error.Cancelled;
const target = self.requested_timeout_ms orelse return error.RequestTimeoutUnavailable;
if (timeout_ms == 0 or timeout_ms > self.max_timeout_ms) return error.InvalidRequestTimeout;
target.* = timeout_ms;
}
/// Obtain a handle without retaining the callback context or request storage.
pub fn notification(self: *Context) error{ NotificationUnavailable, Cancelled }!Notification {
if (self.cancelled.load(.acquire)) return error.Cancelled;
const cell = self.notification_cell orelse return error.NotificationUnavailable;
return cell.handle() orelse error.Cancelled;
}
/// Release the callback until a producer signals or the optional timer expires.
/// Signals before this call remain pending. Repeated signals coalesce.
/// A pending notification takes precedence over an expired optional timer.
/// The owner observes signals within its normal poll cycle, usually ten milliseconds.
/// The request deadline still applies. Publish pending bytes before waiting.
pub fn waitNotification(self: *Context, timeout_ns: ?u64) error{ NotificationUnavailable, InvalidState, Cancelled }!Action {
_ = try self.notification();
_ = try self.wait(timeout_ns orelse 0);
self.resume_after_ns = timeout_ns;
self.await_notification = true;
return .wait;
}
pub const BlockingFlush = struct {
context: *anyopaque,
flush: *const fn (*anyopaque) FlushError!void,
};
pub fn supportsBlockingFlush(self: *const Context) bool {
return self.blocking_flush != null;
}
/// Send this snapshot and resume the same callback with fresh output capacity.
/// The worker waits; the I/O owner continues processing other connections.
/// Completion ends the local transport borrow, not the peer's processing.
/// After publication, cancellation waits for transport borrows before returning an error.
/// The context and writer must remain on their original callback thread.
pub fn flushAndWait(self: *Context) FlushError!void {
const hook = self.blocking_flush orelse return error.BlockingFlushUnavailable;
if (self.cancelled.load(.acquire)) return error.Cancelled;
if (self.writer.frozen or self.writer.reserved != 0 or !self.writer.began)
return error.InvalidState;
_ = self.writer.flush();
return hook.flush(hook.context);
}
};
/// Largest response head this framework generates, plus the chunk-size field.
/// The scheduler guarantees at least this much free arena before a callback.
pub const header_reserve_bytes: usize = 384;
/// Fixed-width chunk-size field written before each chunked snapshot.
pub const chunk_size_field_bytes: usize = 10;
/// Space kept free for the chunk CRLF and the final zero chunk.
const chunk_slack_bytes: usize = 7;
pub const max_content_type_bytes: usize = 128;
/// Ordinary response construction errors, including untrusted header values.
pub fn validateHeader(name: []const u8, value: []const u8) !void {
if (name.len == 0) return error.InvalidHeader;
for (name) |byte| switch (byte) {
'a'...'z', 'A'...'Z', '0'...'9', '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.', '^', '_', '`', '|', '~' => {},
else => return error.InvalidHeader,
};
for (value) |byte| {
if ((byte < 32 and byte != '\t') or byte == 127) return error.InvalidHeader;
}
inline for (.{ "Content-Length", "Transfer-Encoding", "Connection", "Content-Type", "Trailer", "Upgrade", "Keep-Alive", "Proxy-Connection", "TE", "Server", "Date" }) |reserved| {
if (std.ascii.eqlIgnoreCase(name, reserved)) return error.ReservedHeader;
}
}
fn validateHeaderBlock(bytes: []const u8) !void {
var offset: usize = 0;
while (offset < bytes.len) {
const end = std.mem.findPosLinear(u8, bytes, offset, "\r\n") orelse return error.InvalidHeader;
const line = bytes[offset..end];
const colon = std.mem.findScalar(u8, line, ':') orelse return error.InvalidHeader;
try validateHeader(line[0..colon], line[colon + 1 ..]);
offset = end + 2;
}
}
/// Date/status prefix rebuilt by one I/O owner once per second. Inline begin()
/// reads that owner's cache; worker begin() reads an exclusive slot snapshot
/// published before dispatch. begin() copies the prefix instead of formatting.
pub const HeaderCache = struct {
date: [29]u8 = undefined,
ok_prefix: [80]u8 = undefined,
ok_prefix_len: usize = 0,
const ok_head = "HTTP/1.1 200 OK\r\nServer: bounded-http\r\nDate: ";
pub fn refresh(self: *HeaderCache, date: *const [29]u8) void {
self.date = date.*;
var n: usize = 0;
@memcpy(self.ok_prefix[n..][0..ok_head.len], ok_head);
n += ok_head.len;
@memcpy(self.ok_prefix[n..][0..29], date);
n += 29;
@memcpy(self.ok_prefix[n..][0..2], "\r\n");
n += 2;
self.ok_prefix_len = n;
}
};
pub fn reason(status: u16) []const u8 {
return switch (status) {
200 => "OK",
201 => "Created",
202 => "Accepted",
204 => "No Content",
205 => "Reset Content",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
307 => "Temporary Redirect",
308 => "Permanent Redirect",
400 => "Bad Request",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
409 => "Conflict",
413 => "Content Too Large",
414 => "URI Too Long",
415 => "Unsupported Media Type",
417 => "Expectation Failed",
431 => "Request Header Fields Too Large",
500 => "Internal Server Error",
501 => "Not Implemented",
503 => "Service Unavailable",
505 => "HTTP Version Not Supported",
else => "Response",
};
}
/// Writes the shortest decimal representation; returns the byte count.
pub fn putDecimal(out: []u8, value: usize) usize {
var count: usize = 1;
var probe = value;
while (probe >= 10) : (probe /= 10) count += 1;
var remaining = value;
var at = count;
while (at > 0) {
at -= 1;
out[at] = @intCast('0' + remaining % 10);
remaining /= 10;
}
return count;
}
/// Copy a short span with word stores instead of a libc call; the destination
/// must hold `src.len` bytes.
pub inline fn copyShort(dst: []u8, src: []const u8) void {
if (src.len > 32) {
@memcpy(dst[0..src.len], src);
return;
}
var at: usize = 0;
while (at + 8 <= src.len) : (at += 8) dst[at..][0..8].* = src[at..][0..8].*;
while (at < src.len) : (at += 1) dst[at] = src[at];
}
/// Writes exactly eight lowercase hex digits and CRLF: a valid chunk-size line
/// with leading zeros, so the field width is fixed before the length is known.
pub fn putChunkSize(out: *[chunk_size_field_bytes]u8, value: usize) void {
assert(value <= std.math.maxInt(u32));
const hex = "0123456789abcdef";
var remaining: u32 = @intCast(value);
var at: usize = 8;
while (at > 0) {
at -= 1;
out[at] = hex[remaining & 15];
remaining >>= 4;
}
out[8] = '\r';
out[9] = '\n';
}
/// Only the current application callback can mutate a Writer. Returning flush
/// or finish transfers its committed bytes to the I/O owner until completion.
///
/// The Writer appends into one contiguous per-connection output arena that is
/// shared by every not yet sent response of that connection. Response head
/// bytes are written at begin(); body bytes follow them, so a whole batch of
/// generated responses forms one span. Borrowed spans at most
/// `copy_threshold` bytes long are copied into the arena as an explicit,
/// counted exception; longer spans stay borrowed and are described separately.
pub const Writer = struct {
arena: []u8,
header_cache: *const HeaderCache,
/// First byte of this response snapshot within the arena.
base: usize = 0,
/// First body byte; the head and any chunk-size field end here.
body_start: usize = 0,
/// Absolute end of committed bytes.
buffered: usize = 0,
reserved: usize = 0,
borrowed: ?[]const u8 = null,
chunk_size_at: ?usize = null,
status: u16 = 200,
content_type: []const u8 = "text/plain",
content_length: ?usize = null,
copy_threshold: usize = 0,
keep_alive: bool = true,
head_only: bool = false,
began: bool = false,
frozen: bool = false,
headers_committed: bool = false,
copied_borrow: bool = false,
/// Payload bytes compacted from an unpublished one-shot draft.
draft_copy_bytes: usize = 0,
pub fn init(arena: []u8, header_cache: *const HeaderCache, copy_threshold: usize) Writer {
return .{ .arena = arena, .header_cache = header_cache, .copy_threshold = copy_threshold };
}
/// Start a new response whose bytes begin at `at`. The framework calls this
/// once per request with the request's connection/HEAD facts.
pub fn open(self: *Writer, at: usize, keep_alive: bool, head_only: bool) void {
assert(at <= self.arena.len - header_reserve_bytes);
self.base = at;
self.body_start = at;
self.buffered = at;
self.reserved = 0;
self.borrowed = null;
self.chunk_size_at = null;
self.status = 200;
self.content_type = "text/plain";
self.content_length = null;
self.keep_alive = keep_alive;
self.head_only = head_only;
self.began = false;
self.frozen = false;
self.headers_committed = false;
self.copied_borrow = false;
self.draft_copy_bytes = 0;
}
/// Continue the same response after a flush drained the arena. The head is
/// already on the wire; a chunked response gets a fresh size field.
pub fn resumeSnapshot(self: *Writer, at: usize) void {
assert(!self.frozen and self.began and self.headers_committed);
assert(at <= self.arena.len - header_reserve_bytes);
self.base = at;
self.buffered = at;
self.reserved = 0;
self.borrowed = null;
self.chunk_size_at = null;
self.copied_borrow = false;
self.draft_copy_bytes = 0;
if (self.chunked()) {
self.chunk_size_at = at;
self.buffered += chunk_size_field_bytes;
}
self.body_start = self.buffered;
}
pub fn chunked(self: *const Writer) bool {
return self.content_length == null and !self.head_only and self.status != 204 and self.status != 304;
}
fn slack(self: *const Writer) usize {
return if (self.chunked()) chunk_slack_bytes else 0;
}
/// Body bytes the application can still reserve in one snapshot after a
/// flush, independent of how full the arena currently is.
pub fn capacity(self: *const Writer) usize {
return self.arena.len - header_reserve_bytes - chunk_slack_bytes;
}
/// Return bounded scratch for the current unpublished response.
/// The slice excludes earlier snapshots and lasts only during this callback.
/// The adapter must reserve this capacity through Config.callback_output_reserve.
/// A zero-length request checks draft state without exposing storage.
pub fn draftStorage(self: *Writer, required_bytes: usize) ![]u8 {
if (self.frozen or self.began or self.headers_committed or self.reserved != 0 or
self.borrowed != null or self.buffered != self.base) return error.InvalidState;
if (required_bytes > self.arena.len - self.base) return error.WouldBlock;
return self.arena[self.base..][0..required_bytes];
}
/// Discard only the current unpublished response, including a partial begin.
/// Earlier snapshots remain frozen. The adapter must discard its draft metadata.
pub fn discardDraft(self: *Writer) !void {
if (self.frozen or self.headers_committed) return error.InvalidState;
self.open(self.base, self.keep_alive, self.head_only);
}
pub fn begin(self: *Writer, status: u16, content_type: []const u8, length: ?usize) !void {
return self.beginWithHeaders(status, content_type, length, "");
}
/// Extra fields are complete name/value lines ending in CRLF.
/// The writer validates framing before changing its state or output.
/// This method copies Content-Type and extra fields before returning.
/// Arena-backed arguments must start beyond the current snapshot's header_reserve_bytes prefix.
/// The adapter must keep its staged arguments disjoint.
/// Callers reserve additional head space before dispatch; begin keeps its fixed reserve.
pub fn beginWithHeaders(self: *Writer, status: u16, content_type: []const u8, length: ?usize, extra_headers: []const u8) !void {
if (self.frozen or self.began or self.headers_committed) return error.InvalidState;
if (status < 200 or status > 599 or content_type.len > max_content_type_bytes) return error.InvalidResponse;
for (content_type) |byte| if (byte < 32 or byte > 126) return error.InvalidResponse;
try validateHeaderBlock(extra_headers);
const head_bound = std.math.add(usize, header_reserve_bytes, extra_headers.len) catch return error.InvalidResponse;
if (head_bound > self.arena.len - self.buffered) return error.WouldBlock;
self.status = status;
self.content_type = content_type;
self.content_length = length;
self.began = true;
// The scheduler only dispatches with header_reserve_bytes free.
assert(self.arena.len - self.buffered >= header_reserve_bytes);
var n = self.buffered;
const out = self.arena;
if (status == 200) {
// Fixed-size copy of the cached prefix; the reserve guarantees room
// and the logical end advances by the prefix's real length.
const cache = self.header_cache;
out[n..][0..cache.ok_prefix.len].* = cache.ok_prefix;
n += cache.ok_prefix_len;
} else {
@memcpy(out[n..][0..9], "HTTP/1.1 ");
n += 9;
out[n] = @intCast('0' + status / 100);
out[n + 1] = @intCast('0' + (status / 10) % 10);
out[n + 2] = @intCast('0' + status % 10);
out[n + 3] = ' ';
n += 4;
const text = reason(status);
@memcpy(out[n..][0..text.len], text);
n += text.len;
const server = "\r\nServer: bounded-http\r\nDate: ";
@memcpy(out[n..][0..server.len], server);
n += server.len;
@memcpy(out[n..][0..29], &self.header_cache.date);
n += 29;
@memcpy(out[n..][0..2], "\r\n");
n += 2;
}
@memcpy(out[n..][0..14], "Content-Type: ");
n += 14;
copyShort(out[n..], content_type);
self.content_type = out[n..][0..content_type.len];
n += content_type.len;
@memcpy(out[n..][0..2], "\r\n");
n += 2;
if (status != 204 and status != 304) {
if (length) |value| {
@memcpy(out[n..][0..16], "Content-Length: ");
n += 16;
n += putDecimal(out[n..], value);
@memcpy(out[n..][0..2], "\r\n");
n += 2;
} else {
const coding = "Transfer-Encoding: chunked\r\n";
@memcpy(out[n..][0..coding.len], coding);
n += coding.len;
}
}
if (!self.keep_alive) {
const close = "Connection: close\r\n";
@memcpy(out[n..][0..close.len], close);
n += close.len;
}
std.mem.copyForwards(u8, out[n..][0..extra_headers.len], extra_headers);
n += extra_headers.len;
@memcpy(out[n..][0..2], "\r\n");
n += 2;
if (self.chunked()) {
self.chunk_size_at = n;
n += chunk_size_field_bytes;
}
assert(n - self.buffered <= head_bound);
self.buffered = n;
self.body_start = n;
}
pub fn reserve(self: *Writer, count: usize) ![]u8 {
if (self.frozen or self.borrowed != null or self.reserved != 0) return error.InvalidState;
if (count > self.arena.len - self.buffered - self.slack()) return error.WouldBlock;
self.reserved = count;
return self.arena[self.buffered..][0..count];
}
pub fn commit(self: *Writer, count: usize) void {
assert(!self.frozen);
assert(count <= self.reserved);
assert(count <= self.arena.len - self.buffered - self.slack());
self.buffered += count;
self.reserved = 0;
}
/// Convenience copying path. reserve/commit writes directly into output storage.
pub fn write(self: *Writer, bytes: []const u8) !void {
const destination = try self.reserve(bytes.len);
@memcpy(destination, bytes);
self.commit(bytes.len);
}
/// Copy staged body bytes after begin, before publishing the response.
/// The source may overlap the destination in either direction.
/// The writer counts this copy separately from small borrowed-body copies.
pub fn writeDraftBody(self: *Writer, body: []const u8) !void {
if (!self.began or self.headers_committed) return error.InvalidState;
const copied = std.math.add(usize, self.draft_copy_bytes, body.len) catch return error.InvalidResponse;
const destination = try self.reserve(body.len);
if (@intFromPtr(destination.ptr) <= @intFromPtr(body.ptr)) {
std.mem.copyForwards(u8, destination, body);
} else {
std.mem.copyBackwards(u8, destination, body);
}
self.commit(body.len);
self.draft_copy_bytes = copied;
}
/// Storage must be request-owned input or immutable server-lifetime assets;
/// there is no dynamic lease-release notification yet. Spans up to the
/// configured copy threshold are copied into the arena when they fit, which
/// keeps small responses in one span; the copy is counted, never hidden.
pub fn borrow(self: *Writer, bytes: []const u8) !void {
if (self.frozen or self.generatedBytes() != 0 or self.reserved != 0 or self.borrowed != null)
return error.InvalidState;
if (bytes.len <= self.copy_threshold and bytes.len <= self.arena.len - self.buffered - self.slack()) {
copyShort(self.arena[self.buffered..], bytes);
self.buffered += bytes.len;
self.copied_borrow = true;
return;
}
self.borrowed = bytes;
}
pub fn flush(self: *Writer) Action {
assert(!self.frozen and self.reserved == 0 and self.began);
self.frozen = true;
return .flush;
}
pub fn finish(self: *Writer) Action {
assert(!self.frozen and self.reserved == 0 and self.began);
self.frozen = true;
return .finish;
}
/// Bytes generated into the arena for this snapshot, after the head.
pub fn generatedBytes(self: *const Writer) usize {
return self.buffered - self.body_start;
}
/// Logical body length of this snapshot: generated or borrowed bytes.
pub fn bodyBytes(self: *const Writer) usize {
return self.generatedBytes() + if (self.borrowed) |span| span.len else 0;
}
/// Committed body bytes as one slice: generated arena bytes or the borrow.
pub fn committed(self: *const Writer) []const u8 {
assert(self.frozen);
return self.borrowed orelse self.arena[self.body_start..self.buffered];
}
pub fn release(self: *Writer) void {
assert(self.frozen);
self.reserved = 0;
self.borrowed = null;
self.frozen = false;
}
};
fn testCache() HeaderCache {
var cache: HeaderCache = .{};
cache.refresh("Sat, 05 Sep 2026 12:34:56 GMT");
return cache;
}
test "blocking flush rejects unavailable, cancelled and unpublished states without freezing" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
var request: http.Request = undefined;
var state: [8]usize = @splat(0);
var cancelled: std.atomic.Value(bool) = .init(false);
var called = false;
var context: Context = .{
.request = &request,
.writer = &writer,
.event = .request,
.state = &state,
.application = null,
.cancelled = &cancelled,
};
try std.testing.expect(!context.supportsBlockingFlush());
try std.testing.expectError(error.BlockingFlushUnavailable, context.flushAndWait());
context.blocking_flush = .{ .context = &called, .flush = struct {
fn flush(pointer: *anyopaque) FlushError!void {
const value: *bool = @ptrCast(@alignCast(pointer));
value.* = true;
}
}.flush };
try std.testing.expect(context.supportsBlockingFlush());
try std.testing.expectError(error.InvalidState, context.flushAndWait());
try writer.begin(200, "text/plain", null);
_ = try writer.reserve(1);
try std.testing.expectError(error.InvalidState, context.flushAndWait());
writer.commit(0);
cancelled.store(true, .release);
try std.testing.expectError(error.Cancelled, context.flushAndWait());
try std.testing.expect(!writer.frozen and !called);
cancelled.store(false, .release);
try context.flushAndWait();
try std.testing.expect(writer.frozen and called);
try std.testing.expectError(error.InvalidState, context.flushAndWait());
}
test "request timeout overrides require a target, stay bounded and stop after cancellation" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
var request: http.Request = undefined;
var state: [8]usize = @splat(0);
var cancelled: std.atomic.Value(bool) = .init(false);
var context: Context = .{
.request = &request,
.writer = &writer,
.event = .request,
.state = &state,
.application = null,
.cancelled = &cancelled,
};
try std.testing.expectError(error.RequestTimeoutUnavailable, context.setRequestTimeout(1000));
var target: u32 = 0;
context.requested_timeout_ms = ⌖
context.max_timeout_ms = 60_000;
try std.testing.expectError(error.InvalidRequestTimeout, context.setRequestTimeout(0));
try std.testing.expectError(error.InvalidRequestTimeout, context.setRequestTimeout(60_001));
try std.testing.expectEqual(@as(u32, 0), target);
try context.setRequestTimeout(60_000);
try std.testing.expectEqual(@as(u32, 60_000), target);
try context.setRequestTimeout(1);
try std.testing.expectEqual(@as(u32, 1), target);
cancelled.store(true, .release);
try std.testing.expectError(error.Cancelled, context.setRequestTimeout(2));
try std.testing.expectEqual(@as(u32, 1), target);
}
test "begin writes the head into the arena and flush keeps the snapshot" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
try writer.begin(200, "text/plain", 7);
const head = "HTTP/1.1 200 OK\r\nServer: bounded-http\r\nDate: Sat, 05 Sep 2026 12:34:56 GMT\r\nContent-Type: text/plain\r\nContent-Length: 7\r\n\r\n";
try std.testing.expectEqualStrings(head, arena[0..writer.body_start]);
const reserved = try writer.reserve(8);
@memcpy(reserved[0..3], "one");
writer.commit(3);
try writer.write(" two");
try std.testing.expectEqual(Action.flush, writer.flush());
try std.testing.expectEqualStrings("one two", writer.committed());
try std.testing.expectEqualStrings(head ++ "one two", arena[0..writer.buffered]);
try std.testing.expectError(error.InvalidState, writer.reserve(1));
writer.release();
try std.testing.expectEqual(@as(usize, 7), writer.generatedBytes());
}
test "non-200 heads, close and chunked size fields are laid out exactly" {
var arena: [2048]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(100, false, false);
try writer.begin(404, "text/html; charset=utf-8", null);
const head = "HTTP/1.1 404 Not Found\r\nServer: bounded-http\r\nDate: Sat, 05 Sep 2026 12:34:56 GMT\r\n" ++
"Content-Type: text/html; charset=utf-8\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
try std.testing.expectEqualStrings(head, arena[100 .. 100 + head.len]);
try std.testing.expectEqual(@as(usize, 100 + head.len), writer.chunk_size_at.?);
try std.testing.expectEqual(@as(usize, 100 + head.len + chunk_size_field_bytes), writer.body_start);
var field: [chunk_size_field_bytes]u8 = undefined;
putChunkSize(&field, 0xabc);
try std.testing.expectEqualStrings("00000abc\r\n", &field);
var decimal: [20]u8 = undefined;
try std.testing.expectEqualStrings("0", decimal[0..putDecimal(&decimal, 0)]);
try std.testing.expectEqualStrings("18446744073709551615", decimal[0..putDecimal(&decimal, std.math.maxInt(usize))]);
}
test "borrow copies small spans when allowed and keeps large spans borrowed" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 16);
writer.open(0, true, false);
try writer.begin(200, "text/plain", 13);
try writer.borrow("Hello, World!");
try std.testing.expect(writer.copied_borrow and writer.borrowed == null);
try std.testing.expectEqual(@as(usize, 13), writer.bodyBytes());
_ = writer.finish();
try std.testing.expectEqualStrings("Hello, World!", writer.committed());
writer.release();
var large = Writer.init(&arena, &cache, 16);
large.open(0, true, false);
try large.begin(200, "application/octet-stream", 32);
const body = "0123456789abcdef0123456789abcdef";
try large.borrow(body);
try std.testing.expect(!large.copied_borrow);
try std.testing.expectEqual(body.ptr, large.borrowed.?.ptr);
_ = large.finish();
try std.testing.expectEqual(body.ptr, large.committed().ptr);
var strict = Writer.init(&arena, &cache, 0);
strict.open(0, true, false);
try strict.begin(200, "text/plain", 13);
try strict.borrow("Hello, World!");
try std.testing.expect(!strict.copied_borrow and strict.borrowed != null);
}
test "reservation capacity errors are recoverable and leave slack for chunk framing" {
var arena: [header_reserve_bytes + 32]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
try writer.begin(200, "text/plain", null);
const free = arena.len - writer.buffered - chunk_slack_bytes;
try std.testing.expectError(error.WouldBlock, writer.reserve(free + 1));
_ = try writer.reserve(free);
writer.commit(free);
try std.testing.expectEqual(chunk_slack_bytes, arena.len - writer.buffered);
_ = writer.flush();
writer.headers_committed = true; // The I/O owner records the sent head.
writer.release();
writer.resumeSnapshot(0);
try std.testing.expectEqual(@as(usize, 0), writer.chunk_size_at.?);
try std.testing.expectEqual(chunk_size_field_bytes, writer.body_start);
try std.testing.expectError(error.InvalidState, writer.begin(200, "text/plain", null));
}
test "extra header validation is transactional and bounded before begin" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
try std.testing.expectError(error.InvalidHeader, writer.beginWithHeaders(200, "text/plain", 0, "Bad Name: x\r\n"));
try std.testing.expectError(error.InvalidHeader, writer.beginWithHeaders(200, "text/plain", 0, "X: missing terminator"));
try std.testing.expectError(error.ReservedHeader, writer.beginWithHeaders(200, "text/plain", 0, "Connection: close\r\n"));
try std.testing.expect(!writer.began and writer.buffered == 0);
try writer.beginWithHeaders(303, "text/plain", 0, "Location: /next\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n");
_ = writer.finish();
try std.testing.expect(std.mem.find(u8, arena[0..writer.buffered], "HTTP/1.1 303 See Other\r\n") != null);
try std.testing.expect(std.mem.endsWith(u8, arena[0..writer.buffered], "Location: /next\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n\r\n"));
writer.release();
writer.open(arena.len - header_reserve_bytes, true, false);
try std.testing.expectError(error.WouldBlock, writer.beginWithHeaders(200, "text/plain", 0, "X: y\r\n"));
try std.testing.expect(!writer.began and writer.buffered == writer.base);
try writer.begin(200, "text/plain", 0);
}
test "draft storage excludes frozen prefixes and discard preserves request facts" {
var arena: [1024]u8 = @splat(0xa5);
const cache = testCache();
const prefix = "older frozen response";
@memcpy(arena[0..prefix.len], prefix);
var writer = Writer.init(&arena, &cache, 0);
writer.open(prefix.len, false, true);
const scratch = try writer.draftStorage(arena.len - prefix.len);
try std.testing.expectEqual(arena[prefix.len..].ptr, scratch.ptr);
try std.testing.expectEqual(arena.len - prefix.len, scratch.len);
try std.testing.expectError(error.WouldBlock, writer.draftStorage(scratch.len + 1));
try std.testing.expectEqual(@as(usize, 0), (try writer.draftStorage(0)).len);
@memset(scratch, 'x');
try writer.discardDraft();
try writer.discardDraft();
try std.testing.expectEqualStrings(prefix, arena[0..prefix.len]);
try std.testing.expect(!writer.keep_alive and writer.head_only);
try writer.begin(200, "text/plain", 3);
try writer.writeDraftBody("old");
try std.testing.expectError(error.InvalidState, writer.draftStorage(0));
try writer.discardDraft();
try std.testing.expectEqual(@as(usize, 0), writer.draft_copy_bytes);
try writer.begin(500, "text/plain", 3);
try writer.writeDraftBody("new");
_ = writer.finish();
try std.testing.expectEqualStrings("new", writer.committed());
try std.testing.expectEqualStrings(prefix, arena[0..prefix.len]);
try std.testing.expectError(error.InvalidState, writer.discardDraft());
try std.testing.expectError(error.InvalidState, writer.draftStorage(0));
try std.testing.expectError(error.InvalidState, writer.writeDraftBody(""));
}
test "draft state rejects active reservations borrows and transmitted heads" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
try std.testing.expectError(error.InvalidState, writer.writeDraftBody("not begun"));
_ = try writer.reserve(1);
try std.testing.expectError(error.InvalidState, writer.draftStorage(0));
try writer.discardDraft();
try writer.borrow("immutable asset");
try std.testing.expectError(error.InvalidState, writer.draftStorage(0));
try writer.discardDraft();
try writer.begin(200, "text/plain", null);
_ = writer.flush();
writer.release();
writer.headers_committed = true;
writer.resumeSnapshot(0);
try std.testing.expectError(error.InvalidState, writer.discardDraft());
try std.testing.expectError(error.InvalidState, writer.draftStorage(0));
try std.testing.expectError(error.InvalidState, writer.writeDraftBody(""));
}
test "draft body copies overlap in both directions and count only committed bytes" {
const text = "abcdefgh";
inline for (.{ false, true }) |copy_backwards| {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
try writer.begin(200, "text/plain", 4 + text.len);
try writer.write("xxab");
const source_at = if (copy_backwards) writer.buffered - 2 else writer.buffered + 2;
@memcpy(arena[source_at..][0..text.len], text);
try writer.writeDraftBody(arena[source_at..][0..text.len]);
try std.testing.expectEqual(text.len, writer.draft_copy_bytes);
try std.testing.expectEqual(@as(usize, 0), writer.reserved);
const before = writer.buffered;
try std.testing.expectError(error.WouldBlock, writer.writeDraftBody(&arena));
try std.testing.expectEqual(before, writer.buffered);
try std.testing.expectEqual(text.len, writer.draft_copy_bytes);
_ = writer.finish();
try std.testing.expectEqualStrings("xxab" ++ text, writer.committed());
}
}
test "draft header aliases copy before storage is reused and preserve repeated fields" {
var arena: [2048]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
const scratch = try writer.draftStorage(arena.len);
const content_type = "application/example";
const fields = "X-Note: staged\r\nSet-Cookie: a=1\r\nSet-Cookie: b=2\r\n";
const type_at = header_reserve_bytes;
const fields_at = type_at + max_content_type_bytes;
@memcpy(scratch[type_at..][0..content_type.len], content_type);
@memcpy(scratch[fields_at..][0..fields.len], fields);
try writer.beginWithHeaders(201, scratch[type_at..][0..content_type.len], 0, scratch[fields_at..][0..fields.len]);
@memset(scratch[type_at..][0..content_type.len], 'x');
@memset(scratch[fields_at..][0..fields.len], 'x');
try std.testing.expectEqualStrings(content_type, writer.content_type);
_ = writer.finish();
try std.testing.expect(std.mem.find(u8, arena[0..writer.body_start], "Content-Type: application/example\r\n") != null);
try std.testing.expect(std.mem.endsWith(u8, arena[0..writer.body_start], fields ++ "\r\n"));
}
test "timer waits reject output ownership and cancellation without publication" {
var arena: [1024]u8 = undefined;
const cache = testCache();
var writer = Writer.init(&arena, &cache, 0);
writer.open(0, true, false);
var request: http.Request = undefined;
var state: [8]usize = @splat(0);
var cancelled: std.atomic.Value(bool) = .init(false);
var context: Context = .{ .request = &request, .writer = &writer, .event = .request, .state = &state, .application = null, .cancelled = &cancelled };
try std.testing.expectError(error.NotificationUnavailable, context.notification());
try std.testing.expectError(error.NotificationUnavailable, context.waitNotification(null));
var cell: Notification.Cell = .{};
try cell.activate();
context.notification_cell = &cell;
try std.testing.expectEqual(Action.wait, try context.waitNotification(null));
try std.testing.expect(context.await_notification and context.resume_after_ns == null);
try std.testing.expectEqual(Action.wait, try context.waitNotification(42));
try std.testing.expect(context.await_notification and context.resume_after_ns.? == 42);
context.requestCancellation();
try std.testing.expect(context.notify_cancel);
try std.testing.expectEqual(Action.wait, try context.wait(0));
try std.testing.expectEqual(@as(?u64, 0), context.resume_after_ns);
try std.testing.expect(!context.await_notification);
try writer.begin(200, "text/plain", null);
try std.testing.expectError(error.InvalidState, context.wait(1));
_ = writer.flush();
try std.testing.expectError(error.InvalidState, context.wait(1));
writer.headers_committed = true;
writer.release();
writer.resumeSnapshot(0);
try std.testing.expectEqual(Action.wait, try context.wait(std.math.maxInt(u64)));
_ = try writer.reserve(1);
try std.testing.expectError(error.InvalidState, context.wait(1));
writer.commit(1);
try std.testing.expectError(error.InvalidState, context.wait(1));
cancelled.store(true, .release);
try std.testing.expectError(error.Cancelled, context.wait(1));
try std.testing.expectError(error.Cancelled, context.notification());
try std.testing.expectError(error.Cancelled, context.waitNotification(null));
}
test "notification cells coalesce, reject stale generations, and retire without wrapping" {
var cell: Notification.Cell = .{};
try std.testing.expect(cell.handle() == null);
try cell.activate();
const first = cell.handle().?;
try std.testing.expectEqual(Notification.Result.notified, first.signal());
try std.testing.expectEqual(Notification.Result.coalesced, first.signal());
try std.testing.expect(cell.consume());
try std.testing.expect(!cell.consume());
try std.testing.expectEqual(Notification.Result.notified, first.signal());
cell.deactivate();
try std.testing.expectEqual(Notification.Result.stale, first.signal());
try std.testing.expect(!cell.consume());
try cell.activate();
const second = cell.handle().?;
try std.testing.expect(first.generation != second.generation);
try std.testing.expectEqual(Notification.Result.stale, first.signal());
try std.testing.expect(!cell.consume());
try std.testing.expectEqual(Notification.Result.notified, second.signal());
cell.deactivate();
cell.state.store(std.math.maxInt(u64) & ~@as(u64, 3), .release);
try std.testing.expectError(error.NotificationGenerationExhausted, cell.activate());
try std.testing.expect(cell.handle() == null);
try std.testing.expectEqual(Notification.Result.stale, second.signal());
}
test "concurrent producers publish one coalesced notification" {
const Producer = struct {
handle: Notification,
result: Notification.Result = .stale,
fn run(self: *@This()) void {
self.result = self.handle.signal();
}
};
var cell: Notification.Cell = .{};
try cell.activate();
var producers: [8]Producer = @splat(.{ .handle = cell.handle().? });
var threads: [8]std.Thread = undefined;
var started: usize = 0;
{
defer for (threads[0..started]) |thread| thread.join();
for (&threads, &producers) |*thread, *producer| {
thread.* = try std.Thread.spawn(.{}, Producer.run, .{producer});
started += 1;
}
}
var notified: usize = 0;
for (producers) |producer| {
try std.testing.expect(producer.result != .stale);
if (producer.result == .notified) notified += 1;
}
try std.testing.expectEqual(@as(usize, 1), notified);
try std.testing.expect(cell.consume());
try std.testing.expect(!cell.consume());
cell.deactivate();
}