You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@trafficserver.apache.org by bc...@apache.org on 2026/08/28 17:35:10 UTC
(trafficserver-site) 01/02: Rewrite Via decoder as tag-driven parser, add pytest suite
This is an automated email from the ASF dual-hosted git repository.
bryancall pushed a commit to branch asf-site
in repository https://gitbox.apache.org/repos/asf/trafficserver-site.git
commit a1ac39d3bd77d928d85ee82874714132b4e0c854
Author: Bryan Call <bc...@apache.org>
AuthorDate: Fri Aug 28 10:21:17 2026 -0700
Rewrite Via decoder as tag-driven parser, add pytest suite
The decoder positionally indexed fixed offsets and rejected anything not
exactly 22 or 6 characters, so real-world vias failed: strings without the
leading client pair, vias whose trailing spaces were stripped in copy/paste
(e.g. cMsSfWpSeN:t cCMpSs), pre-8.0 24-character headers with the ICP tag,
and full Via header lines pasted verbatim.
Extract the logic into content/js/via-decoder.js as a tag-driven parser
mirroring src/traffic_via/traffic_via.cc from apache/trafficserver: lowercase
letters select fields, uppercase letters and spaces are values, ':' or ';'
separates the detail section, and missing trailing values decode as ' '.
This also picks up value codes the page was missing (W read-while-write hit,
R/M/L error codes, N/A tunnel codes, K cookie miss).
The module loads in the browser (window.ViaDecoder) and under node, so
tests/test_via_decoder.py exercises the exact shipped code through node.
Run with: pytest tests/
---
content/js/via-decoder.js | 271 ++++++++++++++++++++++++++++++++++++++++++++++
content/via.html | 169 ++++++++---------------------
tests/test_via_decoder.py | 143 ++++++++++++++++++++++++
3 files changed, 460 insertions(+), 123 deletions(-)
diff --git a/content/js/via-decoder.js b/content/js/via-decoder.js
new file mode 100644
index 0000000..cb2bd53
--- /dev/null
+++ b/content/js/via-decoder.js
@@ -0,0 +1,271 @@
+/*
+ * Decoder for Apache Traffic Server Via header codes.
+ *
+ * Shared between the website (loaded as a plain script, exposed as
+ * window.ViaDecoder) and the pytest suite in tests/ (loaded with require()
+ * under node).
+ *
+ * The parser is tag-driven, mirroring src/traffic_via/traffic_via.cc in
+ * apache/trafficserver: a lowercase letter selects a field, the uppercase
+ * letters and spaces that follow are that field's values, and ':' or ';'
+ * separates the standard section from the detail section. This handles every
+ * via variant regardless of length: the current 22-character form, the
+ * pre-8.0 24-character form with the ICP tag, short response forms, vias
+ * missing the leading client pair, and vias whose trailing spaces were
+ * stripped in copy/paste (a missing trailing value decodes as ' ').
+ */
+(function (global) {
+ "use strict";
+
+ // Fields before the ':' separator.
+ var STANDARD_FIELDS = {
+ u: [
+ {
+ title: "Request headers received from client",
+ values: {
+ C: "cookie",
+ E: "error in request",
+ S: "simple request (not conditional)",
+ N: "no-cache",
+ I: "If-Modified-Since (IMS)",
+ " ": "unknown",
+ },
+ },
+ ],
+ c: [
+ {
+ title: "Result of Traffic Server cache lookup for URL",
+ values: {
+ A: 'in cache, not acceptable (a cache "MISS")',
+ H: 'in cache, fresh (a cache "HIT")',
+ S: 'in cache, stale (a cache "MISS")',
+ R: 'in cache, fresh RAM hit (a cache "HIT")',
+ W: 'in cache, fresh Read While Write (a cache "HIT")',
+ M: 'miss (a cache "MISS")',
+ " ": "no cache lookup",
+ },
+ },
+ ],
+ s: [
+ {
+ title: "Response information received from origin server",
+ values: {
+ E: "error in response",
+ S: "connection opened successfully",
+ N: "not-modified",
+ " ": "no server connection needed",
+ },
+ },
+ ],
+ f: [
+ {
+ title: "Result of document write-to-cache",
+ values: {
+ U: "updated old cache copy",
+ D: "cached copy deleted",
+ W: "written into cache (new copy)",
+ " ": "no cache write performed",
+ },
+ },
+ ],
+ p: [
+ {
+ title: "Proxy operation result",
+ values: {
+ R: "origin server revalidated",
+ S: "served or connection opened successfully",
+ N: "not-modified",
+ " ": "unknown",
+ },
+ },
+ ],
+ e: [
+ {
+ title: "Error codes (if any)",
+ values: {
+ A: "authorization failure",
+ H: "header syntax unacceptable",
+ C: "connection to server failed",
+ T: "connection timed out",
+ S: "server related error",
+ D: "dns failure",
+ N: "no error",
+ F: "request forbidden",
+ R: "cache read error",
+ M: "moved temporarily",
+ L: "loop detected",
+ " ": "unknown",
+ },
+ },
+ ],
+ };
+
+ // Fields after the ':' (or ';') separator. The 'c' tag carries two values:
+ // cache type followed by cache lookup result.
+ var DETAIL_FIELDS = {
+ t: [
+ {
+ title: "Tunnel info",
+ values: {
+ " ": "no tunneling",
+ U: "tunneling because of url (url suggests dynamic content)",
+ M: "tunneling due to a method (e.g. CONNECT)",
+ O: "tunneling because cache is turned off",
+ F: "tunneling due to a header field (such as presence of If-Range header)",
+ N: "tunneling due to no forward",
+ A: "tunnel authorization",
+ },
+ },
+ ],
+ c: [
+ {
+ title: "Cache Type",
+ values: {
+ C: "cache",
+ L: "cluster (not used)",
+ P: "parent",
+ S: "server",
+ I: "ICP (legacy)",
+ " ": "unknown",
+ },
+ },
+ {
+ title: "Cache Lookup Result",
+ values: {
+ C: "cache hit, but config forces revalidate",
+ I: "conditional miss (client sent conditional, fresh in cache, returned 412)",
+ " ": "cache miss or no cache lookup",
+ U: "cache hit, but client forces revalidate (e.g. Pragma: no-cache)",
+ D: "cache hit, but method forces revalidate (e.g. ftp, not anonymous)",
+ M: "cache miss (url not in cache)",
+ N: "conditional hit (client sent conditional, doc fresh in cache, returned 304)",
+ H: "cache hit",
+ S: "cache hit, but expired",
+ K: "cookie miss",
+ },
+ },
+ ],
+ p: [
+ {
+ title: "Parent proxy connection status",
+ values: {
+ " ": "no parent proxy or unknown",
+ S: "connection opened successfully",
+ F: "connection open failed",
+ },
+ },
+ ],
+ s: [
+ {
+ title: "Origin server connection status",
+ values: {
+ " ": "no server connection needed",
+ S: "connection opened successfully",
+ F: "connection open failed",
+ },
+ },
+ ],
+ };
+
+ // Pull the via code out of arbitrary input: a bare code, a code in square
+ // brackets, or a whole Via header line such as
+ // "HTTP/1.1 host (ApacheTrafficServer/10.0.0 [uScMsSfWpSeN:t cCMpSs ])".
+ // Other bracketed parts of a header (the process UUID, the protocol stack)
+ // contain digits or punctuation, so they never match.
+ function extractViaCode(input) {
+ var bracketed = input.match(/\[([A-Za-z:; ]+)\]/);
+ if (bracketed) {
+ return bracketed[1];
+ }
+ var runs = input.match(/[A-Za-z:; ]+/g);
+ if (!runs) {
+ return null;
+ }
+ var longest = "";
+ for (var i = 0; i < runs.length; i++) {
+ if (runs[i].length > longest.length) {
+ longest = runs[i];
+ }
+ }
+ // Leading whitespace is noise; trailing spaces are significant values.
+ return longest.replace(/^\s+/, "") || null;
+ }
+
+ function decodeVia(input) {
+ var code = extractViaCode(String(input == null ? "" : input));
+ var fields = [];
+ var explicit = 0;
+
+ if (code) {
+ var detail = false;
+ var pending = []; // field definitions awaiting their value characters
+
+ var emit = function (def, section, ch, padded) {
+ var known = Object.prototype.hasOwnProperty.call(def.values, ch);
+ var f = {
+ section: section,
+ title: def.title,
+ code: ch,
+ description: known ? def.values[ch] : "invalid value '" + ch + "'",
+ };
+ if (!known) {
+ f.unknown = true;
+ }
+ if (padded) {
+ f.padded = true;
+ } else {
+ explicit++;
+ }
+ fields.push(f);
+ };
+
+ var section = function () {
+ return detail ? "operational" : "proxy";
+ };
+
+ // A tag with no remaining values means trailing spaces were stripped
+ // from the input; decode the missing values as ' '.
+ var padPending = function () {
+ while (pending.length) {
+ emit(pending.shift(), section(), " ", true);
+ }
+ };
+
+ for (var i = 0; i < code.length; i++) {
+ var ch = code.charAt(i);
+ if (ch === ":" || ch === ";") {
+ padPending();
+ detail = true;
+ } else if (ch >= "a" && ch <= "z") {
+ padPending();
+ var defs = (detail ? DETAIL_FIELDS : STANDARD_FIELDS)[ch];
+ // Unknown tags (e.g. the legacy 'i' ICP tag) are skipped; their
+ // value characters fall through with nothing pending.
+ pending = defs ? defs.slice() : [];
+ } else if (pending.length) {
+ emit(pending.shift(), section(), ch, false);
+ }
+ }
+ padPending();
+ }
+
+ if (explicit === 0) {
+ return {
+ ok: false,
+ error:
+ "No valid Traffic Server via codes found. Expected something like " +
+ '"uScMsSfWpSeN:t cCMp sS" or a full Via header containing it.',
+ via: code || "",
+ fields: [],
+ };
+ }
+ return { ok: true, error: null, via: code, fields: fields };
+ }
+
+ var api = { decodeVia: decodeVia };
+ if (typeof module !== "undefined" && module.exports) {
+ module.exports = api;
+ } else {
+ global.ViaDecoder = api;
+ }
+})(this);
diff --git a/content/via.html b/content/via.html
index 9b32830..1f7f5b8 100644
--- a/content/via.html
+++ b/content/via.html
@@ -8,140 +8,62 @@
<link rel="stylesheet" href="styles/tailwind-complete.css">
<link rel="stylesheet" href="styles/custom.css">
+ <script src="/js/via-decoder.js"></script>
<script type="text/javascript">
-var codes = {}
-codes[1] = {}
-codes[1]['title'] = "client-info Request headers received from client. Value is one of:"
-codes[1]['I'] = "If Modified Since (IMS)"
-codes[1]['C'] = "cookie"
-codes[1]['E'] = "error in request"
-codes[1]['S'] = "simple request (not conditional)"
-codes[1]['N'] = "no-cache"
-codes[2] = {}
-codes[2]['title'] = "cache-lookup Result of Traffic Server cache lookup for URL. Value is one of:"
-codes[2]['A'] = "in cache, not acceptable (a cache \"MISS\")"
-codes[2]['H'] = "in cache, fresh (a cache \"HIT\")"
-codes[2]['S'] = "in cache, stale (a cache \"MISS\")"
-codes[2]['R'] = "in cache, fresh Ram hit (a cache \"HIT\")"
-codes[2]['M'] = "miss (a cache \"MISS\")"
-codes[2][' '] = "no cache lookup performed"
-codes[3] = {}
-codes[3]['title'] = "server-info Response information received from origin server. Value is one of:"
-codes[3]['E'] = "error in response"
-codes[3][' '] = "no server connection needed"
-codes[3]['S'] = "served"
-codes[3]['N'] = "not-modified"
-codes[4] = {}
-codes[4]['title'] = "cache-fill Result of document write to cache. Value is one of:"
-codes[4]['U'] = "updated old cache copy"
-codes[4]['D'] = "cached copy deleted"
-codes[4]['W'] = "written into cache (new copy)"
-codes[4][' '] = "no cache write performed"
-codes[5] = {}
-codes[5]['title'] = "proxy-info Proxy operation result. Value is one of:"
-codes[5]['R'] = "origin server revalidated"
-codes[5][' '] = "unknown?"
-codes[5]['S'] = "served"
-codes[5]['N'] = "not-modified"
-codes[6] = {}
-codes[6]['title'] = "error-codes Value is one of:"
-codes[6]['A'] = "authorization failure"
-codes[6]['H'] = "header syntax unacceptable"
-codes[6]['C'] = "connection to server failed"
-codes[6]['T'] = "connection timed out"
-codes[6]['S'] = "server related error"
-codes[6]['D'] = "dns failure"
-codes[6]['N'] = "no error"
-codes[6]['F'] = "request forbidden"
-codes[7] = {}
-codes[7]['title'] = "tunnel-info Proxy-only service operation. Value is one of:"
-codes[7][' '] = "no tunneling"
-codes[7]['U'] = "tunneling because of url (url suggests dynamic content)"
-codes[7]['M'] = "tunneling due to a method (e.g. CONNECT)"
-codes[7]['O'] = "tunneling because cache is turned off"
-codes[7]['F'] = "tunneling due to a header field (such as presence of If-Range header)"
-codes[8] = {}
-codes[8]['title'] = "cache-type and cache-lookup cache result values (2 characters)"
-codes[8]['I'] = "icp"
-codes[8][' '] = "cache miss or no cache lookup"
-codes[8]['C'] = "cache"
-codes[9] = {}
-codes[9]['title'] = "cache-lookup-result character value is one of:"
-codes[9][' '] = "no cache lookup"
-codes[9]['S'] = "cache hit, but expired"
-codes[9]['U'] = "cache hit, but client forces revalidate (e.g. Pragma: no-cache)"
-codes[9]['D'] = "cache hit, but method forces revalidated (e.g. ftp, not anonymous)"
-codes[9]['I'] = "conditional miss (client sent conditional, fresh in cache, returned 412)"
-codes[9]['H'] = "cache hit"
-codes[9]['M'] = "cache miss (url not in cache)"
-codes[9]['C'] = "cache hit, but config forces revalidate"
-codes[9]['N'] = "conditional hit (client sent conditional, doc fresh in cache, returned 304)"
-codes[10] = {}
-codes[10]['title'] = "parent-proxy parent proxy connection status"
-codes[10][' '] = "no parent proxy"
-codes[10]['S'] = "connection opened successfully"
-codes[10]['F'] = "connection open failed"
-codes[11] = {}
-codes[11]['title'] = "server-conn-info origin server connection status"
-codes[11][' '] = "no server connection"
-codes[11]['S'] = "connection opened successfully"
-codes[11]['F'] = "connection open failed"
+function escapeHtml(s) {
+ return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+}
+
+function renderSection(heading, fields) {
+ if (fields.length == 0) {
+ return "";
+ }
+ var out = '<h3 class="text-lg font-bold text-primary mt-6 mb-3">' + heading + '</h3>';
+ out += '<div class="grid grid-cols-1 gap-2">';
+ for (var i = 0; i < fields.length; i++) {
+ var f = fields[i];
+ var code = f.code == " " ? "(space)" : escapeHtml(f.code);
+ var desc = escapeHtml(f.description);
+ if (f.padded) {
+ desc += ' <span class="text-gray-400 italic">(value missing from input, assumed to be a stripped trailing space)</span>';
+ }
+ out += '<div class="flex"><span class="w-80 flex-shrink-0 font-semibold text-gray-700 mr-2">' + escapeHtml(f.title) + ':</span>' +
+ '<span class="font-mono text-gray-500 mr-2">' + code + '</span>' +
+ '<span class="' + (f.unknown ? 'text-red-600' : 'text-accent') + '">' + desc + '</span></div>';
+ }
+ out += '</div>';
+ return out;
+}
function showVia(form, value) {
- var text = value? value : form.via.value;
+ var text = value ? value : document.getElementById("via").value;
if (value) {
document.getElementById("via").value = value;
}
- var via = document.getElementById("viaoutput")
- var output = "";
- var txtonly = text.match(/([a-zA-Z: ]+)/);
- text = txtonly[1];
- if (text.length == 5) {
- text = text + " "
- }
- if (text.length == 22) {
- var arr = text.match(/([a-zA-Z ]+):([a-zA-Z ]+)/);
- output = output + '<h3 class="text-lg font-bold text-primary mt-6 mb-3">Proxy request results:</h3>';
- output = output + '<div class="grid grid-cols-1 gap-2">';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Request headers received from client:</span> <span class="text-accent">' + codes[1][arr[1][1]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Result of Traffic Server cache lookup:</span> <span class="text-accent">' + codes[2][arr[1][3]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Response from origin server:</span> <span class="text-accent">' + codes[3][arr[1][5]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Result of document write-to-cache:</span> <span class="text-accent">' + codes[4][arr[1][7]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Proxy operation result:</span> <span class="text-accent">' + codes[5][arr[1][9]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Error codes (if any):</span> <span class="text-accent">' + codes[6][arr[1][11]] + '</span></div>';
- output = output + '</div>';
-
- output = output + '<h3 class="text-lg font-bold text-primary mt-6 mb-3">Operational results:</h3>';
- output = output + '<div class="grid grid-cols-1 gap-2">';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Tunnel info:</span> <span class="text-accent">' + codes[7][arr[2][1]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Cache-type and lookup result:</span> <span class="text-accent">' + codes[8][arr[2][3]] + " / " + codes[9][arr[2][4]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Parent proxy connection status:</span> <span class="text-accent">' + codes[10][arr[2][6]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Origin server connection status:</span> <span class="text-accent">' + codes[11][arr[2][8]] + '</span></div>';
- output = output + '</div>';
-
- } else if (text.length == 6) {
- output = output + '<h3 class="text-lg font-bold text-primary mt-6 mb-3">Proxy request results:</h3>';
- output = output + '<div class="grid grid-cols-1 gap-2">';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Result of Traffic Server cache lookup:</span> <span class="text-accent">' + codes[2][text[1]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Response from origin server:</span> <span class="text-accent">' + codes[3][text[3]] + '</span></div>';
- output = output + '<div class="flex"><span class="w-80 font-semibold text-gray-700">Result of document write-to-cache:</span> <span class="text-accent">' + codes[4][text[5]] + '</span></div>';
- output = output + '</div>';
-
+ var result = ViaDecoder.decodeVia(text);
+ var output;
+ if (result.ok) {
+ var proxy = [], operational = [];
+ for (var i = 0; i < result.fields.length; i++) {
+ (result.fields[i].section == "proxy" ? proxy : operational).push(result.fields[i]);
+ }
+ output = renderSection("Proxy request results:", proxy) +
+ renderSection("Operational results:", operational);
} else {
- output = '<p class="text-red-600 font-medium">Invalid VIA data, must be 22 or 6 characters long.</p>';
+ output = '<p class="text-red-600 font-medium">' + escapeHtml(result.error) + '</p>';
}
- via.innerHTML = output;
+ document.getElementById("viaoutput").innerHTML = output;
if (form) {
- window.location.hash = escape(text);
+ window.location.hash = encodeURIComponent(result.ok ? result.via : text);
}
return false;
}
function checkQuery() {
- var url = location.href;
- if (url.indexOf("#") > 0) {
- var qs = url.substring(url.indexOf("#")+1).replace("%20", " ").replace("+", " ");
- if (qs && qs.length > 5) {
+ var hash = window.location.hash;
+ if (hash && hash.length > 1) {
+ var qs = decodeURIComponent(hash.substring(1).replace(/\+/g, " "));
+ if (qs) {
showVia(false, qs);
}
}
@@ -216,7 +138,7 @@ function checkQuery() {
<div class="flex gap-4">
<input type="text" name="via" id="via"
class="flex-1 px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-accent focus:border-accent text-lg font-mono"
- placeholder="e.g., uScMsSfWpSeN:u xCHuSxS">
+ placeholder="e.g., uScMsSfWpSeN:t cCMp sS or a full Via header">
<button type="button" onclick="showVia(this.form)"
class="px-6 py-3 bg-gradient-to-r from-blue-500 to-blue-900 text-white font-semibold rounded-lg hover:shadow-lg transition-all">
Parse Header
@@ -226,8 +148,9 @@ function checkQuery() {
<div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-6">
<p class="text-sm text-blue-800">
- <strong>Note:</strong> This tool works with ATS 8.0.0 and above for extended via headers.
- For earlier versions, use the command line tool <code class="bg-blue-100 px-1 rounded">traffic_via</code>.
+ <strong>Note:</strong> Paste the via code or the entire Via header line. All Traffic Server
+ via formats are accepted, including pre-8.0 headers and partial codes. The command line tool
+ <code class="bg-blue-100 px-1 rounded">traffic_via</code> can also decode these.
</p>
</div>
</form>
diff --git a/tests/test_via_decoder.py b/tests/test_via_decoder.py
new file mode 100644
index 0000000..ea909a6
--- /dev/null
+++ b/tests/test_via_decoder.py
@@ -0,0 +1,143 @@
+"""Tests for the Via header decoder used by content/via.html.
+
+The decoder lives in content/js/via-decoder.js and is shared between the
+website (browser) and these tests (node). Each test shells out to node and
+decodes a via string, then asserts on the structured result.
+
+The parser is tag-driven, mirroring traffic_via.cc from apache/trafficserver:
+lowercase letters are field tags, uppercase letters and spaces are values,
+':' or ';' separates the standard section from the detail section.
+
+Run with: pytest tests/
+"""
+
+import json
+import pathlib
+import shutil
+import subprocess
+
+import pytest
+
+ROOT = pathlib.Path(__file__).resolve().parent.parent
+DECODER = ROOT / "content" / "js" / "via-decoder.js"
+
+NODE = shutil.which("node")
+pytestmark = pytest.mark.skipif(NODE is None, reason="node is required to run the decoder")
+
+DRIVER = "const d = require(process.argv[1]); process.stdout.write(JSON.stringify(d.decodeVia(process.argv[2])));"
+
+
+def decode(via):
+ result = subprocess.run(
+ [NODE, "-e", DRIVER, str(DECODER), via],
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ return json.loads(result.stdout)
+
+
+def field(result, title_fragment):
+ matches = [f for f in result["fields"] if title_fragment.lower() in f["title"].lower()]
+ assert matches, f"no field with title containing {title_fragment!r} in {result['fields']}"
+ assert len(matches) == 1, f"ambiguous title fragment {title_fragment!r}"
+ return matches[0]
+
+
+def test_via_missing_client_pair_and_trailing_space():
+ """The reported bug: a via with no leading u<x> client pair and the
+ trailing space (origin connection value) lost in copy/paste."""
+ result = decode("cMsSfWpSeN:t cCMpSs")
+ assert result["ok"] is True
+
+ assert field(result, "cache lookup for URL")["code"] == "M"
+ assert field(result, "Response information")["code"] == "S"
+ assert field(result, "write-to-cache")["code"] == "W"
+ assert field(result, "Proxy operation")["code"] == "S"
+ assert field(result, "Error codes")["code"] == "N"
+ assert "no error" in field(result, "Error codes")["description"]
+
+ assert field(result, "Tunnel")["code"] == " "
+ assert field(result, "Cache Type")["code"] == "C"
+ assert field(result, "Cache Lookup Result")["code"] == "M"
+ assert field(result, "Parent proxy")["code"] == "S"
+ # The trailing space was stripped; the missing value must decode as ' '.
+ assert field(result, "server connection status")["code"] == " "
+
+ # No client-info tag in the input, so no client field in the output.
+ assert not any("received from client" in f["title"] for f in result["fields"])
+
+
+def test_canonical_full_via():
+ result = decode("uScMsSfWpSeN:t cCMp sS")
+ assert result["ok"] is True
+ assert field(result, "received from client")["code"] == "S"
+ assert field(result, "cache lookup for URL")["code"] == "M"
+ assert field(result, "Parent proxy")["code"] == " "
+ assert field(result, "server connection status")["code"] == "S"
+
+
+def test_full_header_line_with_brackets():
+ header = "HTTP/1.1 proxy.example.com (ApacheTrafficServer/10.0.0 [uScMsSfWpSeN:t cCMpSs ])"
+ result = decode(header)
+ assert result["ok"] is True
+ assert field(result, "received from client")["code"] == "S"
+ assert field(result, "Parent proxy")["code"] == "S"
+ assert field(result, "server connection status")["code"] == " "
+
+
+def test_legacy_24_char_via_with_icp_tag():
+ """Pre-8.0 vias are 24 chars and include an 'i' (ICP) tag; it must be
+ tolerated without derailing the rest of the decode."""
+ result = decode("[uScMsSf pSeN:t cCMi p sS]")
+ assert result["ok"] is True
+ assert field(result, "write-to-cache")["code"] == " "
+ assert field(result, "Cache Lookup Result")["code"] == "M"
+ assert field(result, "Parent proxy")["code"] == " "
+ assert field(result, "server connection status")["code"] == "S"
+
+
+def test_short_response_via():
+ result = decode("cMsSfW")
+ assert result["ok"] is True
+ assert field(result, "cache lookup for URL")["code"] == "M"
+ assert field(result, "Response information")["code"] == "S"
+ assert field(result, "write-to-cache")["code"] == "W"
+
+
+def test_short_response_via_stripped_trailing_space():
+ result = decode("cMsSf")
+ assert result["ok"] is True
+ assert field(result, "write-to-cache")["code"] == " "
+
+
+def test_semicolon_separator():
+ """Some ATS versions emit ';' instead of ':' before the detail section."""
+ result = decode("[u c s f p eS;tNc p s ]")
+ assert result["ok"] is True
+ assert "server related error" in field(result, "Error codes")["description"]
+ assert "no forward" in field(result, "Tunnel")["description"]
+ assert field(result, "Cache Type")["code"] == " "
+
+
+def test_read_while_write_hit():
+ """'W' is a valid cache-lookup result (read-while-write hit)."""
+ result = decode("uScWsSfWpSeN:t cCHp sS")
+ assert result["ok"] is True
+ assert "Read While Write" in field(result, "cache lookup for URL")["description"]
+
+
+def test_unknown_value_is_flagged_not_fatal():
+ result = decode("cZsS")
+ assert result["ok"] is True
+ f = field(result, "cache lookup for URL")
+ assert f["code"] == "Z"
+ assert f.get("unknown") is True
+ assert field(result, "Response information")["code"] == "S"
+
+
+@pytest.mark.parametrize("garbage", ["rubbish", "", "12345", "SSSS", "long rubbish via code2"])
+def test_garbage_is_rejected(garbage):
+ result = decode(garbage)
+ assert result["ok"] is False
+ assert result["error"]