1use std::fmt::Write;
12use std::time::SystemTime;
13
14#[must_use]
21pub fn make_etag(data: &[u8]) -> String {
22 let hash = fnv1a(data);
23 format!("W/\"{hash:016x}\"")
24}
25
26pub(crate) fn card_body_and_etag(
43 card: &a2a_protocol_types::agent_card::AgentCard,
44) -> serde_json::Result<(Vec<u8>, String)> {
45 let value = super::sorted_json::sorted(serde_json::to_value(card)?);
46 let etag = make_etag(&serde_json::to_vec(&value)?);
47 Ok((serde_json::to_vec(card)?, etag))
48}
49
50fn fnv1a(data: &[u8]) -> u64 {
52 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
53 for &byte in data {
54 hash ^= u64::from(byte);
55 hash = hash.wrapping_mul(0x0100_0000_01b3);
56 }
57 hash
58}
59
60#[must_use]
64pub fn format_http_date(time: SystemTime) -> String {
65 let dur = time
66 .duration_since(SystemTime::UNIX_EPOCH)
67 .unwrap_or_default();
68 let secs = dur.as_secs();
69
70 let days = secs / 86400;
72 let day_secs = secs % 86400;
73 let hours = day_secs / 3600;
74 let minutes = (day_secs % 3600) / 60;
75 let seconds = day_secs % 60;
76
77 #[allow(clippy::cast_possible_wrap)]
79 let (year, month, day) = civil_from_days(days as i64);
80
81 let dow = ((days + 4) % 7) as usize;
83 let day_names = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
84 let month_names = [
85 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
86 ];
87
88 let mut buf = String::with_capacity(29);
89 let _ = write!(
90 buf,
91 "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT",
92 day_names[dow],
93 day,
94 month_names[month as usize - 1],
95 year,
96 hours,
97 minutes,
98 seconds
99 );
100 buf
101}
102
103#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
105fn civil_from_days(days: i64) -> (i64, u32, u32) {
106 let z = days + 719_468;
107 let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
108 let doe = (z - era * 146_097) as u32;
109 let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
110 let y = i64::from(yoe) + era * 400;
111 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
112 let mp = (5 * doy + 2) / 153;
113 let d = doy - (153 * mp + 2) / 5 + 1;
114 let m = if mp < 10 { mp + 3 } else { mp - 9 };
115 let y = if m <= 2 { y + 1 } else { y };
116 (y, m, d)
117}
118
119#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum ConditionalResult {
124 NotModified,
126 SendFull,
128}
129
130#[must_use]
141pub fn check_conditional(
142 req: &hyper::Request<impl hyper::body::Body>,
143 current_etag: &str,
144 current_last_modified: &str,
145) -> ConditionalResult {
146 if !matches!(*req.method(), hyper::Method::GET | hyper::Method::HEAD) {
147 return ConditionalResult::SendFull;
148 }
149 if req.headers().contains_key(hyper::header::IF_NONE_MATCH) {
150 let matched = crate::dispatch::field_value(req.headers(), "if-none-match")
151 .is_some_and(|inm| etag_matches(&inm, current_etag));
152 return if matched {
153 ConditionalResult::NotModified
154 } else {
155 ConditionalResult::SendFull
156 };
157 }
158
159 if let Some(ims) = req.headers().get("if-modified-since")
161 && let Ok(ims_str) = ims.to_str()
162 && ims_str == current_last_modified
163 {
164 return ConditionalResult::NotModified;
165 }
166
167 ConditionalResult::SendFull
168}
169
170pub(crate) fn etag_matches(header_value: &str, current: &str) -> bool {
176 let header_value = header_value.trim();
177 if header_value == "*" {
178 return true;
179 }
180 let current_bare = current.strip_prefix("W/").unwrap_or(current);
182
183 for candidate in header_value.split(',') {
184 let candidate = candidate.trim();
185 let candidate_bare = candidate.strip_prefix("W/").unwrap_or(candidate);
186 if candidate_bare == current_bare {
187 return true;
188 }
189 }
190 false
191}
192
193#[derive(Debug, Clone, Copy)]
202#[non_exhaustive]
203pub struct CacheConfig {
204 pub max_age: u32,
206}
207
208impl CacheConfig {
209 #[must_use]
211 pub const fn with_max_age(max_age: u32) -> Self {
212 Self { max_age }
213 }
214
215 #[must_use]
217 pub fn header_value(&self) -> String {
218 format!("public, max-age={}", self.max_age)
219 }
220}
221
222impl Default for CacheConfig {
223 fn default() -> Self {
224 Self { max_age: 3600 }
226 }
227}
228
229#[cfg(test)]
232pub(crate) mod tests {
233 use super::*;
234 use a2a_protocol_types::agent_card::{
235 AgentCapabilities, AgentCard, AgentInterface, AgentSkill,
236 };
237 use bytes::Bytes;
238 use http_body_util::Full;
239
240 pub fn minimal_agent_card() -> AgentCard {
242 AgentCard::new(
243 "Test Agent",
244 "1.0.0",
245 AgentInterface::new("https://agent.example.com/rpc", "JSONRPC")
246 .with_protocol_version("1.0.0"),
247 )
248 .with_description("A test agent")
249 .with_input_modes(vec!["text/plain"])
250 .with_output_modes(vec!["text/plain"])
251 .with_skill(AgentSkill::new("echo", "Echo", "Echoes input").with_tags(vec!["echo"]))
252 .with_capabilities(AgentCapabilities::none())
253 }
254
255 #[test]
256 fn make_etag_deterministic() {
257 let data = b"hello world";
258 let etag1 = make_etag(data);
259 let etag2 = make_etag(data);
260 assert_eq!(etag1, etag2);
261 assert!(etag1.starts_with("W/\""));
262 assert!(etag1.ends_with('"'));
263 }
264
265 #[test]
266 fn make_etag_different_for_different_data() {
267 let etag1 = make_etag(b"hello");
268 let etag2 = make_etag(b"world");
269 assert_ne!(etag1, etag2);
270 }
271
272 #[test]
273 fn format_http_date_epoch() {
274 let epoch = SystemTime::UNIX_EPOCH;
275 let date = format_http_date(epoch);
276 assert_eq!(date, "Thu, 01 Jan 1970 00:00:00 GMT");
277 }
278
279 #[test]
280 fn etag_matches_exact() {
281 assert!(etag_matches("W/\"abc\"", "W/\"abc\""));
282 }
283
284 #[test]
285 fn etag_matches_wildcard() {
286 assert!(etag_matches("*", "W/\"abc\""));
287 }
288
289 #[test]
290 fn etag_matches_comma_list() {
291 assert!(etag_matches("W/\"aaa\", W/\"bbb\", W/\"ccc\"", "W/\"bbb\""));
292 }
293
294 #[test]
295 fn etag_no_match() {
296 assert!(!etag_matches("W/\"xxx\"", "W/\"yyy\""));
297 }
298
299 #[test]
300 fn check_conditional_if_none_match_hit() {
301 let req = hyper::Request::builder()
302 .header("if-none-match", "W/\"abc\"")
303 .body(Full::new(Bytes::new()))
304 .unwrap();
305 assert_eq!(
306 check_conditional(&req, "W/\"abc\"", "Thu, 01 Jan 2026 00:00:00 GMT"),
307 ConditionalResult::NotModified,
308 );
309 }
310
311 #[test]
312 fn check_conditional_if_none_match_miss() {
313 let req = hyper::Request::builder()
314 .header("if-none-match", "W/\"xyz\"")
315 .body(Full::new(Bytes::new()))
316 .unwrap();
317 assert_eq!(
318 check_conditional(&req, "W/\"abc\"", "Thu, 01 Jan 2026 00:00:00 GMT"),
319 ConditionalResult::SendFull,
320 );
321 }
322
323 #[test]
324 fn check_conditional_if_modified_since_match() {
325 let lm = "Thu, 01 Jan 2026 00:00:00 GMT";
326 let req = hyper::Request::builder()
327 .header("if-modified-since", lm)
328 .body(Full::new(Bytes::new()))
329 .unwrap();
330 assert_eq!(
331 check_conditional(&req, "W/\"abc\"", lm),
332 ConditionalResult::NotModified,
333 );
334 }
335
336 #[test]
337 fn check_conditional_no_headers() {
338 let req = hyper::Request::builder()
339 .body(Full::new(Bytes::new()))
340 .unwrap();
341 assert_eq!(
342 check_conditional(&req, "W/\"abc\"", "Thu, 01 Jan 2026 00:00:00 GMT"),
343 ConditionalResult::SendFull,
344 );
345 }
346
347 #[test]
349 fn check_conditional_if_modified_since_miss() {
350 let req = hyper::Request::builder()
351 .header("if-modified-since", "Mon, 01 Jan 2024 00:00:00 GMT")
352 .body(Full::new(Bytes::new()))
353 .unwrap();
354 assert_eq!(
355 check_conditional(&req, "W/\"abc\"", "Thu, 01 Jan 2026 00:00:00 GMT"),
356 ConditionalResult::SendFull,
357 "non-matching If-Modified-Since should return SendFull"
358 );
359 }
360
361 #[test]
363 fn check_conditional_if_none_match_non_utf8_falls_through() {
364 let lm = "Thu, 01 Jan 2026 00:00:00 GMT";
368 let req = hyper::Request::builder()
369 .header("if-none-match", "W/\"wrong\"")
370 .header("if-modified-since", lm)
371 .body(Full::new(Bytes::new()))
372 .unwrap();
373 assert_eq!(
376 check_conditional(&req, "W/\"abc\"", lm),
377 ConditionalResult::SendFull,
378 "If-None-Match miss should skip If-Modified-Since per RFC 7232"
379 );
380 }
381
382 fn conditional(method: &str, lines: &[(&str, &[u8])]) -> ConditionalResult {
383 let mut req = hyper::Request::builder().method(method);
384 for (name, value) in lines {
385 req = req.header(
386 *name,
387 hyper::header::HeaderValue::from_bytes(value).unwrap(),
388 );
389 }
390 let req = req.body(Full::new(Bytes::new())).unwrap();
391 check_conditional(&req, "W/\"abc\"", "Thu, 01 Jan 2026 00:00:00 GMT")
392 }
393
394 #[test]
399 fn an_unreadable_if_none_match_still_hides_if_modified_since() {
400 let lines: &[(&str, &[u8])] = &[
401 ("if-none-match", b"\"\xe9\""),
402 ("if-modified-since", b"Thu, 01 Jan 2026 00:00:00 GMT"),
403 ];
404 assert_eq!(conditional("GET", lines), ConditionalResult::SendFull);
405 }
406
407 #[test]
410 fn an_if_none_match_on_a_second_line_counts() {
411 let lines: &[(&str, &[u8])] = &[
412 ("if-none-match", b"\"other\""),
413 ("if-none-match", b"W/\"abc\""),
414 ];
415 assert_eq!(conditional("GET", lines), ConditionalResult::NotModified);
416 }
417
418 #[test]
422 fn conditions_apply_to_get_and_head_only() {
423 let inm: &[(&str, &[u8])] = &[("if-none-match", b"W/\"abc\"")];
424 let ims: &[(&str, &[u8])] = &[("if-modified-since", b"Thu, 01 Jan 2026 00:00:00 GMT")];
425 for lines in [inm, ims] {
426 assert_eq!(conditional("GET", lines), ConditionalResult::NotModified);
427 assert_eq!(conditional("HEAD", lines), ConditionalResult::NotModified);
428 for method in ["POST", "PUT", "DELETE"] {
429 assert_eq!(
430 conditional(method, lines),
431 ConditionalResult::SendFull,
432 "{method}"
433 );
434 }
435 }
436 }
437
438 #[test]
439 fn cache_config_default() {
440 let c = CacheConfig::default();
441 assert_eq!(c.header_value(), "public, max-age=3600");
442 }
443
444 #[test]
445 fn cache_config_custom() {
446 let c = CacheConfig::with_max_age(600);
447 assert_eq!(c.header_value(), "public, max-age=600");
448 }
449
450 #[test]
453 fn fnv1a_known_vectors() {
454 assert_eq!(fnv1a(b""), 0xcbf2_9ce4_8422_2325);
456
457 let expected = (0xcbf2_9ce4_8422_2325_u64 ^ 0x61).wrapping_mul(0x0100_0000_01b3);
459 assert_eq!(fnv1a(b"a"), expected);
460 }
461
462 #[test]
463 fn fnv1a_xor_not_or() {
464 let h_ab = fnv1a(b"ab");
467 let h_ba = fnv1a(b"ba");
468 assert_ne!(h_ab, h_ba, "fnv1a should be order-sensitive (XOR step)");
469 }
470
471 #[test]
486 fn format_http_date_calendar_boundaries() {
487 let cases: &[(u64, &str)] = &[
489 (951_825_600, "Tue, 29 Feb 2000 12:00:00 GMT"), (4_107_542_399, "Sun, 28 Feb 2100 23:59:59 GMT"), (4_107_542_400, "Mon, 01 Mar 2100 00:00:00 GMT"), (13_574_563_200, "Tue, 29 Feb 2400 00:00:00 GMT"), (68_193_000, "Tue, 29 Feb 1972 06:30:00 GMT"), (2_147_483_647, "Tue, 19 Jan 2038 03:14:07 GMT"), (1_735_689_599, "Tue, 31 Dec 2024 23:59:59 GMT"), (946_684_799, "Fri, 31 Dec 1999 23:59:59 GMT"), ];
498
499 for (secs, expected) in cases {
500 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(*secs);
501 assert_eq!(
502 format_http_date(time),
503 *expected,
504 "wrong civil date for {secs} seconds since the epoch"
505 );
506 }
507 }
508
509 #[test]
541 fn civil_from_days_handles_pre_gregorian_epoch_days() {
542 assert_eq!(civil_from_days(-719_468), (0, 3, 1));
544
545 assert_eq!(civil_from_days(-719_469), (0, 2, 29));
548
549 assert_eq!(civil_from_days(-719_530), (-1, 12, 30));
555 assert_eq!(civil_from_days(-1_000_000), (-768, 2, 4));
556 }
557
558 #[test]
559 fn format_http_date_known_timestamp() {
560 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_750_000_245);
563 let date = format_http_date(time);
564 assert_eq!(date, "Sun, 15 Jun 2025 15:10:45 GMT");
565 }
566
567 #[test]
568 fn format_http_date_end_of_day() {
569 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(86399);
571 let date = format_http_date(time);
572 assert_eq!(date, "Thu, 01 Jan 1970 23:59:59 GMT");
573 }
574
575 #[test]
576 fn format_http_date_next_day() {
577 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_hours(24);
579 let date = format_http_date(time);
580 assert_eq!(date, "Fri, 02 Jan 1970 00:00:00 GMT");
581 }
582
583 #[test]
584 fn format_http_date_midday() {
585 let time = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(45015);
587 let date = format_http_date(time);
588 assert_eq!(date, "Thu, 01 Jan 1970 12:30:15 GMT");
589 }
590}