lib/http/src/client/websocket/model.zig
daab053ee43316e1809a84551d573ddd1e5bf3d2
1 const std = @import("std");
2 const alloc_phase = @import("alloc_phase");
3
4 pub const frame_header_bytes: usize = 14;
5
6 pub const Limits = struct {
7 websocket_count: usize,
8 frame_payload_bytes_per_websocket: usize,
9 };
10
11 pub const Capacity = struct {
12 websocket_count: usize,
13 frame_payload_bytes_per_websocket: usize,
14 frame_bytes_per_websocket: usize,
15 storage_bytes: usize,
16
17 pub fn derive(limits: Limits) error{CapacityOverflow}!Capacity {
18 const frame_bytes = try alloc_phase.capacity.add(
19 usize,
20 frame_header_bytes,
21 limits.frame_payload_bytes_per_websocket,
22 );
23 const socket_bytes = try alloc_phase.capacity.mul(
24 usize,
25 frame_bytes,
26 2,
27 );
28 const storage_bytes = try alloc_phase.capacity.mul(
29 usize,
30 limits.websocket_count,
31 socket_bytes,
32 );
33 return .{
34 .websocket_count = limits.websocket_count,
35 .frame_payload_bytes_per_websocket = limits.frame_payload_bytes_per_websocket,
36 .frame_bytes_per_websocket = frame_bytes,
37 .storage_bytes = storage_bytes,
38 };
39 }
40 };
41
42 pub const Scratch = struct {
43 read: []u8,
44 write: []u8,
45 frame_payload_bytes: usize,
46 };
47
48 test "Client WebSocket capacity matches independent arithmetic" {
49 comptime {
50 @stardustClaim(
51 @import("alloc_phase").capacity.witness(@import("./root.zig").ClientWebsocketStorage, "http_client_websocket_capacity"),
52 null,
53 null,
54 null,
55 null,
56 null,
57 null,
58 );
59 }
60
61 const limits = Limits{
62 .websocket_count = 3,
63 .frame_payload_bytes_per_websocket = 257,
64 };
65 const capacity = try Capacity.derive(limits);
66 try std.testing.expectEqual(@as(usize, 271), capacity.frame_bytes_per_websocket);
67 try std.testing.expectEqual(@as(usize, 1626), capacity.storage_bytes);
68 }
69
70 test "Client WebSocket capacity rejects arithmetic overflow" {
71 try std.testing.expectError(
72 error.CapacityOverflow,
73 Capacity.derive(.{
74 .websocket_count = std.math.maxInt(usize),
75 .frame_payload_bytes_per_websocket = 1,
76 }),
77 );
78 try std.testing.expectError(
79 error.CapacityOverflow,
80 Capacity.derive(.{
81 .websocket_count = 1,
82 .frame_payload_bytes_per_websocket = std.math.maxInt(usize),
83 }),
84 );
85 }