Something went wrong. Try again.
An HTTP library for Zig 0.17, server and client, HTTP/1.0 through HTTP/3, with the protocol in a module that owns no socket.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What origins have said, with `Alt-Svc`, about where else they can be//! reached over HTTP/3.//!//! RFC 7838 is how a server that is answering over TCP says that it also//! speaks HTTP/3, and where: `Alt-Svc: h3=":443"; ma=86400` on any response//! means that for the next day the same origin can be had over QUIC on port//! 443 of the same host. It is the way browsers find HTTP/3, and it has to be//! remembered, since the first request to an origin can only go over TCP --//! nothing has yet been said.//!//! This is that memory: a fixed table of origins, each with the one HTTP/3//! alternative it most prefers, when that stops being fresh, and whether it//! has recently failed. It allocates nothing -- the table is inline, and a//! host name is at most 255 octets -- and it has a lock, so that one cache can//! be shared by several `Client`s on several tasks and what one of them learns//! the others use.//!//! Only `h3` is kept. An origin advertising `h2` elsewhere is offering nothing//! a TCP connection with ALPN did not already get, and the drafts' `h3-29`//! and the rest are versions this library does not speak.
const std = @import("std");const Io = std.Io;
const http = @import("http");const Headers = http.protocol.Headers;const token = http.protocol.token;
const AltSvc = @This();
/// How many origins are remembered. When the table is full, the entry that/// expires soonest makes room.pub const capacity = 32;
/// §3.1: "considered fresh for 24 hours from generation of the message"/// when `ma` does not say otherwise.pub const default_max_age_s: u64 = 24 * 60 * 60;
/// How long an alternative that failed is left alone. §2.4 lets a client fall/// back to the origin when an alternative "fails or is unresponsive"; without/// this, every fetch would try it again and pay the handshake timeout again,/// and a network that drops UDP would make every request slower rather than/// one.pub const broken_for_s: u64 = 5 * 60;
mutex: Io.Mutex = .init,entries: [capacity]Entry = undefined,len: usize = 0,
const Name = struct { buf: [255]u8 = undefined, len: u8 = 0,
fn set(n: *Name, text: []const u8) bool { if (text.len > n.buf.len) return false; // Stored lowercase, so that `EXAMPLE.com` and `example.com` are one // origin: §4.3.1 of RFC 9110 compares hosts without case. for (text, 0..) |c, i| n.buf[i] = std.ascii.toLower(c); n.len = @intCast(text.len); return true; }
fn slice(n: *const Name) []const u8 { return n.buf[0..n.len]; }
fn eql(n: *const Name, text: []const u8) bool { return std.ascii.eqlIgnoreCase(n.slice(), text); }};
const Entry = struct { origin: Name, origin_port: u16, /// Empty for "the same host", which is what `h3=":443"` says. alternative: Name, alternative_port: u16, /// Nanoseconds on the awake clock. expires: i96, /// Nanoseconds on the awake clock; zero when it has not failed. broken_until: i96 = 0,};
/// Where to send an origin's requests over HTTP/3.pub const Target = struct { buf: [255]u8, len: u8, port: u16,
/// The host to connect to. Empty for the origin's own, which is what an /// alternative that named no host means. pub fn host(t: *const Target) []const u8 { return t.buf[0..t.len]; }
test host { const gpa = testing.allocator; var cache: AltSvc = .{}; var named = try headersOf(gpa, &.{.{ "Alt-Svc", "h3=\"alt.example.com:8443\"" }}); defer named.deinit(gpa); cache.learn(testing.io, "example.com", 443, &named); try testing.expectEqualStrings("alt.example.com", cache.lookup(testing.io, "example.com", 443).?.host());
// `:443` names a port and no host: the origin's own name is dialled. var unnamed = try headersOf(gpa, &.{.{ "Alt-Svc", "h3=\":443\"" }}); defer unnamed.deinit(gpa); cache.learn(testing.io, "example.org", 443, &unnamed); try testing.expectEqualStrings("", cache.lookup(testing.io, "example.org", 443).?.host()); }};
fn now(io: Io) i96 { return Io.Clock.awake.now(io).nanoseconds;}
fn seconds(s: u64) i96 { return @as(i96, @intCast(@min(s, std.math.maxInt(u64) / 2))) * std.time.ns_per_s;}
/// The fresh, working HTTP/3 alternative for an origin, if there is one.pub fn lookup(a: *AltSvc, io: Io, origin_host: []const u8, origin_port: u16) ?Target { a.mutex.lockUncancelable(io); defer a.mutex.unlock(io); return a.lookupAt(now(io), origin_host, origin_port);}
test lookup { const gpa = testing.allocator; const io = testing.io; var cache: AltSvc = .{}; // Nothing is known of an origin until one of its responses has said so. try testing.expect(cache.lookup(io, "example.com", 443) == null);
var h = try headersOf(gpa, &.{.{ "Alt-Svc", "h3=\":8443\"; ma=3600" }}); defer h.deinit(gpa); cache.learn(io, "example.com", 443, &h);
const target = cache.lookup(io, "EXAMPLE.com", 443).?; try testing.expectEqualStrings("", target.host()); try testing.expectEqual(@as(u16, 8443), target.port); // Another port is another origin. try testing.expect(cache.lookup(io, "example.com", 8080) == null);}
fn lookupAt(a: *AltSvc, at: i96, origin_host: []const u8, origin_port: u16) ?Target { const i = a.find(origin_host, origin_port) orelse return null; const e = &a.entries[i]; if (e.expires <= at) { a.removeAt(i); return null; } if (e.broken_until > at) return null; var t: Target = .{ .buf = undefined, .len = e.alternative.len, .port = e.alternative_port }; @memcpy(t.buf[0..e.alternative.len], e.alternative.slice()); return t;}
/// Takes in whatever `Alt-Svc` fields a response from this origin carried.////// §3.1: "When an Alt-Svc response header field is received from an origin,/// its value invalidates and replaces all cached alternative services for/// that origin." So a response that advertises only `h2` elsewhere, or says/// `clear`, leaves nothing behind for it; one with no `Alt-Svc` at all changes/// nothing.////// Only from a response to an `https` request made directly: §2.1 wants/// "reasonable assurances that the alternative service is under control of/// and valid for the whole origin", which a response over TLS gives and one/// over cleartext or relayed by a proxy does not. That is the caller's to/// know; this does not ask.pub fn learn(a: *AltSvc, io: Io, origin_host: []const u8, origin_port: u16, headers: *const Headers) void { if (headers.get("alt-svc") == null) return; const age = ageOf(headers); const chosen = choose(headers);
a.mutex.lockUncancelable(io); defer a.mutex.unlock(io); a.learnAt(now(io), origin_host, origin_port, chosen, age);}
test learn { const gpa = testing.allocator; const io = testing.io; var cache: AltSvc = .{};
var advertised = try headersOf(gpa, &.{.{ "Alt-Svc", "h2=\":443\", h3=\":443\"; ma=86400" }}); defer advertised.deinit(gpa); cache.learn(io, "example.com", 443, &advertised); try testing.expectEqual(@as(u16, 443), cache.lookup(io, "example.com", 443).?.port);
// A response with no `Alt-Svc` changes nothing... var silent = try headersOf(gpa, &.{.{ "Content-Type", "text/plain" }}); defer silent.deinit(gpa); cache.learn(io, "example.com", 443, &silent); try testing.expect(cache.lookup(io, "example.com", 443) != null);
// ...and one that says `clear` forgets what the origin said before. var cleared = try headersOf(gpa, &.{.{ "Alt-Svc", "clear" }}); defer cleared.deinit(gpa); cache.learn(io, "example.com", 443, &cleared); try testing.expect(cache.lookup(io, "example.com", 443) == null);}
fn learnAt(a: *AltSvc, at: i96, origin_host: []const u8, origin_port: u16, chosen: ?Advertised, age: u64) void { const existing = a.find(origin_host, origin_port); // A failure is remembered across the replacement when it is the same // alternative being advertised again -- which, from a server that keeps // saying it, is every response. Otherwise the mark would last exactly // until the next response, which is no time at all. var broken_until: i96 = 0; if (existing) |i| { const old = &a.entries[i]; if (chosen) |c| { if (old.alternative.eql(c.host) and old.alternative_port == c.port) { broken_until = old.broken_until; } } a.removeAt(i); }
const c = chosen orelse return; // §3.1's arithmetic: `ma` counts from when the response was generated, // and `Age` is how long ago that was. if (c.max_age_s <= age) return; const expires = at + seconds(c.max_age_s - age);
var e: Entry = .{ .origin = .{}, .origin_port = origin_port, .alternative = .{}, .alternative_port = c.port, .expires = expires, .broken_until = broken_until, }; if (!e.origin.set(origin_host) or !e.alternative.set(c.host)) return;
if (a.len == capacity) { // The one that would go soonest anyway. var soonest: usize = 0; for (a.entries[0..a.len], 0..) |*other, i| { if (other.expires < a.entries[soonest].expires) soonest = i; } a.removeAt(soonest); } a.entries[a.len] = e; a.len += 1;}
/// Says the origin's alternative did not work, so that it is left alone for/// `broken_for_s` and the origin is reached over TCP meanwhile.pub fn markBroken(a: *AltSvc, io: Io, origin_host: []const u8, origin_port: u16) void { a.mutex.lockUncancelable(io); defer a.mutex.unlock(io); a.markBrokenAt(now(io), origin_host, origin_port);}
test markBroken { const gpa = testing.allocator; const io = testing.io; var cache: AltSvc = .{}; var h = try headersOf(gpa, &.{.{ "Alt-Svc", "h3=\":443\"" }}); defer h.deinit(gpa); cache.learn(io, "example.com", 443, &h);
cache.markBroken(io, "example.com", 443); try testing.expect(cache.lookup(io, "example.com", 443) == null);
// Advertised again, as the next response over TCP will be: still left // alone until `broken_for_s` has passed. cache.learn(io, "example.com", 443, &h); try testing.expect(cache.lookup(io, "example.com", 443) == null);}
fn markBrokenAt(a: *AltSvc, at: i96, origin_host: []const u8, origin_port: u16) void { const i = a.find(origin_host, origin_port) orelse return; a.entries[i].broken_until = at + seconds(broken_for_s);}
/// Forgets everything, which §2.2 has a client do "when they detect" a change/// of network: an alternative chosen for one network may be a poor one on the/// next. This cannot see the network, so a caller that can calls this.pub fn clear(a: *AltSvc, io: Io) void { a.mutex.lockUncancelable(io); defer a.mutex.unlock(io); a.len = 0;}
test clear { const gpa = testing.allocator; const io = testing.io; var cache: AltSvc = .{}; var h = try headersOf(gpa, &.{.{ "Alt-Svc", "h3=\":443\"" }}); defer h.deinit(gpa); cache.learn(io, "example.com", 443, &h); cache.learn(io, "example.org", 443, &h);
cache.clear(io); try testing.expect(cache.lookup(io, "example.com", 443) == null); try testing.expect(cache.lookup(io, "example.org", 443) == null);}
fn find(a: *const AltSvc, origin_host: []const u8, origin_port: u16) ?usize { for (a.entries[0..a.len], 0..) |*e, i| { if (e.origin_port == origin_port and e.origin.eql(origin_host)) return i; } return null;}
fn removeAt(a: *AltSvc, i: usize) void { a.entries[i] = a.entries[a.len - 1]; a.len -= 1;}
// -- the field ---------------------------------------------------------------
/// One `h3` alternative, as a field advertised it. `host` borrows the field.const Advertised = struct { host: []const u8, port: u16, max_age_s: u64,};
/// The `Age` of a response, which §3.1 subtracts from `ma`. Zero when absent/// or unreadable, which is the reading that keeps an alternative longest --/// and a malformed `Age` is the server's to have sent.fn ageOf(headers: *const Headers) u64 { const text = headers.get("age") orelse return 0; return std.fmt.parseInt(u64, token.trimOws(text), 10) catch 0;}
/// The `h3` alternative the response most prefers, or null when it offers/// none -- including when it says `clear`.////// §3: "the order of the values reflects the server's preference", across/// every `Alt-Svc` line the response carried, in order. A `clear` anywhere/// clears the lot, "including those specified in the same response".fn choose(headers: *const Headers) ?Advertised { var best: ?Advertised = null; var fields = headers.values("alt-svc"); while (fields.next()) |field| { var it: Parser = .{ .text = field }; while (it.next()) |value| switch (value) { .clear => return null, .alternative => |alt| { if (best == null and std.mem.eql(u8, alt.protocol, "h3")) best = alt.advertised; }, }; } return best;}
const Value = union(enum) { clear, alternative: struct { protocol: []const u8, advertised: Advertised },};
/// §3's grammar, one `alt-value` at a time. A value that does not parse is/// skipped to the next comma rather than failing the field: one malformed/// alternative is not a reason to ignore a well-formed one beside it.const Parser = struct { text: []const u8, at: usize = 0,
fn next(p: *Parser) ?Value { while (true) { p.skip(" \t,"); if (p.at >= p.text.len) return null; const start = p.at; if (p.value()) |v| return v; // Malformed: to the next comma outside a quoted string. p.at = start; p.skipValue(); } }
fn value(p: *Parser) ?Value { const protocol = p.takeToken() orelse return null; p.skip(" \t"); if (p.at >= p.text.len or p.text[p.at] == ',') { // §3: `clear` is the whole of its field, and case-sensitive. return if (std.mem.eql(u8, protocol, "clear")) .clear else null; } if (p.text[p.at] != '=') return null; p.at += 1; var authority_buf: [300]u8 = undefined; const authority = p.takeQuoted(&authority_buf) orelse return null; const colon = std.mem.findScalarLast(u8, authority, ':') orelse return null; var host = authority[0..colon]; // §3.2.2 of RFC 3986: an IPv6 literal in an authority is bracketed. if (host.len >= 2 and host[0] == '[' and host[host.len - 1] == ']') host = host[1 .. host.len - 1]; const port = std.fmt.parseInt(u16, authority[colon + 1 ..], 10) catch return null; if (port == 0) return null; // `host` points into the quoted string's copy, which does not outlive // this call -- so only a host that needed no unescaping is kept, and // it is taken from the field itself. const field_host = p.hostInField(host) orelse return null;
var max_age_s = default_max_age_s; while (true) { p.skip(" \t"); if (p.at >= p.text.len or p.text[p.at] == ',') break; if (p.text[p.at] != ';') return null; p.at += 1; p.skip(" \t"); const name = p.takeToken() orelse return null; if (p.at >= p.text.len or p.text[p.at] != '=') return null; p.at += 1; var param_buf: [64]u8 = undefined; const param = if (p.at < p.text.len and p.text[p.at] == '"') p.takeQuoted(¶m_buf) orelse return null else p.takeToken() orelse return null; // §3: "Unknown parameters MUST be ignored." if (std.mem.eql(u8, name, "ma")) { max_age_s = std.fmt.parseInt(u64, param, 10) catch return null; } } return .{ .alternative = .{ .protocol = protocol, .advertised = .{ .host = field_host, .port = port, .max_age_s = max_age_s }, } }; }
/// The host as it appears in the field, when it appears there verbatim -- /// a quoted string with an escape in its host is not one worth keeping. fn hostInField(p: *const Parser, host: []const u8) ?[]const u8 { if (host.len == 0) return host; const at = std.mem.find(u8, p.text, host) orelse return null; return p.text[at..][0..host.len]; }
fn skip(p: *Parser, set: []const u8) void { while (p.at < p.text.len and std.mem.findScalar(u8, set, p.text[p.at]) != null) p.at += 1; }
fn takeToken(p: *Parser) ?[]const u8 { const start = p.at; while (p.at < p.text.len and token.isTokenChar(p.text[p.at])) p.at += 1; if (p.at == start) return null; return p.text[start..p.at]; }
/// §5.6.4 of RFC 9110's quoted-string, unescaped into `buf`. fn takeQuoted(p: *Parser, buf: []u8) ?[]const u8 { if (p.at >= p.text.len or p.text[p.at] != '"') return null; p.at += 1; var n: usize = 0; while (p.at < p.text.len) : (p.at += 1) { var c = p.text[p.at]; if (c == '"') { p.at += 1; return buf[0..n]; } if (c == '\\') { p.at += 1; if (p.at >= p.text.len) return null; c = p.text[p.at]; } if (n == buf.len) return null; buf[n] = c; n += 1; } return null; }
fn skipValue(p: *Parser) void { var quoted = false; while (p.at < p.text.len) : (p.at += 1) { const c = p.text[p.at]; if (quoted) { if (c == '\\') p.at += 1 else if (c == '"') quoted = false; } else if (c == '"') { quoted = true; } else if (c == ',') { return; } } }};
// -- tests -------------------------------------------------------------------
const testing = std.testing;
test { // So that `Target`'s example is compiled: a nested type's tests are // reached only when something refers to the type itself. testing.refAllDecls(@This());}
fn headersOf(gpa: std.mem.Allocator, lines: []const [2][]const u8) !Headers { var h: Headers = .empty; for (lines) |line| try h.append(gpa, line[0], line[1]); return h;}
test "RFC 7838 3: the examples, and what is chosen from them" { const gpa = testing.allocator; const Case = struct { field: []const u8, host: ?[]const u8, port: u16 = 0, ma: u64 = default_max_age_s }; const cases = [_]Case{ .{ .field = "h3=\":443\"", .host = "", .port = 443 }, .{ .field = "h3=\"new.example.org:8443\"; ma=3600", .host = "new.example.org", .port = 8443, .ma = 3600 }, // Preference is order, and only `h3` is kept. .{ .field = "h2=\"alt.example.com:8000\", h3=\":443\"; ma=60", .host = "", .port = 443, .ma = 60 }, .{ .field = "h3-29=\":443\", h3=\":8443\"", .host = "", .port = 8443 }, // §3: "Unknown parameters MUST be ignored", quoted or not. .{ .field = "h3=\":443\"; persist=1; foo=\"a;b,c\"; ma=10", .host = "", .port = 443, .ma = 10 }, .{ .field = "h3 = \":443\"", .host = null }, .{ .field = "h3=\"[2001:db8::1]:443\"", .host = "2001:db8::1", .port = 443 }, // A malformed value is skipped, and the good one after it kept. .{ .field = "h3=\"nocolon\", h3=\":444\"", .host = "", .port = 444 }, .{ .field = "h3=\":0\"", .host = null }, .{ .field = "h3=\":99999\"", .host = null }, .{ .field = "h2=\":443\"", .host = null }, .{ .field = "clear", .host = null }, // "including those specified in the same response" .{ .field = "h3=\":443\", clear", .host = null }, .{ .field = "", .host = null }, // As real servers send them, captured with curl: Google and YouTube // (no space after the comma), LiteSpeed (a space), and Cloudflare, // Facebook, nginx and Forgejo behind Caddy (one value). .{ .field = "h3=\":443\"; ma=2592000,h3-29=\":443\"; ma=2592000", .host = "", .port = 443, .ma = 2592000 }, .{ .field = "h3=\":443\"; ma=2592000, h3-29=\":443\"; ma=2592000", .host = "", .port = 443, .ma = 2592000 }, .{ .field = "h3=\":443\"; ma=86400", .host = "", .port = 443, .ma = 86400 }, }; for (cases) |case| { var h = try headersOf(gpa, &.{.{ "Alt-Svc", case.field }}); defer h.deinit(gpa); const got = choose(&h); if (case.host) |want| { const alt = got orelse { std.debug.print("no alternative from: {s}\n", .{case.field}); return error.TestExpectedAlternative; }; try testing.expectEqualStrings(want, alt.host); try testing.expectEqual(case.port, alt.port); try testing.expectEqual(case.ma, alt.max_age_s); } else { if (got != null) std.debug.print("unexpected alternative from: {s}\n", .{case.field}); try testing.expect(got == null); } }}
test "RFC 7838 3: several fields are one list, in order" { const gpa = testing.allocator; var h = try headersOf(gpa, &.{ .{ "Alt-Svc", "h2=\":443\"" }, .{ "alt-svc", "h3=\":8443\"; ma=5, h3=\":9443\"" }, }); defer h.deinit(gpa); const got = choose(&h).?; try testing.expectEqual(@as(u16, 8443), got.port);}
const s_ns: i96 = std.time.ns_per_s;
test "RFC 7838 3.1: an alternative is fresh for ma less Age" { var a: AltSvc = .{}; const alt: Advertised = .{ .host = "", .port = 443, .max_age_s = 60 }; a.learnAt(1000 * s_ns, "example.com", 443, alt, 30);
// Thirty seconds left, not sixty. try testing.expect(a.lookupAt(1029 * s_ns, "example.com", 443) != null); try testing.expect(a.lookupAt(1030 * s_ns, "example.com", 443) == null); // Expired and gone, not merely hidden. try testing.expectEqual(@as(usize, 0), a.len);
// Already stale on arrival, which is not an alternative at all. a.learnAt(1000 * s_ns, "example.com", 443, alt, 60); try testing.expectEqual(@as(usize, 0), a.len);}
test "RFC 7838 3.1: a field replaces what an origin said before" { var a: AltSvc = .{}; a.learnAt(0, "example.com", 443, .{ .host = "", .port = 443, .max_age_s = 60 }, 0); a.learnAt(0, "Example.COM", 443, .{ .host = "alt.example.com", .port = 8443, .max_age_s = 60 }, 0); try testing.expectEqual(@as(usize, 1), a.len); const t = a.lookupAt(0, "EXAMPLE.com", 443).?; try testing.expectEqualStrings("alt.example.com", t.host()); try testing.expectEqual(@as(u16, 8443), t.port);
// And an `Alt-Svc` that offers no `h3` -- `clear`, or only `h2` -- leaves // nothing, since it invalidates everything that came before. a.learnAt(0, "example.com", 443, null, 0); try testing.expect(a.lookupAt(0, "example.com", 443) == null);
// Another port is another origin. a.learnAt(0, "example.com", 443, .{ .host = "", .port = 443, .max_age_s = 60 }, 0); try testing.expect(a.lookupAt(0, "example.com", 8443) == null);}
test "a broken alternative is left alone for a while, even when advertised again" { var a: AltSvc = .{}; const alt: Advertised = .{ .host = "", .port = 443, .max_age_s = 3600 }; a.learnAt(0, "example.com", 443, alt, 0); a.markBrokenAt(0, "example.com", 443); try testing.expect(a.lookupAt(1 * s_ns, "example.com", 443) == null);
// The server says it again on the next response, over TCP: still broken. a.learnAt(2 * s_ns, "example.com", 443, alt, 0); try testing.expect(a.lookupAt(3 * s_ns, "example.com", 443) == null);
// After the wait it is tried again. try testing.expect(a.lookupAt(seconds(broken_for_s) + 1, "example.com", 443) != null);
// A *different* alternative is a fresh start. a.markBrokenAt(0, "example.com", 443); a.learnAt(0, "example.com", 443, .{ .host = "", .port = 8443, .max_age_s = 3600 }, 0); try testing.expect(a.lookupAt(1, "example.com", 443) != null);}
test "a full table makes room by dropping what would go soonest" { var a: AltSvc = .{}; var name_buf: [32]u8 = undefined; for (0..capacity) |i| { const name = try std.fmt.bufPrint(&name_buf, "host{d}.example", .{i}); // host0 expires first. a.learnAt(0, name, 443, .{ .host = "", .port = 443, .max_age_s = 100 + i }, 0); } a.learnAt(0, "newcomer.example", 443, .{ .host = "", .port = 443, .max_age_s = 1000 }, 0); try testing.expectEqual(@as(usize, capacity), a.len); try testing.expect(a.lookupAt(0, "newcomer.example", 443) != null); try testing.expect(a.lookupAt(0, "host0.example", 443) == null); try testing.expect(a.lookupAt(0, "host1.example", 443) != null);}
test "one cache, many tasks" { // The lock is the whole of the reason this is its own type: tasks // learning and asking at once must see whole entries and never a torn // one, and must never walk off the end of a table another is shrinking. const io = testing.io; var a: AltSvc = .{};
const Worker = struct { fn run(cache: *AltSvc, seed: u64) void { var prng: std.Random.DefaultPrng = .init(seed); const r = prng.random(); var name_buf: [32]u8 = undefined; var headers_storage: [1]Headers.Field = undefined; for (0..2000) |_| { const name = std.fmt.bufPrint(&name_buf, "h{d}.example", .{r.uintLessThan(u8, 48)}) catch unreachable; switch (r.uintLessThan(u8, 4)) { 0 => { headers_storage[0] = .{ .name = "alt-svc", .value = "h3=\":8443\"; ma=60" }; const h: Headers = .initBorrowed(&headers_storage); cache.learn(testing.io, name, 443, &h); }, 1 => cache.markBroken(testing.io, name, 443), else => if (cache.lookup(testing.io, name, 443)) |t| { // Whatever was learned, whole. std.debug.assert(t.port == 8443 and t.len == 0); }, } } } };
var group: Io.Group = .init; defer group.cancel(io); for (0..4) |i| group.concurrent(io, Worker.run, .{ &a, i }) catch return error.SkipZigTest; try group.await(io); try testing.expect(a.len <= capacity);}