Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(replay-core-v4): own the byte scanner, codecs and url policy (#117958)

Nicholas Waltzc70eefc68138
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index efa466a76984..0c1cc6aa4cee 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -11019,22 +11019,31 @@ name = "replay-core-v4"
version = "0.1.0"
dependencies = [
"aes-gcm",
+ "anyhow",
"async-trait",
"aws-sdk-dynamodb",
"aws-sdk-kms",
"base64 0.22.1",
"chrono",
+ "flate2",
"futures",
"governor",
"hkdf",
"hmac 0.12.1",
+ "libdeflater",
+ "lz4",
"md5",
+ "memchr",
"moka",
+ "percent-encoding",
+ "public-suffix",
"rand 0.8.5",
"serde_json",
"sha2 0.10.9",
"thiserror 2.0.18",
"tokio",
+ "url",
+ "zstd 0.13.3",
]
[[package]]
diff --git a/rust/ai-research/replay-core-v4/Cargo.toml b/rust/ai-research/replay-core-v4/Cargo.toml
index 331530166ca7..bfea58948b11 100644
--- a/rust/ai-research/replay-core-v4/Cargo.toml
+++ b/rust/ai-research/replay-core-v4/Cargo.toml
@@ -15,6 +15,7 @@ store = ["dep:async-trait", "dep:aws-sdk-dynamodb", "dep:aws-sdk-kms", "dep:chro
[dependencies]
aes-gcm = "0.10"
+anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
aws-sdk-dynamodb = { workspace = true, optional = true }
aws-sdk-kms = { workspace = true, optional = true }
@@ -24,10 +25,20 @@ futures = { workspace = true, optional = true }
governor = { workspace = true, optional = true }
hkdf = "0.12"
hmac = { workspace = true }
+libdeflater = { workspace = true }
+lz4 = { workspace = true }
md5 = "0.8"
+memchr = "2"
moka = { workspace = true, optional = true }
+percent-encoding = { workspace = true }
+public-suffix = { workspace = true }
rand = { workspace = true, optional = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
thiserror = { workspace = true }
+url = { workspace = true }
tokio = { workspace = true, optional = true }
+zstd = { workspace = true }
+
+[dev-dependencies]
+flate2 = { workspace = true }
diff --git a/rust/ai-research/replay-core-v4/src/bytescan.rs b/rust/ai-research/replay-core-v4/src/bytescan.rs
new file mode 100644
index 000000000000..5731f63fb5a2
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/bytescan.rs
@@ -0,0 +1,714 @@
+//! Byte-level JSON span scanning: locate values, iterate object entries and array items, and read
+//! scalars without building a tree. The byte-pass reader in [`crate::scan`] uses it to read replay
+//! messages and to cut spans out of them without a parse.
+//!
+//! The scanners assume structurally valid JSON (the payload is re-serialized by capture upstream) and
+//! only report *structural* failures (unbalanced brackets, truncation). They never unescape strings;
+//! callers that need decoded text use [`unescape`], and callers that meet an escaped **key** must fall
+//! back to a real parse — a `\uXXXX` key could alias a routing key, and byte comparison would miss it.
+
+/// Half-open byte range into the scanned buffer.
+pub type Span = (usize, usize);
+
+#[derive(Debug, PartialEq, Eq)]
+pub struct ScanError(pub &'static str);
+
+type Result<T> = std::result::Result<T, ScanError>;
+
+fn is_ws(b: u8) -> bool {
+ matches!(b, b' ' | b'\t' | b'\n' | b'\r')
+}
+
+pub fn skip_ws(bytes: &[u8], mut pos: usize) -> usize {
+ while pos < bytes.len() && is_ws(bytes[pos]) {
+ pos += 1;
+ }
+ pos
+}
+
+/// True when the little-endian 8-byte word contains a `"` or `\` byte (the classic SWAR
+/// zero-byte test), letting scanners consume 8 bytes per step with no memchr per-call setup.
+#[inline]
+fn word_has_quote_or_backslash(word: u64) -> bool {
+ const LO: u64 = 0x0101_0101_0101_0101;
+ const HI: u64 = 0x8080_8080_8080_8080;
+ let q = word ^ (LO * b'"' as u64);
+ let b = word ^ (LO * b'\\' as u64);
+ ((q.wrapping_sub(LO) & !q) | (b.wrapping_sub(LO) & !b)) & HI != 0
+}
+
+#[inline]
+fn word_has_backslash(word: u64) -> bool {
+ const LO: u64 = 0x0101_0101_0101_0101;
+ const HI: u64 = 0x8080_8080_8080_8080;
+ let b = word ^ (LO * b'\\' as u64);
+ b.wrapping_sub(LO) & !b & HI != 0
+}
+
+#[inline]
+fn read_word(bytes: &[u8], pos: usize) -> u64 {
+ u64::from_le_bytes(bytes[pos..pos + 8].try_into().expect("8 bytes"))
+}
+
+/// Position of the next `\` in `bytes[pos..end]`, or `end`. Same SWAR-then-memchr shape as
+/// [`skip_string`], for the unescapers' clean-run scans.
+#[inline]
+fn next_backslash(bytes: &[u8], mut pos: usize, end: usize) -> usize {
+ let mut words = 0u32;
+ while pos + 8 <= end && words < 4 {
+ if word_has_backslash(read_word(bytes, pos)) {
+ while bytes[pos] != b'\\' {
+ pos += 1;
+ }
+ return pos;
+ }
+ pos += 8;
+ words += 1;
+ }
+ if words == 4 {
+ return memchr::memchr(b'\\', &bytes[pos..end]).map_or(end, |j| pos + j);
+ }
+ while pos < end {
+ if bytes[pos] == b'\\' {
+ return pos;
+ }
+ pos += 1;
+ }
+ end
+}
+
+/// `start` must be at an opening quote; returns the position just past the closing quote.
+/// Each stretch is scanned SWAR-first (8-byte words, no per-call setup), escalating to memchr only
+/// after 32 clean bytes: DOM JSON is mostly 5-20 byte strings and JSON-in-JSON has an escape every
+/// ~15 bytes, so memchr-per-hop would be all setup — while long clean runs (blobs, base64 bodies)
+/// still get real SIMD jumps.
+pub fn skip_string(bytes: &[u8], start: usize) -> Result<usize> {
+ debug_assert_eq!(bytes.get(start), Some(&b'"'));
+ let mut pos = start + 1;
+ 'stretch: while pos < bytes.len() {
+ let mut words = 0u32;
+ while pos + 8 <= bytes.len() && words < 4 {
+ if word_has_quote_or_backslash(read_word(bytes, pos)) {
+ let word_end = pos + 8;
+ while pos < word_end {
+ match bytes[pos] {
+ b'"' => return Ok(pos + 1),
+ b'\\' => {
+ pos += 2; // skip the escape and its payload byte
+ continue 'stretch;
+ }
+ _ => pos += 1,
+ }
+ }
+ continue 'stretch;
+ }
+ pos += 8;
+ words += 1;
+ }
+ if words == 4 {
+ // 32 clean bytes: a long run, worth memchr's setup.
+ let Some(i) = memchr::memchr2(b'\\', b'"', &bytes[pos..]) else {
+ break;
+ };
+ let at = pos + i;
+ if bytes[at] == b'"' {
+ return Ok(at + 1);
+ }
+ pos = at + 2;
+ continue 'stretch;
+ }
+ // Tail: fewer than 8 bytes left.
+ while pos < bytes.len() {
+ match bytes[pos] {
+ b'"' => return Ok(pos + 1),
+ b'\\' => pos += 2,
+ _ => pos += 1,
+ }
+ }
+ break;
+ }
+ Err(ScanError("unterminated string"))
+}
+
+/// Matches the parse path's `MAX_JSON_DEPTH` so scan and parse fail closed on the same over-deep
+/// inputs; real DOMs nest to ~25 but some legitimately exceed 64.
+const MAX_BRACKET_NESTING: usize = 1024;
+
+/// `start` must be at `open`; returns the position just past the matching `close`. `open`/`close`
+/// only name the expected top level.
+///
+/// The `stack` bitstack (0 = brace, 1 = bracket) rejects a mismatched closer instead of closing the
+/// wrong container — otherwise `{"a":[}]}` would locate a span at the inner `}` and splice invalid
+/// bytes through verbatim.
+///
+/// Stays bytewise: memchr3 here measured ~20% slower on bracket-dense payloads (the gaps between
+/// strings are too short to amortize its setup).
+pub fn skip_balanced(bytes: &[u8], start: usize, open: u8, close: u8) -> Result<usize> {
+ debug_assert_eq!(bytes.get(start), Some(&open));
+ let _ = close;
+ let mut stack = [0u64; MAX_BRACKET_NESTING / 64];
+ let mut depth: usize = 0;
+ let mut pos = start;
+ while pos < bytes.len() {
+ match bytes[pos] {
+ b'"' => {
+ pos = skip_string(bytes, pos)?;
+ continue;
+ }
+ b'{' | b'[' => {
+ if depth >= MAX_BRACKET_NESTING {
+ return Err(ScanError("bracket nesting too deep"));
+ }
+ if bytes[pos] == b'[' {
+ stack[depth / 64] |= 1 << (depth % 64);
+ } else {
+ stack[depth / 64] &= !(1 << (depth % 64));
+ }
+ depth += 1;
+ }
+ b'}' | b']' => {
+ let Some(next) = depth.checked_sub(1) else {
+ return Err(ScanError("unbalanced brackets"));
+ };
+ let was_bracket = (stack[next / 64] >> (next % 64)) & 1 == 1;
+ if was_bracket != (bytes[pos] == b']') {
+ return Err(ScanError("mismatched brackets"));
+ }
+ depth = next;
+ if depth == 0 {
+ return Ok(pos + 1);
+ }
+ }
+ _ => {}
+ }
+ pos += 1;
+ }
+ Err(ScanError("unbalanced brackets"))
+}
+
+fn skip_scalar(bytes: &[u8], start: usize) -> usize {
+ let mut pos = start;
+ while pos < bytes.len() {
+ let b = bytes[pos];
+ if matches!(b, b',' | b'}' | b']') || is_ws(b) {
+ return pos;
+ }
+ pos += 1;
+ }
+ pos
+}
+
+/// Span of the JSON value starting at (or after whitespace from) `start`.
+pub fn locate_value(bytes: &[u8], start: usize) -> Result<Span> {
+ let start = skip_ws(bytes, start);
+ let end = match bytes.get(start) {
+ Some(b'"') => skip_string(bytes, start)?,
+ Some(b'{') => skip_balanced(bytes, start, b'{', b'}')?,
+ Some(b'[') => skip_balanced(bytes, start, b'[', b']')?,
+ Some(_) => skip_scalar(bytes, start),
+ None => return Err(ScanError("expected a value")),
+ };
+ Ok((start, end))
+}
+
+/// One scanned object entry. `key` excludes the quotes and is *raw* (not unescaped);
+/// `key_escaped` marks a backslash in the raw key — callers must treat such objects as unscannable.
+pub struct Entry {
+ pub key: Span,
+ pub key_escaped: bool,
+ pub value: Span,
+}
+
+/// Iterates the top-level entries of the object whose span is `obj` (must start at `{`).
+pub struct ObjectEntries<'b> {
+ bytes: &'b [u8],
+ pos: usize,
+ end: usize,
+ done: bool,
+ first: bool,
+}
+
+pub fn object_entries<'b>(bytes: &'b [u8], obj: Span) -> Result<ObjectEntries<'b>> {
+ if bytes.get(obj.0) != Some(&b'{') {
+ return Err(ScanError("not an object"));
+ }
+ Ok(ObjectEntries {
+ bytes,
+ pos: obj.0 + 1,
+ end: obj.1,
+ done: false,
+ first: true,
+ })
+}
+
+impl<'b> Iterator for ObjectEntries<'b> {
+ type Item = Result<Entry>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.done {
+ return None;
+ }
+ let bytes = self.bytes;
+ let mut pos = skip_ws(bytes, self.pos);
+ if pos + 1 == self.end && bytes.get(pos) == Some(&b'}') {
+ self.done = true;
+ return None;
+ }
+ if !self.first {
+ if bytes.get(pos) != Some(&b',') {
+ self.done = true;
+ return Some(Err(ScanError("expected ',' between object entries")));
+ }
+ pos = skip_ws(bytes, pos + 1);
+ }
+ self.first = false;
+ if bytes.get(pos) != Some(&b'"') {
+ self.done = true;
+ return Some(Err(ScanError("expected object key")));
+ }
+ let key_end = match skip_string(bytes, pos) {
+ Ok(e) => e,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ let key = (pos + 1, key_end - 1);
+ let key_escaped = bytes[key.0..key.1].contains(&b'\\');
+ pos = skip_ws(bytes, key_end);
+ if bytes.get(pos) != Some(&b':') {
+ self.done = true;
+ return Some(Err(ScanError("expected ':' after object key")));
+ }
+ let value = match locate_value(bytes, pos + 1) {
+ Ok(v) => v,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ self.pos = value.1;
+ Some(Ok(Entry {
+ key,
+ key_escaped,
+ value,
+ }))
+ }
+}
+
+/// Iterates the top-level item spans of the array whose span is `arr` (must start at `[`).
+pub struct ArrayItems<'b> {
+ bytes: &'b [u8],
+ pos: usize,
+ end: usize,
+ done: bool,
+ first: bool,
+}
+
+pub fn array_items<'b>(bytes: &'b [u8], arr: Span) -> Result<ArrayItems<'b>> {
+ if bytes.get(arr.0) != Some(&b'[') {
+ return Err(ScanError("not an array"));
+ }
+ Ok(ArrayItems {
+ bytes,
+ pos: arr.0 + 1,
+ end: arr.1,
+ done: false,
+ first: true,
+ })
+}
+
+impl<'b> Iterator for ArrayItems<'b> {
+ type Item = Result<Span>;
+
+ fn next(&mut self) -> Option<Self::Item> {
+ if self.done {
+ return None;
+ }
+ let bytes = self.bytes;
+ let mut pos = skip_ws(bytes, self.pos);
+ if pos + 1 == self.end && bytes.get(pos) == Some(&b']') {
+ self.done = true;
+ return None;
+ }
+ if !self.first {
+ if bytes.get(pos) != Some(&b',') {
+ self.done = true;
+ return Some(Err(ScanError("expected ',' between array items")));
+ }
+ pos += 1;
+ }
+ self.first = false;
+ let item = match locate_value(bytes, pos) {
+ Ok(v) => v,
+ Err(e) => {
+ self.done = true;
+ return Some(Err(e));
+ }
+ };
+ self.pos = item.1;
+ Some(Ok(item))
+ }
+}
+
+/// Parse a scanned scalar span as a JSON number, mirroring what `JSON.parse` would produce (an f64).
+/// Returns `None` for non-numbers. Accepts the full JSON number grammar (fractions, exponents); the
+/// charset pre-check keeps Rust-isms like `inf`/`NaN` out.
+pub fn parse_number(bytes: &[u8], span: Span) -> Option<f64> {
+ let raw = bytes.get(span.0..span.1)?;
+ let first = *raw.first()?;
+ if first != b'-' && !first.is_ascii_digit() {
+ return None;
+ }
+ if !raw
+ .iter()
+ .all(|b| b.is_ascii_digit() || matches!(b, b'-' | b'+' | b'.' | b'e' | b'E'))
+ {
+ return None;
+ }
+ std::str::from_utf8(raw).ok()?.parse::<f64>().ok()
+}
+
+/// True when the span is exactly the JSON literal `null`.
+pub fn is_null(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0..span.1) == Some(b"null")
+}
+
+/// True when the span is a JSON string (starts with a quote).
+pub fn is_string(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'"')
+}
+
+/// True when the span is a JSON object.
+pub fn is_object(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'{')
+}
+
+/// True when the span is a JSON array.
+pub fn is_array(bytes: &[u8], span: Span) -> bool {
+ bytes.get(span.0) == Some(&b'[')
+}
+
+/// Decode a JSON string span (including its quotes), handling all JSON escapes including surrogate
+/// pairs. Escape-free strings (the overwhelming majority) borrow the input — zero copy.
+pub fn unescape<'b>(bytes: &'b [u8], span: Span) -> Result<std::borrow::Cow<'b, str>> {
+ let raw = bytes
+ .get(span.0..span.1)
+ .ok_or(ScanError("string span out of range"))?;
+ if raw.len() < 2 || raw[0] != b'"' || raw[raw.len() - 1] != b'"' {
+ return Err(ScanError("not a string span"));
+ }
+ let inner = &raw[1..raw.len() - 1];
+ if !inner.contains(&b'\\') {
+ return std::str::from_utf8(inner)
+ .map(std::borrow::Cow::Borrowed)
+ .map_err(|_| ScanError("invalid utf-8 in string"));
+ }
+ let mut out = Vec::with_capacity(inner.len());
+ let mut i = 0;
+ while i < inner.len() {
+ // Bulk-copy the clean run up to the next escape: one slice push per run, not per byte.
+ let run_start = i;
+ i = next_backslash(inner, i, inner.len());
+ out.extend_from_slice(&inner[run_start..i]);
+ if i >= inner.len() {
+ break;
+ }
+ let esc = *inner.get(i + 1).ok_or(ScanError("truncated escape"))?;
+ i += 2;
+ match esc {
+ b'"' => out.push(b'"'),
+ b'\\' => out.push(b'\\'),
+ b'/' => out.push(b'/'),
+ b'b' => out.push(0x08),
+ b'f' => out.push(0x0c),
+ b'n' => out.push(b'\n'),
+ b'r' => out.push(b'\r'),
+ b't' => out.push(b'\t'),
+ b'u' => {
+ let (ch, consumed) = decode_unicode(inner, i)?;
+ i += consumed;
+ let mut buf = [0u8; 4];
+ out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
+ }
+ _ => return Err(ScanError("bad escape")),
+ }
+ }
+ String::from_utf8(out)
+ .map(std::borrow::Cow::Owned)
+ .map_err(|_| ScanError("invalid utf-8 in string"))
+}
+
+/// Decode the `XXXX` (possibly a surrogate pair `XXXX\uYYYY`) after a `\u`, `at` pointing at the
+/// first hex digit. Returns the char and how many bytes were consumed.
+pub(crate) fn decode_unicode(bytes: &[u8], at: usize) -> Result<(char, usize)> {
+ let cp = hex4(bytes, at)?;
+ if (0xD800..0xDC00).contains(&cp) {
+ // High surrogate: pair it with the following \uXXXX low surrogate.
+ if bytes.get(at + 4) == Some(&b'\\') && bytes.get(at + 5) == Some(&b'u') {
+ let low = hex4(bytes, at + 6)?;
+ if (0xDC00..0xE000).contains(&low) {
+ let c = 0x10000 + ((cp as u32 - 0xD800) << 10) + (low as u32 - 0xDC00);
+ let ch = char::from_u32(c).ok_or(ScanError("invalid surrogate pair"))?;
+ return Ok((ch, 10));
+ }
+ }
+ return Ok((char::REPLACEMENT_CHARACTER, 4));
+ }
+ if (0xDC00..0xE000).contains(&cp) {
+ // Lone low surrogate.
+ return Ok((char::REPLACEMENT_CHARACTER, 4));
+ }
+ char::from_u32(cp as u32)
+ .map(|ch| (ch, 4))
+ .ok_or(ScanError("invalid codepoint"))
+}
+
+/// Unescape a JSON string span (including quotes) *in place*: decoded bytes are written over the
+/// span's own start (an unescaped string is never longer than its escaped form, so the write cursor
+/// trails the read cursor). Returns the decoded byte length, starting at `span.0 + 1`.
+///
+/// The buffer past the decoded bytes is left as scrap — callers must treat the span as consumed.
+/// Returns the decoded length and whether the decoded bytes are pure ASCII — ASCII output needs no
+/// further UTF-8 validation; non-ASCII output does (the second tuple field is `false`).
+pub fn unescape_in_place(bytes: &mut [u8], span: Span) -> Result<(usize, bool)> {
+ let raw_len = span.1.checked_sub(span.0).ok_or(ScanError("bad span"))?;
+ if raw_len < 2 || bytes.get(span.0) != Some(&b'"') || bytes.get(span.1 - 1) != Some(&b'"') {
+ return Err(ScanError("not a string span"));
+ }
+ let (start, end) = (span.0 + 1, span.1 - 1);
+ let Some(first) = memchr::memchr(b'\\', &bytes[start..end]) else {
+ let ascii = is_ascii_fold(&bytes[start..end]);
+ return Ok((end - start, ascii)); // escape-free: the bytes are already in place
+ };
+ let mut ascii = is_ascii_fold(&bytes[start..start + first]);
+ let mut rd = start + first;
+ let mut wr = rd;
+ while rd < end {
+ if bytes[rd] != b'\\' {
+ // Clean run: locate its end, then one copy_within.
+ let run_start = rd;
+ rd = next_backslash(bytes, rd, end);
+ ascii &= is_ascii_fold(&bytes[run_start..rd]);
+ bytes.copy_within(run_start..rd, wr);
+ wr += rd - run_start;
+ continue;
+ }
+ if rd + 1 >= end {
+ return Err(ScanError("truncated escape"));
+ }
+ let esc = bytes[rd + 1];
+ rd += 2;
+ let simple = match esc {
+ b'"' => b'"',
+ b'\\' => b'\\',
+ b'/' => b'/',
+ b'b' => 0x08,
+ b'f' => 0x0c,
+ b'n' => b'\n',
+ b'r' => b'\r',
+ b't' => b'\t',
+ b'u' => {
+ let (ch, consumed) = decode_unicode(&bytes[..end], rd)?;
+ rd += consumed;
+ ascii &= ch.is_ascii();
+ let mut buf = [0u8; 4];
+ let encoded = ch.encode_utf8(&mut buf).as_bytes();
+ bytes[wr..wr + encoded.len()].copy_from_slice(encoded);
+ wr += encoded.len();
+ continue;
+ }
+ _ => return Err(ScanError("bad escape")),
+ };
+ bytes[wr] = simple;
+ wr += 1;
+ }
+ Ok((wr - start, ascii))
+}
+
+/// OR-fold ASCII check (auto-vectorizes; the bytes are cache-warm from the surrounding copy).
+#[inline]
+fn is_ascii_fold(bytes: &[u8]) -> bool {
+ bytes.iter().fold(0u8, |acc, &b| acc | b) < 0x80
+}
+
+fn hex4(bytes: &[u8], at: usize) -> Result<u16> {
+ let mut v: u16 = 0;
+ for k in 0..4 {
+ let d = (*bytes.get(at + k).ok_or(ScanError("truncated \\u escape"))? as char)
+ .to_digit(16)
+ .ok_or(ScanError("bad hex digit"))?;
+ v = (v << 4) | d as u16;
+ }
+ Ok(v)
+}
+
+/// JSON-escape `s` into `out` as a quoted string, matching `JSON.stringify` byte-for-byte for the
+/// escapes it emits (control chars as `\u00xx`, everything else verbatim UTF-8).
+pub fn write_json_string(s: &str, out: &mut Vec<u8>) {
+ const HEX: &[u8; 16] = b"0123456789abcdef";
+ let bytes = s.as_bytes();
+ out.push(b'"');
+ let mut i = 0;
+ while i < bytes.len() {
+ // Bulk-copy the run needing no escape (scrubbed strings are long `*`/`#` runs).
+ let run_start = i;
+ while i < bytes.len() && !matches!(bytes[i], 0x00..=0x1f | b'"' | b'\\') {
+ i += 1;
+ }
+ out.extend_from_slice(&bytes[run_start..i]);
+ if i >= bytes.len() {
+ break;
+ }
+ let b = bytes[i];
+ i += 1;
+ match b {
+ b'"' => out.extend_from_slice(b"\\\""),
+ b'\\' => out.extend_from_slice(b"\\\\"),
+ 0x08 => out.extend_from_slice(b"\\b"),
+ 0x0c => out.extend_from_slice(b"\\f"),
+ b'\n' => out.extend_from_slice(b"\\n"),
+ b'\r' => out.extend_from_slice(b"\\r"),
+ b'\t' => out.extend_from_slice(b"\\t"),
+ _ => out.extend_from_slice(&[
+ b'\\',
+ b'u',
+ b'0',
+ b'0',
+ HEX[(b >> 4) as usize],
+ HEX[(b & 0xf) as usize],
+ ]),
+ }
+ }
+ out.push(b'"');
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn entries(json: &str) -> Vec<(String, String)> {
+ let bytes = json.as_bytes();
+ let span = locate_value(bytes, 0).unwrap();
+ object_entries(bytes, span)
+ .unwrap()
+ .map(|e| {
+ let e = e.unwrap();
+ (
+ String::from_utf8(bytes[e.key.0..e.key.1].to_vec()).unwrap(),
+ String::from_utf8(bytes[e.value.0..e.value.1].to_vec()).unwrap(),
+ )
+ })
+ .collect()
+ }
+
+ #[test]
+ fn object_scan_walks_nested_values_and_strings_with_brackets() {
+ let got = entries(r#"{ "a" : {"x":[1,2,{"y":"}"}]}, "b":"[{", "c": -1.5e3 , "d": null }"#);
+ assert_eq!(
+ got,
+ vec![
+ ("a".into(), r#"{"x":[1,2,{"y":"}"}]}"#.into()),
+ ("b".into(), r#""[{""#.into()),
+ ("c".into(), "-1.5e3".into()),
+ ("d".into(), "null".into()),
+ ]
+ );
+ }
+
+ #[test]
+ fn array_scan_yields_item_spans() {
+ let json = br#"[ {"a":1}, "two", 3, [4], null ]"#;
+ let span = locate_value(json, 0).unwrap();
+ let items: Vec<String> = array_items(json, span)
+ .unwrap()
+ .map(|s| {
+ let s = s.unwrap();
+ String::from_utf8(json[s.0..s.1].to_vec()).unwrap()
+ })
+ .collect();
+ assert_eq!(items, vec![r#"{"a":1}"#, r#""two""#, "3", "[4]", "null"]);
+ }
+
+ #[test]
+ fn malformed_structures_error_rather_than_hang_or_panic() {
+ for bad in [
+ r#"{"a" 1}"#, // missing colon
+ r#"{"a":1 "b":2}"#, // missing comma
+ r#"{"a":"unterminated"#,
+ r#"[1 2]"#,
+ r#"{"a":{"#,
+ ] {
+ let bytes = bad.as_bytes();
+ let Ok(span) = locate_value(bytes, 0) else {
+ continue; // structurally rejected up front is fine too
+ };
+ let result: std::result::Result<(), ScanError> = if bad.starts_with('{') {
+ match object_entries(bytes, span) {
+ Ok(mut it) => it.try_for_each(|r| r.map(|_| ())),
+ Err(e) => Err(e),
+ }
+ } else {
+ match array_items(bytes, span) {
+ Ok(mut it) => it.try_for_each(|r| r.map(|_| ())),
+ Err(e) => Err(e),
+ }
+ };
+ assert!(result.is_err(), "should reject: {bad}");
+ }
+ }
+
+ #[test]
+ fn number_parsing_matches_json_semantics() {
+ let cases: &[(&str, Option<f64>)] = &[
+ ("1234", Some(1234.0)),
+ ("-1.5", Some(-1.5)),
+ ("1.7e12", Some(1.7e12)),
+ ("2E+2", Some(200.0)),
+ ("1e999", Some(f64::INFINITY)), // JSON.parse("1e999") -> Infinity
+ ("\"str\"", None),
+ ("null", None),
+ ("true", None),
+ ("NaN", None),
+ ];
+ for (raw, expected) in cases {
+ let got = parse_number(raw.as_bytes(), (0, raw.len()));
+ assert_eq!(got, *expected, "case: {raw}");
+ }
+ }
+
+ #[test]
+ fn unescape_handles_escapes_and_surrogate_pairs() {
+ let cases: &[(&str, &str)] = &[
+ (r#""plain""#, "plain"),
+ (r#""a\nb\t\"c\"""#, "a\nb\t\"c\""),
+ (r#""é$""#, "é$"),
+ (r#""😀""#, "😀"),
+ (r#""\ud800x""#, "\u{FFFD}x"), // lone high surrogate
+ ];
+ for (raw, expected) in cases {
+ let got = unescape(raw.as_bytes(), (0, raw.len())).unwrap();
+ assert_eq!(&got, expected, "case: {raw}");
+ }
+ }
+
+ #[test]
+ fn write_json_string_round_trips_through_serde() {
+ for s in ["plain", "with \"quotes\" and \\", "ctl\u{1}\n\t", "π😀"] {
+ let mut out = Vec::new();
+ write_json_string(s, &mut out);
+ let parsed: String = serde_json::from_slice(&out).unwrap();
+ assert_eq!(parsed, s);
+ }
+ }
+
+ #[test]
+ fn escaped_keys_are_flagged() {
+ // `data` parses to the key `data`; a byte scanner can't see that, so it must flag the
+ // escape and let the caller fall back to a real parse instead of missing a routing key.
+ let json = br#"{"\u0064ata": 1}"#;
+ let span = locate_value(json, 0).unwrap();
+ let e = object_entries(json, span).unwrap().next().unwrap().unwrap();
+ assert!(e.key_escaped, "escaped key must be flagged for fallback");
+ }
+}
diff --git a/rust/ai-research/replay-core-v4/src/compression.rs b/rust/ai-research/replay-core-v4/src/compression.rs
new file mode 100644
index 000000000000..db57e00bac0f
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/compression.rs
@@ -0,0 +1,293 @@
+//! The compression codecs of the v4 reader, in one place: gzip on libdeflate, which needs the
+//! output size up front (gzip carries it in its ISIZE footer), the zstd pair (`compress_cv` writes
+//! cv payloads; `unzstd` reads them back), the lz4 block leg for capture-wrapped Kafka values, and
+//! the magic-byte dispatch over a cv stream. The `gzip` compressor exists for tests that simulate
+//! the SDK wire format.
+
+use std::cell::RefCell;
+use std::io::Read;
+
+use anyhow::{anyhow, bail, Result};
+use libdeflater::{CompressionLvl, Compressor, Decompressor};
+
+/// Compression-bomb cap: ~6x the 10.3 MB largest payload in a 1000-message production sample.
+/// Exceeding it fails closed as a classified DLQ instead of an unclassifiable OOM crash-loop.
+pub const MAX_DECOMPRESSED_BYTES: usize = 64 * 1024 * 1024;
+
+/// Leading magic of a gzip member (RFC 1952).
+pub const GZIP_MAGIC: [u8; 2] = [0x1f, 0x8b];
+
+/// Leading magic of a zstd frame (RFC 8878).
+pub const ZSTD_MAGIC: [u8; 4] = [0x28, 0xb5, 0x2f, 0xfd];
+
+/// zstd level for written cv payloads. Negative on purpose: cv bytes are stored as latin-1 in
+/// JSON, where each high byte costs 2 UTF-8 bytes and a block codec cannot compress it. A negative
+/// level leaves more ASCII literals, so the stored bytes are smaller although the raw ratio is
+/// worse.
+const CV_ZSTD_LEVEL: i32 = -1;
+
+/// zstd `windowLogMax` cap. The decoder's back-reference window can't exceed our decompressed-size
+/// cap (2^26 = 64 MiB), so a frame header declaring a huge `windowLog` can't force an outsized
+/// working-buffer allocation before the size cap engages. Real cv payloads sit far below this.
+const CV_ZSTD_WINDOW_LOG_MAX: u32 = 26;
+
+thread_local! {
+ // Reused per thread: each codec state is a one-time ~50-300 KB malloc and cv work runs several
+ // times per event.
+ static DECOMPRESSOR: RefCell<Decompressor> = RefCell::new(Decompressor::new());
+ static COMPRESSOR: RefCell<Compressor> =
+ RefCell::new(Compressor::new(CompressionLvl::default()));
+ static ZSTD_COMPRESSOR: RefCell<zstd::bulk::Compressor<'static>> = RefCell::new(
+ zstd::bulk::Compressor::new(CV_ZSTD_LEVEL).expect("static zstd level is valid"),
+ );
+ static ZSTD_DECOMPRESSOR: RefCell<zstd::bulk::Decompressor<'static>> = RefCell::new({
+ let mut d = zstd::bulk::Decompressor::new().expect("default zstd decompressor is valid");
+ d.set_parameter(zstd::zstd_safe::DParameter::WindowLogMax(CV_ZSTD_WINDOW_LOG_MAX))
+ .expect("window log max is a valid decompression parameter");
+ d
+ });
+}
+
+/// Gunzip a single-member stream. The output buffer is sized exactly from the stream's ISIZE
+/// footer (uncompressed length mod 2^32, RFC 1952), so both footer lies fail closed: claiming
+/// more than [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating, and claiming less than the
+/// real size makes libdeflate stop at the buffer end with `InsufficientSpace`.
+pub fn gunzip(raw: &[u8]) -> Result<Vec<u8>> {
+ let Some(footer) = raw.len().checked_sub(4).map(|start| &raw[start..]) else {
+ bail!("gzip stream too short");
+ };
+ let hint = u32::from_le_bytes(footer.try_into().expect("4-byte slice")) as usize;
+ if hint > MAX_DECOMPRESSED_BYTES {
+ bail!("gzip uncompressed size exceeds limit");
+ }
+ let mut out = vec![0u8; hint];
+ let n = DECOMPRESSOR
+ .with(|d| d.borrow_mut().gzip_decompress(raw, &mut out))
+ .map_err(|e| anyhow!("gunzip: {e:?}"))?;
+ out.truncate(n);
+ Ok(out)
+}
+
+/// Gzip `payload` as one default-level (6, matching both flate2's default and pako's default)
+/// member.
+pub fn gzip(payload: &[u8]) -> Result<Vec<u8>> {
+ COMPRESSOR.with(|c| {
+ let mut c = c.borrow_mut();
+ let mut out = vec![0u8; c.gzip_compress_bound(payload.len())];
+ let n = c
+ .gzip_compress(payload, &mut out)
+ .map_err(|e| anyhow!("gzip: {e:?}"))?;
+ out.truncate(n);
+ Ok(out)
+ })
+}
+
+/// Decompress a single zstd frame. Unlike gzip there is no ISIZE trailer: when the frame header
+/// declares its content size the output buffer is sized from it (a declaration past
+/// [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating), and a frame without one falls back to
+/// a streaming decode capped at the same limit.
+///
+/// The input must be exactly one frame that consumes every byte. Trailing bytes, concatenated
+/// frames, and appended skippable frames all decode to less than the input. A caller that keeps
+/// the original bytes of an unchanged payload would then keep bytes it never decompressed. So
+/// anything but a single self-contained frame fails closed.
+pub fn unzstd(raw: &[u8]) -> Result<Vec<u8>> {
+ match zstd::zstd_safe::find_frame_compressed_size(raw) {
+ Ok(n) if n == raw.len() => {}
+ Ok(_) => bail!("zstd cv payload is not a single self-contained frame"),
+ Err(code) => bail!("zstd frame: {}", zstd::zstd_safe::get_error_name(code)),
+ }
+ match zstd::zstd_safe::get_frame_content_size(raw) {
+ Ok(Some(size)) => {
+ if size > MAX_DECOMPRESSED_BYTES as u64 {
+ bail!("zstd declared content size exceeds limit");
+ }
+ ZSTD_DECOMPRESSOR
+ .with(|d| d.borrow_mut().decompress(raw, size as usize))
+ .map_err(|e| anyhow!("unzstd: {e}"))
+ }
+ Ok(None) => {
+ let mut decoder = zstd::stream::read::Decoder::new(raw)?;
+ decoder.window_log_max(CV_ZSTD_WINDOW_LOG_MAX)?;
+ let mut out = Vec::new();
+ decoder
+ .take(MAX_DECOMPRESSED_BYTES as u64 + 1)
+ .read_to_end(&mut out)
+ .map_err(|e| anyhow!("unzstd (streaming): {e}"))?;
+ if out.len() > MAX_DECOMPRESSED_BYTES {
+ bail!("zstd uncompressed size exceeds limit");
+ }
+ Ok(out)
+ }
+ Err(e) => bail!("zstd frame header: {e}"),
+ }
+}
+
+/// Compress a cv payload as zstd. A reader tells the formats apart by magic bytes alone
+/// (`1f 8b` gzip vs `28 b5 2f fd` zstd), so gzip payloads stay readable.
+pub fn compress_cv(payload: &[u8]) -> Result<Vec<u8>> {
+ ZSTD_COMPRESSOR.with(|c| {
+ c.borrow_mut()
+ .compress(payload)
+ .map_err(|e| anyhow!("zstd: {e}"))
+ })
+}
+
+/// Decompress a compressed stream by its leading magic: gzip (the SDK wire format) or zstd (what
+/// [`compress_cv`] writes). Unknown magic fails closed. The only limit is
+/// [`MAX_DECOMPRESSED_BYTES`] per stream. A caller that reads many streams for one message sets
+/// its own budget.
+pub fn decompress_by_magic(raw: &[u8]) -> Result<Vec<u8>> {
+ if raw.starts_with(&GZIP_MAGIC) {
+ gunzip(raw)
+ } else if raw.starts_with(&ZSTD_MAGIC) {
+ unzstd(raw)
+ } else {
+ bail!("cv stream is neither gzip nor zstd");
+ }
+}
+
+/// Decompress an lz4 *block* (not frame) with capture's 4-byte LE uncompressed-size prefix. Both
+/// prefix lies fail closed: a size over [`MAX_DECOMPRESSED_BYTES`] is rejected before allocating (a
+/// forged u32 prefix can claim up to 4 GiB), and a decoded length that disagrees with the prefix is
+/// an error rather than a short/long buffer surfacing later as invalid JSON.
+pub fn unlz4_block(raw: &[u8]) -> Result<Vec<u8>> {
+ let Some(size_bytes) = raw.get(..4).and_then(|b| <[u8; 4]>::try_from(b).ok()) else {
+ bail!("lz4 payload too short for size prefix");
+ };
+ let size = u32::from_le_bytes(size_bytes) as usize;
+ if size > MAX_DECOMPRESSED_BYTES {
+ bail!("lz4 uncompressed size exceeds limit");
+ }
+ let out = lz4::block::decompress(&raw[4..], Some(size as i32))
+ .map_err(|e| anyhow!("lz4 decompress failed: {e}"))?;
+ if out.len() != size {
+ bail!("lz4 decoded length does not match the size prefix");
+ }
+ Ok(out)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::io::{Read, Write};
+
+ #[test]
+ fn round_trips_through_an_independent_codec() {
+ let payload = b"hello hello hello compression".repeat(50);
+
+ // Ours -> flate2: the member we emit must be a standard gzip stream.
+ let ours = gzip(&payload).unwrap();
+ let mut via_flate2 = Vec::new();
+ flate2::read::GzDecoder::new(&ours[..])
+ .read_to_end(&mut via_flate2)
+ .unwrap();
+ assert_eq!(via_flate2, payload);
+
+ // flate2 -> ours: we must decode members other encoders produced.
+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ enc.write_all(&payload).unwrap();
+ let theirs = enc.finish().unwrap();
+ assert_eq!(gunzip(&theirs).unwrap(), payload);
+ }
+
+ #[test]
+ fn rejects_a_footer_claiming_more_than_the_cap() {
+ let mut stream = gzip(b"small").unwrap();
+ let n = stream.len();
+ stream[n - 4..].copy_from_slice(&(u32::MAX).to_le_bytes());
+ let err = gunzip(&stream).unwrap_err().to_string();
+ assert!(err.contains("exceeds limit"), "got: {err}");
+ }
+
+ #[test]
+ fn fails_closed_on_a_footer_claiming_less_than_the_real_size() {
+ let payload = b"0123456789".repeat(100);
+ let mut stream = gzip(&payload).unwrap();
+ let n = stream.len();
+ stream[n - 4..].copy_from_slice(&8u32.to_le_bytes());
+ assert!(gunzip(&stream).is_err());
+ }
+
+ #[test]
+ fn rejects_truncated_and_empty_streams() {
+ assert!(gunzip(b"").is_err());
+ assert!(gunzip(&[0x1f, 0x8b, 0x08]).is_err());
+ }
+
+ #[test]
+ fn unzstd_round_trips_bulk_and_streaming_frames() {
+ let payload = b"zstd zstd zstd payload".repeat(100);
+ // Bulk frame with a declared content size — what `compress_cv` emits.
+ let bulk = compress_cv(&payload).unwrap();
+ assert_eq!(unzstd(&bulk).unwrap(), payload);
+ // A streaming encoder omits the content size, exercising the capped streaming leg.
+ let mut enc = zstd::stream::write::Encoder::new(Vec::new(), 1).unwrap();
+ std::io::Write::write_all(&mut enc, &payload).unwrap();
+ let streamed = enc.finish().unwrap();
+ assert_eq!(
+ zstd::zstd_safe::get_frame_content_size(&streamed).unwrap(),
+ None,
+ "fixture must omit the declared content size"
+ );
+ assert_eq!(unzstd(&streamed).unwrap(), payload);
+ }
+
+ #[test]
+ fn unzstd_rejects_a_declared_size_over_the_cap() {
+ let frame = compress_cv(&vec![0u8; MAX_DECOMPRESSED_BYTES + 1]).unwrap();
+ let err = unzstd(&frame).unwrap_err().to_string();
+ assert!(err.contains("exceeds limit"), "got: {err}");
+ }
+
+ #[test]
+ fn unzstd_rejects_garbage() {
+ assert!(unzstd(b"").is_err());
+ assert!(unzstd(&[0x28, 0xb5, 0x2f, 0xfd, 0x00]).is_err());
+ }
+
+ #[test]
+ fn unzstd_rejects_non_single_frame_payloads() {
+ // Bytes past the first frame would ride verbatim into a "kept unchanged" re-emit without
+ // ever being decompressed/scrubbed, so a single self-contained frame is required.
+ let frame = compress_cv(b"clean cv content").unwrap();
+
+ // Two concatenated frames.
+ let mut concatenated = frame.clone();
+ concatenated.extend_from_slice(&frame);
+ assert!(unzstd(&concatenated)
+ .unwrap_err()
+ .to_string()
+ .contains("single self-contained frame"));
+
+ // A skippable frame appended (magic 0x184D2A50, 4-byte LE length, then arbitrary bytes).
+ let mut with_skippable = frame.clone();
+ with_skippable.extend_from_slice(&[0x50, 0x2a, 0x4d, 0x18]);
+ with_skippable.extend_from_slice(&4u32.to_le_bytes());
+ with_skippable.extend_from_slice(b"junk");
+ assert!(unzstd(&with_skippable)
+ .unwrap_err()
+ .to_string()
+ .contains("single self-contained frame"));
+
+ // Trailing garbage after a complete frame.
+ let mut with_trailing = frame.clone();
+ with_trailing.extend_from_slice(b"trailing");
+ assert!(unzstd(&with_trailing).is_err());
+
+ // The clean single frame still decodes.
+ assert_eq!(unzstd(&frame).unwrap(), b"clean cv content");
+ }
+
+ #[test]
+ fn compress_cv_emits_a_zstd_frame() {
+ // Magic-byte dispatch is the consumer contract, so pin the emitted magic.
+ let payload = b"payload".repeat(20);
+ let zs = compress_cv(&payload).unwrap();
+ assert_eq!(&zs[..4], &[0x28, 0xb5, 0x2f, 0xfd]);
+ assert_eq!(
+ zstd::bulk::decompress(&zs, payload.len() + 64).unwrap(),
+ payload
+ );
+ }
+}
diff --git a/rust/ai-research/replay-core-v4/src/lib.rs b/rust/ai-research/replay-core-v4/src/lib.rs
index b0899ab8c573..d0b84dee02af 100644
--- a/rust/ai-research/replay-core-v4/src/lib.rs
+++ b/rust/ai-research/replay-core-v4/src/lib.rs
@@ -1,9 +1,13 @@
//! The v4 AI research replay dataset: the format in `products/ai_training/docs/replay-data.md`, section "v4 dataset".
+pub mod bytescan;
+pub mod compression;
pub mod envelope;
pub mod gate;
#[cfg(feature = "store")]
pub mod keys;
+pub mod payload;
pub mod refs;
pub mod seal;
pub mod session;
+pub mod url_policy;
diff --git a/rust/ai-research/replay-core-v4/src/payload.rs b/rust/ai-research/replay-core-v4/src/payload.rs
new file mode 100644
index 000000000000..a527cdc58ad8
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/payload.rs
@@ -0,0 +1,89 @@
+//! Decompress a raw replay Kafka message value and tell web replays from mobile ones.
+
+/// Why a payload could not be read; maps onto the TS pipeline's dlq/drop reasons.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FailKind {
+ /// The Kafka message value could not be decompressed (dlq `invalid_compressed_data`).
+ InvalidCompressedData,
+}
+
+impl FailKind {
+ pub fn reason(self) -> &'static str {
+ match self {
+ FailKind::InvalidCompressedData => "invalid_compressed_data",
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct Failure {
+ pub kind: FailKind,
+ pub detail: String,
+}
+
+impl Failure {
+ fn new(kind: FailKind, detail: impl Into<String>) -> Self {
+ Self {
+ kind,
+ detail: detail.into(),
+ }
+ }
+}
+
+type SResult<T> = Result<T, Failure>;
+
+/// Capture writes `web` when a client sends no source, so a missing source never comes from capture.
+pub fn is_web_replay(snapshot_source: Option<&str>) -> bool {
+ snapshot_source == Some("web")
+}
+
+const GZIP_MAGIC: &[u8; 4] = &[0x1f, 0x8b, 0x08, 0x00];
+
+/// Decompress a raw Kafka message value the way capture wraps it (mirrors the TS
+/// `decompressMessageValue`): lz4 block with a 4-byte LE uncompressed-size prefix when the
+/// `content-encoding` header says lz4, gzip when the magic bytes say so, else pass through.
+/// Codec failures classify as `invalid_compressed_data`, matching the TS path.
+pub fn decompress_payload(raw: Vec<u8>, content_encoding: Option<&str>) -> SResult<Vec<u8>> {
+ let bad = |e: anyhow::Error| Failure::new(FailKind::InvalidCompressedData, format!("{e:#}"));
+ if content_encoding == Some("lz4") {
+ return crate::compression::unlz4_block(&raw).map_err(bad);
+ }
+ if raw.starts_with(GZIP_MAGIC) {
+ return crate::compression::gunzip(&raw)
+ .map_err(|e| bad(e.context("gzip decompress failed")));
+ }
+ Ok(raw)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn decompress_payload_matches_the_capture_producer_format() {
+ let body = br#"{"distinct_id":"d","data":"{}"}"#.to_vec();
+
+ // lz4: capture writes `block::compress` output behind a 4-byte LE uncompressed-size prefix,
+ // signalled by the content-encoding header.
+ let compressed = lz4::block::compress(&body, None, false).unwrap();
+ let mut framed = (body.len() as u32).to_le_bytes().to_vec();
+ framed.extend_from_slice(&compressed);
+ assert_eq!(decompress_payload(framed, Some("lz4")).unwrap(), body);
+
+ // gzip: detected by magic bytes, no header needed.
+ {
+ use std::io::Write;
+ let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
+ enc.write_all(&body).unwrap();
+ let zipped = enc.finish().unwrap();
+ assert_eq!(decompress_payload(zipped, None).unwrap(), body);
+ }
+
+ // Uncompressed passes through untouched.
+ assert_eq!(decompress_payload(body.clone(), None).unwrap(), body);
+
+ // Corrupt lz4 fails closed with the TS parse step's classification.
+ let err = decompress_payload(vec![9, 0, 0, 0, 0xff, 0xff], Some("lz4")).unwrap_err();
+ assert_eq!(err.kind.reason(), "invalid_compressed_data");
+ }
+}
diff --git a/rust/ai-research/replay-core-v4/src/tracking_beacons.txt b/rust/ai-research/replay-core-v4/src/tracking_beacons.txt
new file mode 100644
index 000000000000..45e083b80fe5
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/tracking_beacons.txt
@@ -0,0 +1,142 @@
+# Advertising and analytics beacons. The replay collector and the image fetcher refuse these.
+#
+# One entry per line: <host pattern><path prefix>
+# host pattern an exact host, "*.example.com" for every host below example.com, or "*" for every host
+# path prefix starts with "/" and is compared case-insensitively with the start of the decoded
+# request path. A prefix that does not end with "/" must end at a segment boundary,
+# so "host/tr" refuses "/tr" and "/tr/x" but not "/trending/x". "/" alone matches
+# every path on the host, and "*/" alone is refused.
+# A line that starts with "#" and a blank line are ignored.
+#
+# url_policy.rs embeds this file. The recorder refuses a match when it collects a URL, and the
+# fetcher refuses a match again for every job it reads from the frontier, so an entry added here
+# also drains the queued backlog for that beacon without a request. A change here ships only with
+# an image build of both lanes. A malformed line fails the crate's tests.
+
+# X / Twitter Ads conversion pixel
+analytics.twitter.com/i/adsct
+t.co/i/adsct
+
+# Microsoft Advertising UET and Clarity
+bat.bing.com/action
+bat.bing.net/action
+c.bing.com/c.gif
+c.clarity.ms/c.gif
+
+# Meta pixel
+www.facebook.com/tr
+
+# Google Ads, Floodlight, and Analytics
+www.google.com/pagead/1p-user-list
+www.google.com/pagead/1p-conversion
+www.google.com/ads/ga-audiences
+www.googleadservices.com/pagead/conversion
+googleads.g.doubleclick.net/pagead
+ad.doubleclick.net/ddm/activity
+*.fls.doubleclick.net/activityi
+cm.g.doubleclick.net/
+stats.g.doubleclick.net/
+securepubads.g.doubleclick.net/pcs
+google-analytics.com/
+*.google-analytics.com/
+
+# LinkedIn Insight Tag
+px.ads.linkedin.com/
+dc.ads.linkedin.com/
+www.linkedin.com/px
+
+# TikTok, Pinterest, Snap, Quora, and Reddit pixels
+analytics.tiktok.com/
+ct.pinterest.com/
+tr.snapchat.com/
+q.quora.com/_/ad
+alb.reddit.com/
+
+# Shopify storefront pixel
+v.shopify.com/last_shop
+
+# HubSpot, WordPress, Segment, and Mixpanel image beacons
+track.hubspot.com/__ptq.gif
+pixel.wp.com/
+api.segment.io/v1/pixel
+api.mixpanel.com/track
+
+# Yandex Metrica, VK, and Mail.ru
+mc.yandex.ru/watch
+mc.yandex.ru/pixel
+mc.yandex.com/watch
+mc.yandex.com/pixel
+vk.com/rtrg
+top-fwz1.mail.ru/
+
+# Adobe Analytics and Audience Manager, on Adobe hosts and on customer CNAMEs
+*.omtrdc.net/b/ss
+*.2o7.net/b/ss
+*/b/ss/
+*.demdex.net/
+cm.everesttech.net/
+
+# Legacy Google Analytics, Matomo, and Piwik image beacons at the site root of any host
+*/__utm.gif
+*/matomo.php
+*/piwik.php
+
+# Retargeting, cookie sync, and bidder pixels
+d.adroll.com/
+*.bidr.io/
+insight.adsrvr.org/
+*.adnxs.com/
+*.criteo.com/
+trc.taboola.com/
+trc-events.taboola.com/
+tr.outbrain.com/
+sp.analytics.yahoo.com/
+pixel.advertising.com/
+*.amazon-adsystem.com/
+*.rubiconproject.com/
+*.casalemedia.com/
+*.pubmatic.com/
+*.openx.net/
+p.adsymptotic.com/
+*.mathtag.com/
+*.rlcdn.com/
+*.agkn.com/
+*.bluekai.com/
+*.exelator.com/
+*.krxd.net/
+pixel.tapad.com/
+*.3lift.com/
+match.sharethrough.com/
+*.teads.tv/
+*.smartadserver.com/
+*.liadm.com/
+*.id5-sync.com/
+*.bidswitch.net/
+tags.srv.stackadapt.com/
+creativecdn.com/tags
+*.creativecdn.com/tags
+*.zemanta.com/
+tag.perfectaudience.com/
+pixel.sitescout.com/
+bh.contextweb.com/
+*.sonobi.com/
+rtb.gumgum.com/
+ap.lijit.com/
+*.pippio.com/
+*.semasio.net/
+*.dotomi.com/
+*.bttrack.com/
+
+# Sales intelligence trackers
+serve.albacross.com/
+b.6sc.co/
+epsilon.6sense.com/
+
+# Affiliate network pixels
+www.awin1.com/sread.img
+www.emjcd.com/
+track.linksynergy.com/
+
+# Email open pixels rendered inside web apps
+mandrillapp.com/track/open.php
+*.ct.sendgrid.net/wf/open
diff --git a/rust/ai-research/replay-core-v4/src/url_policy.rs b/rust/ai-research/replay-core-v4/src/url_policy.rs
new file mode 100644
index 000000000000..0798daa1f68e
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/url_policy.rs
@@ -0,0 +1,1031 @@
+//! The rules that decide whether a remote image URL may be fetched, and what its canonical forms
+//! are.
+//!
+//! The recorder collects the URLs of one message. This module holds only the policy, because the
+//! policy has more than one consumer.
+//!
+//! The fetch lane applies the same host rule again at request time. It applies it to the resolved
+//! address, and to every redirect hop, because a name that resolves publicly now can resolve
+//! privately later. The fetch lane also canonicalizes what it fetched, to find its ledger entry.
+//!
+//! The fetch lane runs in another language. The registrable domain therefore travels with each
+//! URL as data, so that lane reads the result and never repeats the rule.
+
+use std::collections::HashSet;
+use std::net::IpAddr;
+use std::sync::LazyLock;
+
+use percent_encoding::percent_decode_str;
+use public_suffix::{EffectiveTLDProvider, DEFAULT_PROVIDER};
+
+use url::Url;
+
+mod shopify;
+
+const VOLATILE_PARAMS: &[&str] = &["cb", "nocache", "rnd"];
+
+const CREDENTIAL_PARAMS: &[&str] = &[
+ "__cld_token__",
+ "__token__",
+ "access_token",
+ "api_key",
+ "apikey",
+ "auth_token",
+ "authorization",
+ "awsaccesskeyid",
+ "credential",
+ "googleaccessid",
+ "hdnea",
+ "hdntl",
+ "hdnts",
+ "id_token",
+ "ik-s",
+ "jsessionid",
+ "ossaccesskeyid",
+ "phpsessid",
+ "q-ak",
+ "q-signature",
+ "security-token",
+ "session_token",
+ "sessionid",
+ "sig",
+ "signature",
+ "signedheaders",
+ "token",
+ "x-amz-credential",
+ "x-amz-security-token",
+ "x-amz-signature",
+ "x-amz-signedheaders",
+ "x-cos-security-token",
+ "x-goog-credential",
+ "x-goog-signature",
+ "x-goog-signedheaders",
+ "x-oss-credential",
+ "x-oss-security-token",
+ "x-oss-signature",
+];
+
+const SCOPED_VOLATILE_PARAMS: &[(&str, &[&str])] =
+ &[("_nc_ohc", &["_nc_ohc", "_nc_ht", "ccb", "oe", "oh", "stp"])];
+
+/// The advertising and analytics beacons the lane refuses. The file documents its own format.
+const TRACKING_BEACONS: &str = include_str!("tracking_beacons.txt");
+
+enum BeaconHost {
+ Any,
+ /// `*.example.com`: every host below the suffix, never the suffix itself.
+ Below(String),
+ Exact(String),
+}
+
+struct BeaconPattern {
+ host: BeaconHost,
+ path_prefix: String,
+}
+
+impl BeaconPattern {
+ /// A prefix that does not end with `/` must end at a segment boundary, so that `host/tr` refuses
+ /// `/tr` and `/tr/x` but not `/trending/x.png`. A `;` also ends the segment, because Floodlight
+ /// puts its parameters after one (`/activityi;src=...`).
+ fn matches(&self, host: &str, path: &str) -> bool {
+ let host_matches = match &self.host {
+ BeaconHost::Any => true,
+ BeaconHost::Below(suffix) => host.ends_with(suffix.as_str()),
+ BeaconHost::Exact(exact) => host == exact,
+ };
+ let Some(rest) = path.strip_prefix(self.path_prefix.as_str()) else {
+ return false;
+ };
+ host_matches
+ && (self.path_prefix.ends_with('/')
+ || rest.is_empty()
+ || rest.starts_with('/')
+ || rest.starts_with(';'))
+ }
+}
+
+static TRACKING_BEACON_PATTERNS: LazyLock<Vec<BeaconPattern>> = LazyLock::new(|| {
+ parse_beacon_list(TRACKING_BEACONS)
+ .unwrap_or_else(|line| panic!("tracking_beacons.txt has a malformed entry: {line:?}"))
+});
+
+fn parse_beacon_list(text: &str) -> Result<Vec<BeaconPattern>, String> {
+ let mut patterns = Vec::new();
+ for line in text.lines().map(str::trim) {
+ if line.is_empty() || line.starts_with('#') {
+ continue;
+ }
+ let Some(slash) = line.find('/') else {
+ return Err(line.to_string());
+ };
+ let (host, path) = line.split_at(slash);
+ // A scheme, port, space, or trailing dot in the host, or a comment, query, or percent-encoding
+ // in the path, would parse as an entry that can never match, so it is refused instead of
+ // shipping as a silent no-op. A catch-all entry is refused too, because it would stop the
+ // whole lane with only a counter as evidence.
+ let host_is_malformed = host.contains(|c: char| c == ':' || c.is_whitespace())
+ || (host != "*" && (!host.contains('.') || host.ends_with('.')));
+ let path_is_malformed =
+ path.contains(|c: char| c.is_whitespace() || matches!(c, '#' | '?' | '%'));
+ if host_is_malformed || path_is_malformed || (host == "*" && path == "/") {
+ return Err(line.to_string());
+ }
+ let host = match host {
+ "*" => BeaconHost::Any,
+ _ if host.starts_with("*.") && host.len() > 2 && !host[1..].contains('*') => {
+ BeaconHost::Below(host[1..].to_ascii_lowercase())
+ }
+ _ if !host.is_empty() && !host.contains('*') => {
+ BeaconHost::Exact(host.to_ascii_lowercase())
+ }
+ _ => return Err(line.to_string()),
+ };
+ patterns.push(BeaconPattern {
+ host,
+ path_prefix: path.to_ascii_lowercase(),
+ });
+ }
+ Ok(patterns)
+}
+
+/// Whether a host and decoded path name an entry in `tracking_beacons.txt`.
+pub fn is_tracking_beacon(host: &str, path: &str) -> bool {
+ let host = host.strip_suffix('.').unwrap_or(host).to_ascii_lowercase();
+ matches_beacon_list(&host, &collapse_slashes(&path.to_ascii_lowercase()))
+}
+
+/// `host` and `path` must already be lowercase, and the path decoded with its slashes collapsed.
+fn matches_beacon_list(host: &str, path: &str) -> bool {
+ TRACKING_BEACON_PATTERNS
+ .iter()
+ .any(|pattern| pattern.matches(host, path))
+}
+
+/// Origin servers collapse a doubled slash, so `//adsct` and `/adsct` name one resource to them.
+fn collapse_slashes(path: &str) -> String {
+ let mut collapsed = String::with_capacity(path.len());
+ for character in path.chars() {
+ if character == '/' && collapsed.ends_with('/') {
+ continue;
+ }
+ collapsed.push(character);
+ }
+ collapsed
+}
+
+/// Longer than this and we neither collect nor fetch it. Well past what a real image URL needs,
+/// and it bounds what one message can pin in memory alongside the count cap.
+pub const MAX_URL_LEN: usize = 2048;
+
+/// The politeness unit for a host: the registrable domain, or the host itself when it has none.
+///
+/// A rate limit protects the operator that answers the request, not a DNS label. A CDN that shards
+/// over `img1..img8.cdn.example.com` would otherwise receive eight times the intended rate.
+/// The fetch topic keys on this, so every URL of one operator lands on one partition and one pod
+/// holds its budget without a distributed lock.
+///
+/// The public suffix list draws the boundary, and its private section is what makes this correct
+/// for multi-tenant hosts. `d111.cloudfront.net`, `bucket.s3.amazonaws.com`, `user.github.io` and
+/// `myapp.vercel.app` are each their own registrable domain, because `cloudfront.net`,
+/// `s3.amazonaws.com`, `github.io` and `vercel.app` are all public suffixes. One tenant therefore
+/// never shares a budget with an unrelated tenant of the same provider.
+///
+/// An IP literal has no registrable domain and returns unchanged, which is right: the address is
+/// the operator.
+pub fn politeness_key(host: &str) -> String {
+ // `example.com.` and `example.com` are one operator, so two spellings must not take two
+ // budgets, two breakers, and two partitions. Brackets stay, because an IPv6 literal keys in the
+ // form the URL carries.
+ let host = host.strip_suffix('.').unwrap_or(host);
+ if host.parse::<IpAddr>().is_ok() || host.starts_with('[') {
+ return host.to_string();
+ }
+ match DEFAULT_PROVIDER.effective_tld_plus_one(host) {
+ Ok(domain) => domain.to_string(),
+ // A host with no registrable domain is its own operator. `is_public_host` already declined
+ // the bare names this could otherwise return.
+ Err(_) => host.to_string(),
+ }
+}
+
+/// The two forms of one URL. See the module docs for why both exist.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct CanonicalUrl {
+ pub fetch: String,
+ pub dedup: String,
+ pub host: String,
+ /// The registrable domain of `host`. See [`politeness_key`].
+ pub domain: String,
+}
+
+fn is_volatile(name: &str, names_on_this_url: &HashSet<String>) -> bool {
+ if VOLATILE_PARAMS
+ .iter()
+ .any(|volatile| volatile.eq_ignore_ascii_case(name))
+ {
+ return true;
+ }
+ SCOPED_VOLATILE_PARAMS.iter().any(|(marker, names)| {
+ names_on_this_url.contains(*marker)
+ && names
+ .iter()
+ .any(|volatile| volatile.eq_ignore_ascii_case(name))
+ })
+}
+
+/// Whether a host is one we would ever fetch from.
+///
+/// A page controls the URL set, and the set exists to be handed to something that makes outbound
+/// requests from inside our network. A page carrying
+/// `<img src="http://169.254.169.254/...">` must not become a fetch instruction for the cloud
+/// metadata endpoint.
+///
+/// This is not a substitute for a check at fetch time. A name that resolves publicly now can
+/// resolve privately later. The fetcher therefore validates the address DNS returns, on the first
+/// request and on every redirect hop.
+pub fn is_public_host(host: &str) -> bool {
+ let host = without_brackets_or_trailing_dot(host);
+ if host.parse::<IpAddr>().is_ok() {
+ return false;
+ }
+ is_public_domain_name(&host.to_ascii_lowercase())
+}
+
+/// `[2606:4700::1111]` becomes `2606:4700::1111`, and `localhost.` becomes `localhost`.
+///
+/// A trailing dot makes a name fully qualified and resolves identically, so leaving it on let
+/// `localhost.` past the name check below: the label after the final dot is empty and matches
+/// nothing.
+fn without_brackets_or_trailing_dot(host: &str) -> &str {
+ let bare = host.trim_matches(|c| c == '[' || c == ']');
+ bare.strip_suffix('.').unwrap_or(bare)
+}
+
+fn is_public_domain_name(lowercase_host: &str) -> bool {
+ let has_no_dot = !lowercase_host.contains('.');
+ let has_empty_label = lowercase_host.split('.').any(|label| label.is_empty());
+ if has_no_dot || has_empty_label {
+ return false;
+ }
+ !matches!(
+ lowercase_host.rsplit('.').next(),
+ Some(
+ "localhost"
+ | "local"
+ | "internal"
+ | "intranet"
+ | "lan"
+ | "home"
+ | "corp"
+ | "test"
+ | "invalid"
+ | "example"
+ )
+ )
+}
+
+/// Why a URL was not collected. Each variant is a label on the decline counter. A lane
+/// that collects less than it should then reads off a dashboard, rather than being guessed at.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+#[non_exhaustive]
+pub enum Decline {
+ /// Longer than [`MAX_URL_LEN`], before or after normalization.
+ TooLong,
+ /// Not parseable as an absolute URL. A relative `src` lands here, because the recording does
+ /// not carry the base it would need to resolve against.
+ NotAbsolute,
+ /// A scheme we do not fetch. Only `https` passes, so plain `http` lands here too.
+ BadScheme,
+ /// A port the scheme does not own. See the port check in [`try_canonicalize`].
+ BadPort,
+ /// No host at all.
+ NoHost,
+ /// Loopback, private, link-local or an internal-only name. See [`is_public_host`].
+ NonPublicHost,
+ /// A known URL credential, signature, token, signed-header list, or non-empty userinfo.
+ Credential,
+ /// A query parameter name could not be percent-decoded as UTF-8.
+ InvalidQuery,
+ /// An advertising or analytics beacon from `tracking_beacons.txt`. Nobody sees the one-pixel
+ /// image, and a fetch of it reports a conversion or a visit to the network that serves it.
+ TrackingBeacon,
+}
+
+impl Decline {
+ /// True for a URL the policy refuses because nobody wants it fetched, not because it is
+ /// malformed or unsafe. A consumer that reads jobs from a queue drops only that job for such a
+ /// decline, and rejects the whole record for every other one.
+ pub fn is_unwanted(self) -> bool {
+ matches!(self, Decline::TrackingBeacon)
+ }
+
+ /// The metric label. Stable, because a dashboard and an alert both key on it.
+ pub fn label(self) -> &'static str {
+ match self {
+ Decline::TooLong => "too_long",
+ Decline::NotAbsolute => "not_absolute",
+ Decline::BadScheme => "bad_scheme",
+ Decline::BadPort => "bad_port",
+ Decline::NoHost => "no_host",
+ Decline::NonPublicHost => "non_public_host",
+ Decline::Credential => "credential",
+ Decline::InvalidQuery => "invalid_query",
+ Decline::TrackingBeacon => "tracking_beacon",
+ }
+ }
+}
+
+/// Canonicalize a remote image URL into its fetch and dedup forms, or say why it was refused.
+pub fn canonicalize(raw: &str) -> Option<CanonicalUrl> {
+ try_canonicalize(raw).ok()
+}
+
+pub fn try_canonicalize(raw: &str) -> Result<CanonicalUrl, Decline> {
+ if raw.len() > MAX_URL_LEN {
+ return Err(Decline::TooLong);
+ }
+ let mut url = Url::parse(raw).map_err(|_| Decline::NotAbsolute)?;
+ // The browser blocks a plain `http` image on an HTTPS page as mixed content, so it never
+ // rendered for the person we recorded, and a fetch puts the request on the wire in clear text
+ // from our egress addresses.
+ if url.scheme() != "https" {
+ return Err(Decline::BadScheme);
+ }
+ // A port the scheme does not own makes the fetcher a port prober: a page names any host and
+ // port, the connection leaves our egress addresses, and the outcome metric shows what answered.
+ // Too few images are served on other ports to be worth that.
+ //
+ // This check limits which service on a host we reach. `is_public_host` and the address check at
+ // request time limit which hosts we reach, because DNS for a name the attacker owns can point
+ // anywhere.
+ if url.port().is_some() {
+ return Err(Decline::BadPort);
+ }
+ if !url.username().is_empty() || url.password().is_some() {
+ return Err(Decline::Credential);
+ }
+ // `example.com.` and `example.com` name the same host, and the consumer compares the two as
+ // strings in more than one place. The dot comes off the URL as well as off the host, so
+ // everything downstream sees one spelling.
+ let host_str = url.host_str().ok_or(Decline::NoHost)?;
+ let host = host_str.strip_suffix('.').unwrap_or(host_str).to_string();
+ if !is_public_host(&host) {
+ return Err(Decline::NonPublicHost);
+ }
+ if host != host_str {
+ url.set_host(Some(&host)).map_err(|_| Decline::NoHost)?;
+ }
+ let lowercase_path = decoded_lowercase_path(&url)?;
+ if has_credential_query(&url)? || has_credential_path(&lowercase_path, &host) {
+ return Err(Decline::Credential);
+ }
+ if matches_beacon_list(&host, &collapse_slashes(&lowercase_path)) {
+ return Err(Decline::TrackingBeacon);
+ }
+
+ let original_query = original_query(raw);
+ url.set_fragment(None);
+ url.set_query(None);
+ let serialized_without_query = url.to_string();
+ let fetch = serialize_with_query(&serialized_without_query, original_query);
+ // Percent-encoding and IDNA can grow a URL, so the cap is re-checked on what we emit.
+ if fetch.len() > MAX_URL_LEN {
+ return Err(Decline::TooLong);
+ }
+
+ let resized_query = shopify::normalize_image_size(&mut url, original_query);
+ let dedup_query = remove_volatile_params(resized_query.as_deref().or(original_query))?;
+ let dedup = serialize_with_query(url.as_str(), dedup_query.as_deref());
+ if dedup.len() > MAX_URL_LEN {
+ return Err(Decline::TooLong);
+ }
+
+ Ok(CanonicalUrl {
+ fetch,
+ dedup,
+ domain: politeness_key(&host),
+ host,
+ })
+}
+
+fn original_query(raw: &str) -> Option<&str> {
+ let before_fragment = raw.split_once('#').map_or(raw, |(before, _)| before);
+ before_fragment.split_once('?').map(|(_, query)| query)
+}
+
+fn serialize_with_query(serialized_without_query: &str, query: Option<&str>) -> String {
+ let mut serialized = serialized_without_query.to_string();
+ if let Some(query) = query {
+ serialized.push('?');
+ serialized.push_str(query);
+ }
+ serialized
+}
+
+fn has_credential_query(url: &Url) -> Result<bool, Decline> {
+ let Some(raw_query) = url.query() else {
+ return Ok(false);
+ };
+ for raw_pair in raw_query.split('&') {
+ let raw_name = raw_pair.split_once('=').map_or(raw_pair, |(name, _)| name);
+ if !has_valid_percent_encoding(raw_name) {
+ return Err(Decline::InvalidQuery);
+ }
+ let form_name = raw_name.replace('+', " ");
+ percent_decode_str(&form_name)
+ .decode_utf8()
+ .map_err(|_| Decline::InvalidQuery)?;
+ }
+ Ok(url.query_pairs().any(|(name, value)| {
+ CREDENTIAL_PARAMS
+ .iter()
+ .any(|credential| credential.eq_ignore_ascii_case(&name))
+ || (name.eq_ignore_ascii_case("s") && value.chars().count() == 32)
+ }))
+}
+
+fn has_valid_percent_encoding(value: &str) -> bool {
+ let bytes = value.as_bytes();
+ let mut index = 0;
+ while index < bytes.len() {
+ if bytes[index] == b'%' {
+ if index + 2 >= bytes.len()
+ || !bytes[index + 1].is_ascii_hexdigit()
+ || !bytes[index + 2].is_ascii_hexdigit()
+ {
+ return false;
+ }
+ index += 3;
+ } else {
+ index += 1;
+ }
+ }
+ true
+}
+
+/// The request path with percent-encoding removed and ASCII lowercased. A path that cannot be
+/// decoded is refused as a credential, because the lane cannot prove it carries none.
+fn decoded_lowercase_path(url: &Url) -> Result<String, Decline> {
+ if !has_valid_percent_encoding(url.path()) {
+ return Err(Decline::Credential);
+ }
+ Ok(percent_decode_str(url.path())
+ .decode_utf8()
+ .map_err(|_| Decline::Credential)?
+ .to_ascii_lowercase())
+}
+
+/// `path` is the decoded lowercase path from [`decoded_lowercase_path`].
+fn has_credential_path(path: &str, host: &str) -> bool {
+ let segments: Vec<&str> = path.split('/').collect();
+ let first_segment_has_bunny_token = segments
+ .get(1)
+ .and_then(|segment| segment.strip_prefix("bcdn_token="))
+ .and_then(|value| value.split('&').next())
+ .is_some_and(|token| !token.is_empty());
+ let has_oracle_token = host.starts_with("objectstorage.")
+ && host.ends_with(".oraclecloud.com")
+ && host.split('.').count() == 4
+ && segments.get(1) == Some(&"p")
+ && segments.get(2).is_some_and(|token| !token.is_empty())
+ && segments.get(3) == Some(&"n");
+ let has_cloudinary_signature = segments.iter().any(|segment| {
+ segment
+ .strip_prefix("s--")
+ .and_then(|value| value.strip_suffix("--"))
+ .is_some_and(|token| !token.is_empty())
+ });
+ let has_supabase_signature = path.contains("/storage/v1/object/sign/")
+ || path.contains("/storage/v1/render/image/sign/");
+ let has_session_token = segments.iter().any(|segment| {
+ segment
+ .split_once(";jsessionid=")
+ .and_then(|(_, value)| value.split(';').next())
+ .is_some_and(|token| !token.is_empty())
+ });
+
+ first_segment_has_bunny_token
+ || has_oracle_token
+ || has_cloudinary_signature
+ || has_supabase_signature
+ || has_session_token
+}
+
+fn remove_volatile_params(raw_query: Option<&str>) -> Result<Option<String>, Decline> {
+ let Some(raw_query) = raw_query else {
+ return Ok(None);
+ };
+ let pairs: Vec<(&str, String)> = raw_query
+ .split('&')
+ .map(|raw_pair| {
+ let raw_name = raw_pair.split_once('=').map_or(raw_pair, |(name, _)| name);
+ if !has_valid_percent_encoding(raw_name) {
+ return Err(Decline::InvalidQuery);
+ }
+ let decoded_name = percent_decode_str(raw_name)
+ .decode_utf8()
+ .map_err(|_| Decline::InvalidQuery)?
+ .into_owned();
+ Ok((raw_pair, decoded_name))
+ })
+ .collect::<Result<_, _>>()?;
+ let names_on_this_url: HashSet<String> = pairs
+ .iter()
+ .map(|(_, name)| name.to_ascii_lowercase())
+ .collect();
+ let kept: Vec<&str> = pairs
+ .iter()
+ .filter(|(_, name)| !is_volatile(name, &names_on_this_url))
+ .map(|(raw_pair, _)| *raw_pair)
+ .collect();
+
+ if kept.is_empty() {
+ return Ok(None);
+ }
+ Ok(Some(kept.join("&")))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn canonicalize_rejects_what_we_will_not_fetch() {
+ for raw in [
+ "ftp://example.com/a.png",
+ "data:image/png;base64,aGk=",
+ "/relative/a.png",
+ "not a url",
+ "//protocol-relative.example.com/a.png",
+ ] {
+ assert!(canonicalize(raw).is_none(), "{raw} should not canonicalize");
+ }
+ let long = format!("https://example.com/{}", "a".repeat(MAX_URL_LEN));
+ assert!(canonicalize(&long).is_none());
+ }
+
+ #[test]
+ fn tracking_beacons_are_refused_by_host_pattern_and_path_prefix() {
+ for raw in [
+ "https://analytics.twitter.com/i/adsct?txn_id=abc&p_id=Twitter",
+ "https://ANALYTICS.twitter.com/I/ADSCT",
+ "https://analytics.twitter.com/i/%61dsct",
+ "https://analytics.twitter.com/i//adsct",
+ "https://www.facebook.com//tr?id=1",
+ "https://www.facebook.com/tr?id=1&ev=PageView",
+ "https://bat.bing.com/action/0?ti=123&Ver=2",
+ "https://123456.fls.doubleclick.net/activityi;src=1;type=a",
+ "https://metrics.example.com/b/ss/rsid/1/JS-2.0/s123",
+ "https://ct.pinterest.com/v3/?tid=1&noscript=1",
+ ] {
+ assert_eq!(try_canonicalize(raw), Err(Decline::TrackingBeacon), "{raw}");
+ }
+ for raw in [
+ "https://pbs.twimg.com/media/abc.jpg",
+ "https://analytics.twitter.com/transparency/logo.png",
+ "https://notanalytics.twitter.com/i/adsct",
+ "https://fls.doubleclick.net/activityi",
+ "https://example.com/b/ss.png",
+ "https://www.facebook.com/trending/x.png",
+ "https://bat.bing.com/actions/x.png",
+ "https://example.com/matomo.php.png",
+ "https://cdn.shopify.com/s/files/1/photo.png",
+ "https://d111.cloudfront.net/photo.png",
+ ] {
+ assert!(canonicalize(raw).is_some(), "{raw} is not a beacon");
+ }
+ assert_eq!(
+ try_canonicalize("https://analytics.twitter.com/i/adsct?token=abc"),
+ Err(Decline::Credential),
+ "a credential is refused before the beacon list is consulted"
+ );
+ }
+
+ #[test]
+ fn the_beacon_list_parses_and_refuses_a_malformed_entry() {
+ assert!(!TRACKING_BEACON_PATTERNS.is_empty());
+ for malformed in [
+ "no-slash",
+ "/path-only",
+ "*x.example.com/",
+ "a.*.example.com/",
+ "*.example.com",
+ "*/",
+ "https://host.example.com/path",
+ "host.example.com:443/path",
+ "host.example.com/path # note",
+ "host example.com/path",
+ "host.example.com./path",
+ "localhost/path",
+ "host.example.com/path?x=1",
+ "host.example.com/%61",
+ ] {
+ assert!(
+ parse_beacon_list(malformed).is_err(),
+ "{malformed:?} must not parse"
+ );
+ }
+ }
+
+ #[test]
+ fn canonicalize_normalizes_and_removes_the_fragment() {
+ let c = canonicalize("HTTPS://Example.COM:443/A.png#frag").unwrap();
+ assert_eq!(c.fetch, "https://example.com/A.png");
+ assert_eq!(c.host, "example.com");
+ }
+
+ #[test]
+ fn known_query_credentials_are_refused_case_insensitively() {
+ for name in CREDENTIAL_PARAMS {
+ let raw = format!(
+ "https://cdn.example.com/a.png?{}=",
+ name.to_ascii_uppercase()
+ );
+ assert_eq!(try_canonicalize(&raw), Err(Decline::Credential), "{name}");
+ }
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?X-Amz-%53ignature=value"),
+ Err(Decline::Credential)
+ );
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?safe=1&safe=2&TOKEN="),
+ Err(Decline::Credential)
+ );
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?s=0123456789abcdef0123456789abcdef"),
+ Err(Decline::Credential)
+ );
+ assert!(canonicalize("https://cdn.example.com/a.png?s=200").is_some());
+ }
+
+ #[test]
+ fn credential_path_patterns_are_refused_case_insensitively() {
+ for raw in [
+ "https://cdn.example.com/BCDN_TOKEN=value/image.png",
+ "https://objectstorage.region.oraclecloud.com/P/value/N/image.png",
+ "https://cdn.example.com/S--value--/image.png",
+ "https://cdn.example.com/STORAGE/V1/OBJECT/SIGN/value",
+ "https://cdn.example.com/storage/v1/render/image/sign/value",
+ "https://cdn.example.com/images;JSESSIONID=value/a.png",
+ ] {
+ assert_eq!(try_canonicalize(raw), Err(Decline::Credential), "{raw}");
+ }
+ }
+
+ #[test]
+ fn percent_encoded_credential_path_patterns_are_refused() {
+ for raw in [
+ "https://cdn.example.com/BCDN%5fTOKEN=value/image.png",
+ "https://objectstorage.region.oraclecloud.com/%70/value/%6e/image.png",
+ "https://cdn.example.com/S%2d%2dvalue%2d%2d/image.png",
+ "https://cdn.example.com/storage/v1/object/s%69gn/value",
+ "https://cdn.example.com/storage/v1/render/image/s%69gn/value",
+ "https://cdn.example.com/images%3bJSESSIONID=value/a.png",
+ ] {
+ assert_eq!(try_canonicalize(raw), Err(Decline::Credential), "{raw}");
+ }
+ }
+
+ #[test]
+ fn userinfo_and_invalid_query_names_are_refused() {
+ assert_eq!(
+ try_canonicalize("https://user:[email protected]/a.png"),
+ Err(Decline::Credential)
+ );
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?bad%FF=value"),
+ Err(Decline::InvalidQuery)
+ );
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?bad%ZZ=value"),
+ Err(Decline::InvalidQuery)
+ );
+ }
+
+ #[test]
+ fn signing_metadata_without_a_credential_is_preserved() {
+ let raw = "https://cdn.example.com/a.png?X-Amz-Algorithm=v4&X-Amz-Date=20260810T000000Z&X-Amz-Expires=60";
+ let canonical = canonicalize(raw).unwrap();
+ assert!(canonical.fetch.contains("X-Amz-Algorithm=v4"));
+ assert!(canonical.dedup.contains("X-Amz-Algorithm=v4"));
+ }
+
+ #[test]
+ fn volatile_query_fields_stay_on_the_fetch_url_and_leave_the_global_ref() {
+ let canonical = canonicalize(
+ "https://cdn.example.com/a.png?w=200&%63b=first&CB=second&no%63ache=third&RND=fourth",
+ )
+ .unwrap();
+
+ assert_eq!(
+ canonical.fetch,
+ "https://cdn.example.com/a.png?w=200&%63b=first&CB=second&no%63ache=third&RND=fourth"
+ );
+ assert_eq!(canonical.dedup, "https://cdn.example.com/a.png?w=200");
+ }
+
+ #[test]
+ fn shopify_resize_variants_share_an_identity_and_keep_their_fetch_urls() {
+ for (first, second, expected) in [
+ (
+ "photo.jpg?v=123&width=300",
+ "photo.jpg?v=123&width=800",
+ "photo.jpg?v=123&width=1024",
+ ),
+ (
+ "photo.jpg?height=100",
+ "photo.jpg?height=200",
+ "photo.jpg?height=1024",
+ ),
+ (
+ "photo_64x64.jpg?v=123",
+ "photo_128x128.jpg?v=123",
+ "photo_1024x1024.jpg?v=123",
+ ),
+ ("photo_480x.jpg", "[email protected]", "photo_1024x.jpg"),
+ ("photo_x480.jpg", "photo_x960.jpg", "photo_x1024.jpg"),
+ ("photo_small.jpg", "photo_large.jpg", "photo_1024x1024.jpg"),
+ (
+ "photo_300x200.png",
+ "photo_600x400.png",
+ "photo_1023x682.png",
+ ),
+ ] {
+ for prefix in [
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/",
+ "https://cdn.shopify.com/s/files/1/0000/0001/products/",
+ "https://cdn.shopify.com/s/files/1/0000/0001/collections/",
+ "https://example-store.myshopify.com/cdn/shop/files/",
+ "https://example-store.myshopify.com/cdn/shop/products/",
+ "https://example-store.myshopify.com/cdn/shop/collections/",
+ ] {
+ let first_url = format!("{prefix}{first}");
+ let second_url = format!("{prefix}{second}");
+ let first = canonicalize(&first_url).unwrap();
+ let second = canonicalize(&second_url).unwrap();
+ assert_eq!(first.fetch, first_url);
+ assert_eq!(second.fetch, second_url);
+ assert_eq!(first.dedup, format!("{prefix}{expected}"));
+ assert_eq!(first.dedup, second.dedup);
+ assert_eq!(canonicalize(&first.fetch).unwrap(), first);
+ }
+ }
+ }
+
+ #[test]
+ fn shopify_paths_on_unknown_hosts_preserve_distinct_resources() {
+ for prefix in [
+ "https://store.example.com/cdn/shop/files/",
+ "https://store.example.com/cdn/shop/products/",
+ "https://store.example.com/cdn/shop/collections/",
+ "https://notmyshopify.com/cdn/shop/files/",
+ "https://example-store.myshopify.com.example.com/cdn/shop/files/",
+ "https://nested.example-store.myshopify.com/cdn/shop/files/",
+ "https://myshopify.com/cdn/shop/files/",
+ "https://cdn.shopify.com.example.com/s/files/1/0000/0001/files/",
+ ] {
+ for suffix in [
+ "photo.jpg?width=300",
+ "photo.jpg?width=800",
+ "photo.jpg?height=100",
+ "photo.jpg?height=200",
+ "photo_480x.jpg",
+ "photo_960x.jpg",
+ ] {
+ let raw = format!("{prefix}{suffix}");
+ let canonical = canonicalize(&raw).unwrap();
+ assert_eq!(canonical.fetch, raw);
+ assert_eq!(canonical.dedup, raw);
+ }
+ }
+ }
+
+ #[test]
+ fn shopify_resize_normalization_preserves_content_boundaries() {
+ let prefix = "https://cdn.shopify.com/s/files/1/0000/0001/files/";
+ for (first, second) in [
+ ("photo.jpg?v=1&width=300", "photo.jpg?v=2&width=300"),
+ (
+ "photo_300x200_crop_center.jpg",
+ "photo_200x300_crop_center.jpg",
+ ),
+ (
+ "photo_300x300_crop_top.jpg",
+ "photo_300x300_crop_bottom.jpg",
+ ),
+ (
+ "photo.jpg?width=300&height=200",
+ "photo.jpg?width=200&height=300",
+ ),
+ (
+ "photo.jpg?width=300&height=200&crop=top",
+ "photo.jpg?width=300&height=200&crop=bottom",
+ ),
+ ("photo.jpg?width=300", "other.jpg?width=300"),
+ ] {
+ assert_ne!(
+ canonicalize(&format!("{prefix}{first}")).unwrap().dedup,
+ canonicalize(&format!("{prefix}{second}")).unwrap().dedup
+ );
+ }
+ for raw in [
+ "https://example.com/photo.jpg?width=300&height=200&size=small",
+ "https://example.com/photo_480x.jpg",
+ "https://cdn.shopify.com/other/photo.jpg?width=300",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&width=400",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=0",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=999999999999999999999",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&crop=region&crop_width=100",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&height=200",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&height=200&crop=center",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_64x64_crop_center.jpg",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo.jpg?width=300&size=small",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_300x200.jpg?width=100",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_350x350_banner.jpg",
+ "https://cdn.shopify.com/s/files/1/0000/0001/files/photo_480px.jpg",
+ ] {
+ let canonical = canonicalize(raw).unwrap();
+ assert_eq!(canonical.fetch, raw);
+ assert_eq!(canonical.dedup, raw);
+ }
+ }
+
+ #[test]
+ fn fetch_and_retained_dedup_query_bytes_are_never_rebuilt() {
+ let raw = "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f&cb=drop#fragment";
+ let canonical = canonicalize(raw).unwrap();
+
+ assert_eq!(
+ canonical.fetch,
+ "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f&cb=drop"
+ );
+ assert_eq!(
+ canonical.dedup,
+ "https://cdn.example.com/a.png?flag&empty=&plus=a+b&space=a%20b&bytes=%FF&slash=%2f"
+ );
+ }
+
+ #[test]
+ fn distinct_raw_nonvolatile_queries_keep_distinct_global_refs() {
+ let bare = canonicalize("https://cdn.example.com/a.png?flag").unwrap();
+ let empty = canonicalize("https://cdn.example.com/a.png?flag=").unwrap();
+ let plus = canonicalize("https://cdn.example.com/a.png?q=a+b").unwrap();
+ let encoded_space = canonicalize("https://cdn.example.com/a.png?q=a%20b").unwrap();
+
+ assert_ne!(bare.dedup, empty.dedup);
+ assert_ne!(plus.dedup, encoded_space.dedup);
+ }
+
+ #[test]
+ fn meta_query_fields_are_volatile_only_with_their_marker() {
+ let without_marker =
+ canonicalize("https://cdn.example.com/a.png?stp=first&ccb=second").unwrap();
+ assert_eq!(
+ without_marker.dedup,
+ "https://cdn.example.com/a.png?stp=first&ccb=second"
+ );
+
+ let with_marker = canonicalize(
+ "https://cdn.example.com/a.png?keep=1&_nc_%6Fhc=a&_NC_HT=b&ccb=c&oe=d&oh=e&stp=f",
+ )
+ .unwrap();
+ assert_eq!(with_marker.dedup, "https://cdn.example.com/a.png?keep=1");
+ }
+
+ #[test]
+ fn credentials_are_refused_before_volatile_query_fields_are_removed() {
+ assert_eq!(
+ try_canonicalize("https://cdn.example.com/a.png?cb=first&TOKEN=secret&cb=second"),
+ Err(Decline::Credential)
+ );
+ }
+
+ #[test]
+ fn only_https_on_its_own_port_is_collected() {
+ assert_eq!(canonicalize("https://cdn.example.com:11211/a.png"), None);
+ assert_eq!(canonicalize("https://cdn.example.com:8443/a.png"), None);
+ assert_eq!(canonicalize("http://cdn.example.com/a.png"), None);
+ assert_eq!(canonicalize("http://cdn.example.com:80/a.png"), None);
+ // The parser normalizes the default port away, so `url.port()` is None and `:443` passes.
+ assert!(canonicalize("https://cdn.example.com:443/a.png").is_some());
+ assert!(canonicalize("https://cdn.example.com/a.png").is_some());
+ }
+
+ #[test]
+ fn the_politeness_key_is_the_operator_not_the_dns_label() {
+ // A CDN that shards over numbered subdomains must share one budget.
+ assert_eq!(politeness_key("img1.cdn.example.com"), "example.com");
+ assert_eq!(politeness_key("img8.cdn.example.com"), "example.com");
+ assert_eq!(politeness_key("example.com"), "example.com");
+ }
+
+ #[test]
+ fn a_multi_tenant_host_keeps_its_tenants_apart() {
+ // The private section of the public suffix list is what makes this correct. Without it,
+ // every CloudFront distribution on the internet would share one budget and one partition.
+ assert_eq!(politeness_key("d111.cloudfront.net"), "d111.cloudfront.net");
+ assert_eq!(
+ politeness_key("bucket.s3.amazonaws.com"),
+ "bucket.s3.amazonaws.com"
+ );
+ assert_eq!(politeness_key("user.github.io"), "user.github.io");
+ // The app-hosting case: a tenant subdomain is its own operator for our purposes.
+ assert_eq!(politeness_key("myapp.vercel.app"), "myapp.vercel.app");
+ assert_eq!(politeness_key("site.netlify.app"), "site.netlify.app");
+ assert_eq!(politeness_key("worker.workers.dev"), "worker.workers.dev");
+ }
+
+ #[test]
+ fn a_fully_qualified_host_keys_the_same_as_the_bare_one() {
+ assert_eq!(politeness_key("example.com."), "example.com");
+ assert_eq!(politeness_key("img1.cdn.example.com."), "example.com");
+ assert_eq!(politeness_key("user.github.io."), "user.github.io");
+ }
+
+ #[test]
+ fn an_ip_literal_is_its_own_operator() {
+ assert_eq!(politeness_key("203.0.113.7"), "203.0.113.7");
+ assert_eq!(politeness_key("[2606:4700::1111]"), "[2606:4700::1111]");
+ }
+
+ #[test]
+ fn canonicalize_carries_the_politeness_key() {
+ let c = canonicalize("https://img3.cdn.example.co.uk/a.png").unwrap();
+ assert_eq!(c.host, "img3.cdn.example.co.uk");
+ // A multi-label public suffix, which is why this cannot be "the last two labels".
+ assert_eq!(c.domain, "example.co.uk");
+ }
+
+ #[test]
+ fn a_gravatar_size_is_not_stripped() {
+ let big = canonicalize("https://www.gravatar.com/avatar/abc?s=200").unwrap();
+ let small = canonicalize("https://www.gravatar.com/avatar/abc?s=48").unwrap();
+ assert_ne!(
+ big.dedup, small.dedup,
+ "two avatar sizes are two images and must not share a ref"
+ );
+ }
+
+ #[test]
+ fn a_non_public_host_is_never_collected() {
+ // The URL set comes from page content, and the fetch lane runs inside our network. Every
+ // one is https, or the scheme rule would refuse it before the host rule was reached.
+ for raw in [
+ "https://169.254.169.254/latest/meta-data/iam/security-credentials/",
+ "https://localhost/admin/export.png",
+ "https://127.0.0.1/i.png",
+ "https://10.0.0.5/i.png",
+ "https://192.168.1.1/i.png",
+ "https://172.16.0.1/i.png",
+ "https://[::1]/i.png",
+ "https://[fd00::1]/i.png",
+ "https://metadata.internal/i.png",
+ "https://buildserver/i.png",
+ // A trailing dot makes a name fully qualified and resolves the same way. It used to
+ // walk past the name list, because the label after the final dot is empty.
+ "https://localhost./i.png",
+ "https://metadata.internal./i.png",
+ "https://LOCALHOST./i.png",
+ // IPv6 offers several ways to write an IPv4 address. Each one used to skip the IPv4
+ // rules entirely.
+ "https://[::ffff:0.0.0.0]/i.png",
+ "https://[::ffff:127.0.0.1]/i.png",
+ "https://[::ffff:10.0.0.5]/i.png",
+ "https://[::ffff:100.64.0.1]/i.png",
+ "https://[::127.0.0.1]/i.png",
+ "https://[2002:7f00:1::]/i.png",
+ "https://[64:ff9b::7f00:1]/i.png",
+ "https://[ff02::1]/i.png",
+ // Ranges we would never legitimately fetch from.
+ "https://224.0.0.1/i.png",
+ "https://240.0.0.1/i.png",
+ "https://198.18.0.1/i.png",
+ "https://192.0.0.1/i.png",
+ "https://0.0.0.0/i.png",
+ ] {
+ assert!(canonicalize(raw).is_none(), "{raw} must not be collected");
+ }
+ assert!(canonicalize("https://cdn.example.com/i.png").is_some());
+ // A public name with a trailing dot is still public, so the fix must not over-reject.
+ assert!(canonicalize("https://cdn.example.com./i.png").is_some());
+ assert!(canonicalize("https://[2606:4700::1111]/i.png").is_none());
+ assert!(canonicalize("https://8.8.8.8/i.png").is_none());
+ }
+
+ #[test]
+ fn a_fully_qualified_host_survives_the_whole_lane() {
+ let c = canonicalize("https://cdn.example.com./i.png").expect("collected");
+ // The consumer compares `new URL(fetch).hostname` with `host`. A dot on one side only
+ // makes every fully qualified host fail that comparison.
+ assert_eq!(c.host, "cdn.example.com");
+ assert_eq!(c.fetch, "https://cdn.example.com/i.png");
+ }
+
+ #[test]
+ fn a_cache_buster_does_not_identify_a_distinct_resource() {
+ let plain = canonicalize("https://cdn.example.com/a.png?a=hello%20world&b=2").unwrap();
+ let cache_busted =
+ canonicalize("https://cdn.example.com/a.png?a=hello%20world&b=2&cb=zz").unwrap();
+ assert_eq!(plain.dedup, cache_busted.dedup);
+ }
+}
diff --git a/rust/ai-research/replay-core-v4/src/url_policy/shopify.rs b/rust/ai-research/replay-core-v4/src/url_policy/shopify.rs
new file mode 100644
index 000000000000..172982c343c8
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/url_policy/shopify.rs
@@ -0,0 +1,160 @@
+use percent_encoding::percent_decode_str;
+use url::Url;
+
+const RESIZE_LONG_SIDE: u32 = 1024;
+const MAX_SHOPIFY_DIMENSION: u32 = 5760;
+type Dimensions = (Option<u32>, Option<u32>);
+
+pub(super) fn normalize_image_size(url: &mut Url, query: Option<&str>) -> Option<String> {
+ if !is_shopify_image(url) || url.path().contains("_crop_") {
+ return None;
+ }
+ let fields: Vec<&str> = query.map_or_else(Vec::new, |query| query.split('&').collect());
+ let mut width = None;
+ let mut height = None;
+ for field in &fields {
+ let (name, value) = field.split_once('=').unwrap_or((field, ""));
+ let name = percent_decode_str(name).decode_utf8().ok()?;
+ match name.as_ref() {
+ "width" if width.is_none() => width = Some(dimension(value)?),
+ "height" if height.is_none() => height = Some(dimension(value)?),
+ "v" | "format" | "cb" | "nocache" | "rnd" => {}
+ _ => return None,
+ }
+ }
+ let (stem, extension) = url.path().rsplit_once('.')?;
+ let legacy_size = legacy_size(stem);
+ if let Some((base, dimensions)) = legacy_size {
+ if width.is_some() || height.is_some() {
+ return None;
+ }
+ let (width, height) = normalize_dimensions(dimensions.0, dimensions.1)?;
+ let width = width.map_or_else(String::new, |value| value.to_string());
+ let height = height.map_or_else(String::new, |value| value.to_string());
+ let path = format!("{base}_{width}x{height}.{extension}");
+ url.set_path(&path);
+ return None;
+ }
+ // Two dimensions can request a crop, whose result also depends on the original image bounds.
+ if width.is_some() && height.is_some() {
+ return None;
+ }
+ let (width, height) = normalize_dimensions(width, height)?;
+ let fields: Vec<String> = fields
+ .into_iter()
+ .map(|field| {
+ let (name, _) = field.split_once('=').unwrap_or((field, ""));
+ match percent_decode_str(name).decode_utf8().ok().as_deref() {
+ Some("width") => format!("{name}={}", width.unwrap()),
+ Some("height") => format!("{name}={}", height.unwrap()),
+ _ => field.to_string(),
+ }
+ })
+ .collect();
+ Some(fields.join("&"))
+}
+
+fn is_shopify_image(url: &Url) -> bool {
+ let path = url.path();
+ let Some((_, extension)) = path.rsplit_once('.') else {
+ return false;
+ };
+ if !matches!(extension, "jpg" | "jpeg" | "png" | "webp" | "avif" | "gif") {
+ return false;
+ }
+ if url
+ .host_str()
+ .and_then(|host| host.strip_suffix(".myshopify.com"))
+ .is_some_and(|store| !store.is_empty() && !store.contains('.'))
+ {
+ return [
+ "/cdn/shop/files/",
+ "/cdn/shop/products/",
+ "/cdn/shop/collections/",
+ ]
+ .iter()
+ .any(|prefix| {
+ path.strip_prefix(prefix)
+ .is_some_and(|file| !file.contains('/'))
+ });
+ }
+ if url.host_str() != Some("cdn.shopify.com") {
+ return false;
+ }
+ let Some(path) = path.strip_prefix("/s/files/") else {
+ return false;
+ };
+ let segments: Vec<&str> = path.split('/').collect();
+ segments.len() >= 5
+ && matches!(
+ segments[segments.len() - 2],
+ "files" | "products" | "collections"
+ )
+ && segments[..segments.len() - 2]
+ .iter()
+ .all(|segment| !segment.is_empty() && segment.bytes().all(|byte| byte.is_ascii_digit()))
+}
+
+fn dimension(value: &str) -> Option<u32> {
+ if value.is_empty() || !value.bytes().all(|byte| byte.is_ascii_digit()) {
+ return None;
+ }
+ value
+ .parse()
+ .ok()
+ .filter(|value| (1..=MAX_SHOPIFY_DIMENSION).contains(value))
+}
+
+fn legacy_size(stem: &str) -> Option<(&str, Dimensions)> {
+ let stem = stem
+ .strip_suffix("@2x")
+ .or_else(|| stem.strip_suffix("@3x"))
+ .unwrap_or(stem);
+ let (base, size) = stem.rsplit_once('_')?;
+ let named = match size {
+ "pico" => Some(16),
+ "icon" => Some(32),
+ "thumb" => Some(50),
+ "small" => Some(100),
+ "compact" => Some(160),
+ "medium" => Some(240),
+ "large" => Some(480),
+ "grande" => Some(600),
+ _ => None,
+ };
+ let dimensions = if let Some(side) = named {
+ (Some(side), Some(side))
+ } else {
+ let (width, height) = size.split_once('x')?;
+ (
+ if width.is_empty() {
+ None
+ } else {
+ Some(dimension(width)?)
+ },
+ if height.is_empty() {
+ None
+ } else {
+ Some(dimension(height)?)
+ },
+ )
+ };
+ Some((base, dimensions))
+}
+
+fn normalize_dimensions(width: Option<u32>, height: Option<u32>) -> Option<Dimensions> {
+ match (width, height) {
+ (Some(width), Some(height)) => {
+ let (mut a, mut b) = (width, height);
+ while b != 0 {
+ (a, b) = (b, a % b);
+ }
+ let (width, height) = (width / a, height / a);
+ let scale = RESIZE_LONG_SIDE / width.max(height);
+ (scale > 0).then_some((Some(width * scale), Some(height * scale)))
+ }
+ (Some(_), None) => Some((Some(RESIZE_LONG_SIDE), None)),
+ (None, Some(_)) => Some((None, Some(RESIZE_LONG_SIDE))),
+ (None, None) => None,
+ }
+}