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-recorder-v4): send remote image urls to the v4 fetcher (#117977)

Nicholas Waltz038d3e9b76c4
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5c20920b2140..fda74543d84a 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -11052,6 +11052,7 @@ name = "replay-recorder-v4"
version = "0.1.0"
dependencies = [
"aes-gcm",
+ "aho-corasick",
"arc-swap",
"arrow-array",
"arrow-schema",
@@ -11072,6 +11073,7 @@ dependencies = [
"envconfig",
"lifecycle",
"metrics",
+ "moka",
"parquet",
"rand 0.8.5",
"rdkafka",
@@ -11082,6 +11084,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
+ "url",
]
[[package]]
diff --git a/rust/ai-research/replay-core-v4/src/inspect/css.rs b/rust/ai-research/replay-core-v4/src/inspect/css.rs
new file mode 100644
index 000000000000..c0e07444d5c2
--- /dev/null
+++ b/rust/ai-research/replay-core-v4/src/inspect/css.rs
@@ -0,0 +1,428 @@
+//! Remote image URLs in CSS, found with the rules of v3 `css.rs`: the `url()` and the best `image-set()` candidate in the
+//! value of a property that shows an image. Custom properties and other properties do not count.
+
+/// Calls `found` with each image URL candidate in `css`: a `style` attribute, `<style>` text or `_cssText`, which v3
+/// reads the same way.
+pub fn image_urls(css: &str, found: &mut impl FnMut(&str)) {
+ for (start, end, collect) in declaration_value_ranges(css) {
+ if collect {
+ value_urls(&css[start..end], found);
+ }
+ }
+}
+
+pub fn declaration_image_urls(property: &str, value: &str, found: &mut impl FnMut(&str)) {
+ if is_image_property(property.trim()) {
+ value_urls(value, found);
+ }
+}
+
+/// The value ranges of the declarations in `css`, and whether each is an image property.
+fn declaration_value_ranges(css: &str) -> Vec<(usize, usize, bool)> {
+ let bytes = css.as_bytes();
+ let mut ranges: Vec<(usize, usize, bool)> = Vec::new();
+ // Where the text of the current declaration starts, after the whitespace that leads it.
+ let mut segment_start: Option<usize> = None;
+ let mut brace_depth = 0usize;
+ let mut paren_depth = 0usize;
+ let mut bracket_depth = 0usize;
+ let mut position = 0;
+ while position < bytes.len() {
+ if segment_start.is_none() && !bytes[position].is_ascii_whitespace() {
+ segment_start = Some(position);
+ }
+ if starts_with(bytes, position, b"/*") {
+ position = skip_comment(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ if bytes[position] == b'\\' {
+ position = skip_escape(bytes, position);
+ continue;
+ }
+ if matches!(bytes[position], b'\'' | b'"') {
+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ match bytes[position] {
+ b'(' => paren_depth += 1,
+ b')' => paren_depth = paren_depth.saturating_sub(1),
+ b'[' => bracket_depth += 1,
+ b']' => bracket_depth = bracket_depth.saturating_sub(1),
+ b'{' if paren_depth == 0 && bracket_depth == 0 => {
+ brace_depth += 1;
+ segment_start = None;
+ }
+ b'}' if paren_depth == 0 && bracket_depth == 0 => {
+ brace_depth = brace_depth.saturating_sub(1);
+ segment_start = None;
+ }
+ b';' if paren_depth == 0 && bracket_depth == 0 => segment_start = None,
+ // A colon in a custom property value, as in `--link: https://…`, is not a new declaration.
+ b':' if paren_depth == 0
+ && bracket_depth == 0
+ && ranges.last().is_none_or(|previous| position >= previous.1) =>
+ {
+ // Each colon trims only the whitespace before it, so a long selector list stays linear.
+ let property = css[segment_start.unwrap_or(position)..position].trim_end();
+ let image = is_image_property(property);
+ if image || property.starts_with("--") {
+ ranges.push((
+ position + 1,
+ declaration_end(bytes, position + 1, brace_depth),
+ image,
+ ));
+ }
+ }
+ _ => {}
+ }
+ position += 1;
+ }
+ ranges
+}
+
+fn declaration_end(bytes: &[u8], start: usize, brace_depth: usize) -> usize {
+ let mut position = start;
+ let mut paren_depth = 0usize;
+ let mut bracket_depth = 0usize;
+ while position < bytes.len() {
+ if starts_with(bytes, position, b"/*") {
+ position = skip_comment(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ if bytes[position] == b'\\' {
+ position = skip_escape(bytes, position);
+ continue;
+ }
+ if matches!(bytes[position], b'\'' | b'"') {
+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ match bytes[position] {
+ b'(' => paren_depth += 1,
+ b')' => paren_depth = paren_depth.saturating_sub(1),
+ b'[' => bracket_depth += 1,
+ b']' => bracket_depth = bracket_depth.saturating_sub(1),
+ b';' if paren_depth == 0 && bracket_depth == 0 => return position,
+ b'}' if paren_depth == 0 && bracket_depth == 0 && brace_depth > 0 => return position,
+ _ => {}
+ }
+ position += 1;
+ }
+ bytes.len()
+}
+
+/// The longest name [`is_image_property`] accepts, so that a longer text is not lowercased.
+const MAX_IMAGE_PROPERTY_LEN: usize = "-webkit-mask-box-image-source".len();
+
+fn is_image_property(property: &str) -> bool {
+ property.len() <= MAX_IMAGE_PROPERTY_LEN
+ && matches!(
+ property.to_ascii_lowercase().as_str(),
+ "background"
+ | "background-image"
+ | "border-image"
+ | "border-image-source"
+ | "content"
+ | "cursor"
+ | "list-style"
+ | "list-style-image"
+ | "mask"
+ | "mask-border"
+ | "mask-border-source"
+ | "mask-image"
+ | "shape-outside"
+ | "symbols"
+ | "-webkit-border-image"
+ | "-webkit-border-image-source"
+ | "-webkit-box-reflect"
+ | "-webkit-mask"
+ | "-webkit-mask-box-image"
+ | "-webkit-mask-box-image-source"
+ | "-webkit-mask-image"
+ )
+}
+
+fn value_urls(value: &str, found: &mut impl FnMut(&str)) {
+ let bytes = value.as_bytes();
+ let mut position = 0;
+ while position < bytes.len() {
+ if starts_with(bytes, position, b"/*") {
+ position = skip_comment(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ if bytes[position] == b'\\' {
+ position = skip_escape(bytes, position);
+ continue;
+ }
+ if matches!(bytes[position], b'\'' | b'"') {
+ position = skip_quoted(bytes, position).unwrap_or(bytes.len());
+ continue;
+ }
+ let image_set = if function_at(bytes, position, b"image-set") {
+ Some(b"image-set".len())
+ } else if function_at(bytes, position, b"-webkit-image-set") {
+ Some(b"-webkit-image-set".len())
+ } else {
+ None
+ };
+ if let Some(name_len) = image_set {
+ let open = position + name_len;
+ let Some(end) = matching_paren(bytes, open) else {
+ return;
+ };
+ if let Some(source) = select_image_set_candidate(&value[open + 1..end - 1]) {
+ collect(&source, found);
+ }
+ position = end;
+ continue;
+ }
+ if function_at(bytes, position, b"url") {
+ let (resume_at, source) = scan_url_function(value, position);
+ position = resume_at;
+ if let Some(source) = source {
+ collect(&source, found);
+ }
+ continue;
+ }
+ position += 1;
+ }
+}
+
+/// v3 collects neither a fragment nor a source with an escape in it.
+fn collect(source: &str, found: &mut impl FnMut(&str)) {
+ let source = source.trim();
+ if !source.starts_with('#') && !source.contains('\\') {
+ found(source);
+ }
+}
+
+fn scan_url_function(value: &str, start: usize) -> (usize, Option<String>) {
+ let bytes = value.as_bytes();
+ let Some(resume_at) = matching_paren(bytes, start + 3) else {
+ return (bytes.len(), None);
+ };
+ let contents_end = resume_at - 1;
+ let mut position = start + 4;
+ skip_whitespace(bytes, &mut position);
+ let source = if matches!(bytes.get(position), Some(b'\'' | b'"')) {
+ let content_start = position + 1;
+ let Some(end) = skip_quoted(bytes, position) else {
+ return (resume_at, None);
+ };
+ position = end;
+ skip_whitespace(bytes, &mut position);
+ if position != contents_end {
+ return (resume_at, None);
+ }
+ &value[content_start..end - 1]
+ } else {
+ &value[position..contents_end]
+ };
+ let source = source.trim();
+ (
+ resume_at,
+ (!source.is_empty() && !source.contains('\\')).then(|| source.to_owned()),
+ )
+}
+
+fn select_image_set_candidate(contents: &str) -> Option<String> {
+ let bytes = contents.as_bytes();
+ let mut best: Option<(f64, String)> = None;
+ let mut start = 0;
+ let mut position = 0;
+ let mut depth = 0usize;
+ while position < bytes.len() {
+ if bytes[position] == b'\\' {
+ position = skip_escape(bytes, position);
+ continue;
+ }
+ if starts_with(bytes, position, b"/*") {
+ position = skip_comment(bytes, position)?;
+ continue;
+ }
+ if matches!(bytes[position], b'\'' | b'"') {
+ position = skip_quoted(bytes, position)?;
+ continue;
+ }
+ match bytes[position] {
+ b'(' => depth += 1,
+ b')' => depth = depth.saturating_sub(1),
+ b',' if depth == 0 => {
+ keep_better_candidate(&mut best, &contents[start..position])?;
+ start = position + 1;
+ }
+ _ => {}
+ }
+ position += 1;
+ }
+ keep_better_candidate(&mut best, &contents[start..])?;
+ best.map(|(_, source)| source)
+}
+
+fn keep_better_candidate(best: &mut Option<(f64, String)>, candidate: &str) -> Option<()> {
+ let candidate = candidate.trim();
+ if candidate.is_empty() {
+ return None;
+ }
+ let (source, remainder) = parse_image_set_source(candidate)?;
+ let resolution = parse_resolution(remainder)?;
+ if best
+ .as_ref()
+ .is_none_or(|(best_resolution, _)| resolution > *best_resolution)
+ {
+ *best = Some((resolution, source));
+ }
+ Some(())
+}
+
+fn parse_image_set_source(candidate: &str) -> Option<(String, &str)> {
+ let bytes = candidate.as_bytes();
+ if function_at(bytes, 0, b"url") {
+ let (resume_at, source) = scan_url_function(candidate, 0);
+ return Some((source?, &candidate[resume_at..]));
+ }
+ if matches!(bytes.first(), Some(b'\'' | b'"')) {
+ let end = skip_quoted(bytes, 0)?;
+ let source = candidate[1..end - 1].to_owned();
+ if source.contains('\\') {
+ return None;
+ }
+ return Some((source, &candidate[end..]));
+ }
+ None
+}
+
+fn parse_resolution(remainder: &str) -> Option<f64> {
+ let mut resolution = None;
+ for token in remainder.split_ascii_whitespace() {
+ let parsed = if let Some(value) = token.strip_suffix("dppx") {
+ value.parse::<f64>().ok()
+ } else if let Some(value) = token.strip_suffix("dpi") {
+ value.parse::<f64>().ok().map(|value| value / 96.0)
+ } else if let Some(value) = token.strip_suffix("dpcm") {
+ value.parse::<f64>().ok().map(|value| value * 2.54 / 96.0)
+ } else if let Some(value) = token.strip_suffix('x') {
+ value.parse::<f64>().ok()
+ } else if token.starts_with("type(") {
+ continue;
+ } else {
+ return None;
+ };
+ if resolution.replace(parsed?).is_some() {
+ return None;
+ }
+ }
+ let value = resolution.unwrap_or(1.0);
+ (value.is_finite() && value > 0.0).then_some(value)
+}
+
+fn function_at(bytes: &[u8], start: usize, name: &[u8]) -> bool {
+ bytes
+ .get(start..start + name.len())
+ .is_some_and(|candidate| candidate.eq_ignore_ascii_case(name))
+ && bytes.get(start + name.len()) == Some(&b'(')
+ && (start == 0
+ || !matches!(bytes[start - 1], b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'_' | b'-'))
+}
+
+fn matching_paren(bytes: &[u8], open: usize) -> Option<usize> {
+ if bytes.get(open) != Some(&b'(') {
+ return None;
+ }
+ let mut position = open + 1;
+ let mut depth = 1usize;
+ while position < bytes.len() {
+ if starts_with(bytes, position, b"/*") {
+ position = skip_comment(bytes, position)?;
+ continue;
+ }
+ if bytes[position] == b'\\' {
+ position = skip_escape(bytes, position);
+ continue;
+ }
+ if matches!(bytes[position], b'\'' | b'"') {
+ position = skip_quoted(bytes, position)?;
+ continue;
+ }
+ match bytes[position] {
+ b'(' => depth += 1,
+ b')' => {
+ depth -= 1;
+ if depth == 0 {
+ return Some(position + 1);
+ }
+ }
+ _ => {}
+ }
+ position += 1;
+ }
+ None
+}
+
+fn skip_quoted(bytes: &[u8], start: usize) -> Option<usize> {
+ let quote = *bytes.get(start)?;
+ let mut position = start + 1;
+ while position < bytes.len() {
+ match bytes[position] {
+ b'\\' => position += 2,
+ value if value == quote => return Some(position + 1),
+ _ => position += 1,
+ }
+ }
+ None
+}
+
+/// The position after the escape at `start` and the character it escapes, so that an escaped quote, bracket or
+/// parenthesis does not count as one.
+fn skip_escape(bytes: &[u8], start: usize) -> usize {
+ let width = match bytes.get(start + 1) {
+ Some(0xf0..) => 4,
+ Some(0xe0..) => 3,
+ Some(0xc0..) => 2,
+ _ => 1,
+ };
+ (start + 1 + width).min(bytes.len())
+}
+
+fn skip_comment(bytes: &[u8], start: usize) -> Option<usize> {
+ let relative = bytes
+ .get(start + 2..)?
+ .windows(2)
+ .position(|pair| pair == b"*/")?;
+ Some(start + 2 + relative + 2)
+}
+
+fn skip_whitespace(bytes: &[u8], position: &mut usize) {
+ while bytes.get(*position).is_some_and(u8::is_ascii_whitespace) {
+ *position += 1;
+ }
+}
+
+fn starts_with(bytes: &[u8], start: usize, needle: &[u8]) -> bool {
+ bytes.get(start..start + needle.len()) == Some(needle)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn reads_past_escapes_outside_strings() {
+ // Tailwind escapes brackets, parentheses and quotes in its arbitrary value class names.
+ let css = r".bg-\[url\(\'\/hero\.png\'\)\]{background-image:url('/hero.png')}.a{background:url(https://cdn.example.com/a.png)}";
+ let mut found = Vec::new();
+ image_urls(css, &mut |url| found.push(url.to_owned()));
+ assert_eq!(found, ["/hero.png", "https://cdn.example.com/a.png"]);
+ }
+
+ #[test]
+ fn scans_a_long_selector_list_in_linear_time() {
+ let css = format!(
+ "{} a:hover {{ background: url(https://cdn.example.com/a.png) }}",
+ "a:hover, b:focus-visible,\n".repeat(50_000)
+ );
+ let mut found = Vec::new();
+ image_urls(&css, &mut |url| found.push(url.to_owned()));
+ assert_eq!(found, ["https://cdn.example.com/a.png"]);
+ }
+}
diff --git a/rust/ai-research/replay-core-v4/src/inspect/dom.rs b/rust/ai-research/replay-core-v4/src/inspect/dom.rs
index 472eba7ec8ed..f79788d476d9 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/dom.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/dom.rs
@@ -2,11 +2,17 @@
//! there. The replayer renders such a mutation wrongly or not at all.
use std::collections::{HashMap, HashSet};
+use std::ops::Range;
use crate::bytescan::{self as scan, Span};
+use crate::url_policy::MAX_URL_LEN;
-use super::events::{field, number};
-use super::rrweb::{FULL_SNAPSHOT, INCREMENTAL_SNAPSHOT, MUTATION};
+use super::css;
+use super::events::{field, fields, number, text};
+use super::rrweb::{
+ ADOPTED_STYLE_SHEET, FULL_SNAPSHOT, INCREMENTAL_SNAPSHOT, MUTATION, STYLE_DECLARATION,
+ STYLE_SHEET_RULE,
+};
use super::stats::BlockStats;
use crate::scan::cv::{self, Expansion};
use crate::scan::message::Event;
@@ -14,20 +20,286 @@ use crate::scan::tokens::{Token, Tokens};
/// Node ids tracked per window. A larger page stops orphan counting for the window and sets `node_cap_reached`.
pub const MAX_TRACKED_NODES: usize = 200_000;
+/// Remote image URLs kept per message, as the v3 collector caps URLs per message.
+pub const MAX_IMAGE_URLS: usize = 512;
+/// Attribute changes read per mutation, as many as the nodes tracked. A mutation with more drops its block, because
+/// the inspector does not name the URLs in the rest.
+pub const MAX_ATTRIBUTE_ITEMS: usize = MAX_TRACKED_NODES;
+/// The longest remote URL a block may hold in an image slot: four times the longest the fetcher takes.
+pub const MAX_REMOTE_URL_BYTES: usize = 8 * 1024;
+/// The distinct remote URLs in a block's image slots, and their bytes. The writer builds one matcher over them, and
+/// the build takes memory in proportion to their bytes.
+pub const MAX_BLOCK_REMOTE_URLS: usize = 10_000;
+pub const MAX_BLOCK_REMOTE_URL_BYTES: usize = 2 * 1024 * 1024;
+/// Windows tracked per session. A new window past this evicts the window used least recently.
+pub const MAX_WINDOWS: usize = 16;
+/// Evicted windows remembered, so that one that comes back is known to have lost its DOM.
+const MAX_EVICTED_WINDOWS: usize = 1024;
const TEXT_NODE: f64 = 3.0;
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+enum Tag {
+ #[default]
+ Other,
+ Img,
+ SvgImage,
+ Video,
+ Source,
+ Picture,
+ Style,
+ Link,
+ Iframe,
+ Canvas,
+}
+
+const TAGS: [(&str, Tag); 9] = [
+ ("img", Tag::Img),
+ ("image", Tag::SvgImage),
+ ("video", Tag::Video),
+ ("source", Tag::Source),
+ ("picture", Tag::Picture),
+ ("style", Tag::Style),
+ ("link", Tag::Link),
+ ("iframe", Tag::Iframe),
+ ("canvas", Tag::Canvas),
+];
+
+fn tag(bytes: &[u8], span: Span) -> Tag {
+ scan::unescape(bytes, span).map_or(Tag::Other, |name| {
+ TAGS.iter()
+ .find(|(known, _)| name.eq_ignore_ascii_case(known))
+ .map_or(Tag::Other, |&(_, tag)| tag)
+ })
+}
+
+/// An element whose attributes v3 fetches an image from (`is_fetchable_image_attr`). An attribute mutation does not
+/// name its element's tag, so the window keeps these.
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum Media {
+ Img {
+ visibility: Visibility,
+ },
+ SvgImage,
+ Video,
+ PictureSource,
+ /// A `picture`, so that a `source` added under it later is known to be a picture source.
+ Picture,
+}
+
+/// The remote image URLs of a hidden img, which v3 fetches once the img shows.
+#[derive(Clone, Default)]
+struct HiddenSources {
+ src: Option<String>,
+ rr_src: Option<String>,
+ srcset: Vec<String>,
+}
+
+impl HiddenSources {
+ fn read(bytes: &[u8], attributes: &Attributes) -> Self {
+ let mut sources = Self::default();
+ sources.update(bytes, attributes);
+ sources
+ }
+
+ fn update(&mut self, bytes: &[u8], attributes: &Attributes) {
+ let url =
+ |span: Span| text(bytes, Some(span)).and_then(|url| fetchable(&url).map(str::to_owned));
+ if let Some(span) = attributes.src {
+ self.src = url(span);
+ }
+ if let Some(span) = attributes.rr_src {
+ self.rr_src = url(span);
+ }
+ if let Some(span) = attributes.srcset {
+ self.srcset.clear();
+ if let Some(srcset) = text(bytes, Some(span)) {
+ // One message sends at most MAX_IMAGE_URLS URLs, so the img that shows needs no more.
+ srcset_urls(&srcset, &mut |url| {
+ if self.srcset.len() < MAX_IMAGE_URLS {
+ self.srcset.extend(fetchable(url).map(str::to_owned));
+ }
+ });
+ }
+ }
+ }
+
+ /// Whether the attributes set a source, which an update then changes.
+ fn changes(attributes: &Attributes) -> bool {
+ attributes.src.is_some() || attributes.rr_src.is_some() || attributes.srcset.is_some()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.src.is_none() && self.rr_src.is_none() && self.srcset.is_empty()
+ }
+
+ fn heap_bytes(&self) -> usize {
+ let string = |s: &Option<String>| s.as_ref().map_or(0, String::capacity);
+ string(&self.src)
+ + string(&self.rr_src)
+ + self.srcset.capacity() * std::mem::size_of::<String>()
+ + self.srcset.iter().map(String::capacity).sum::<usize>()
+ }
+
+ fn push_revealed(self, set: &Attributes, walk: &mut Walk) {
+ for (url, replaced) in [(self.src, set.src), (self.rr_src, set.rr_src)] {
+ if let Some(url) = url.filter(|_| replaced.is_none()) {
+ walk.push_url_text(&url);
+ }
+ }
+ if set.srcset.is_none() {
+ for url in &self.srcset {
+ walk.push_url_text(url);
+ }
+ }
+ }
+}
+
#[derive(Default)]
struct WindowDom {
- nodes: HashSet<i64>,
+ nodes: HashMap<i64, Option<i64>>,
+ /// The children of each node. A list keeps a node that moved or went away until the next compaction.
+ children: HashMap<i64, Vec<i64>>,
+ /// The summed capacity of the child lists, which can exceed their lengths.
+ child_capacity: usize,
+ stale_children: usize,
+ media: HashMap<i64, Media>,
+ hidden_sources: HashMap<i64, HiddenSources>,
+ hidden_source_bytes: usize,
+ /// The text nodes of `style` elements, whose text changes are CSS.
+ style_texts: HashSet<i64>,
has_snapshot: bool,
- cap_reached: bool,
+ /// Orphan counting stopped: the DOM outgrew the node cap, a snapshot did not decode, a node was too deep to walk,
+ /// or the window was evicted and came back.
+ unverifiable: bool,
+ last_used: u64,
+}
+
+/// Why the inspector stopped naming a block's remote image URLs. The writer replaces only the URLs it is given, so it
+/// drops the block.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UrlLimit {
+ UrlLength,
+ UrlCount,
+ UrlBytes,
+ AttributeItems,
+}
+
+impl UrlLimit {
+ /// The outcome of the dropped block in the recorder's metrics.
+ pub fn label(self) -> &'static str {
+ match self {
+ UrlLimit::UrlLength => "url_too_long",
+ UrlLimit::UrlCount => "too_many_urls",
+ UrlLimit::UrlBytes => "too_many_url_bytes",
+ UrlLimit::AttributeItems => "too_many_attribute_items",
+ }
+ }
+}
+
+/// Distinct remote image URLs within [`MAX_REMOTE_URL_BYTES`], [`MAX_BLOCK_REMOTE_URLS`] and
+/// [`MAX_BLOCK_REMOTE_URL_BYTES`]. Past a limit it keeps no more, and `limit` says why.
+#[derive(Debug, Default)]
+pub struct RemoteUrls {
+ urls: HashSet<String>,
+ bytes: usize,
+ pub limit: Option<UrlLimit>,
+}
+
+impl RemoteUrls {
+ fn insert(&mut self, url: &str) {
+ if self.limit.is_some() || self.urls.contains(url) {
+ return;
+ }
+ self.limit = if url.len() > MAX_REMOTE_URL_BYTES {
+ Some(UrlLimit::UrlLength)
+ } else if self.urls.len() >= MAX_BLOCK_REMOTE_URLS {
+ Some(UrlLimit::UrlCount)
+ } else if self.bytes + url.len() > MAX_BLOCK_REMOTE_URL_BYTES {
+ Some(UrlLimit::UrlBytes)
+ } else {
+ self.bytes += url.len();
+ self.urls.insert(url.to_owned());
+ None
+ };
+ }
+
+ pub fn extend(&mut self, other: RemoteUrls) {
+ self.limit = self.limit.or(other.limit);
+ for url in &other.urls {
+ self.insert(url);
+ }
+ }
+
+ pub fn into_urls(self) -> Vec<String> {
+ self.urls.into_iter().collect()
+ }
+}
+
+/// Distinct remote image URLs, at most [`MAX_IMAGE_URLS`] per message.
+#[derive(Default)]
+struct Urls {
+ urls: Vec<String>,
+ in_message: HashSet<String>,
+ /// Every remote URL in an image slot, past the fetch cap and in a hidden img too. The writer replaces each one in
+ /// the stored block, and the fetch cap limits only the fetch jobs.
+ remote: RemoteUrls,
+}
+
+/// The URL as the fetcher takes it: remote, and no longer than v3 fetches. An inline image is moved out of the block
+/// by the image scan instead.
+fn fetchable(url: &str) -> Option<&str> {
+ let url = url.trim();
+ (url.len() <= MAX_URL_LEN && is_remote(url)).then_some(url)
+}
+
+/// A URL scheme is not case sensitive, so `HTTPS://` loads as `https://` does.
+fn is_remote(url: &str) -> bool {
+ let starts = |prefix: &str| {
+ url.get(..prefix.len())
+ .is_some_and(|start| start.eq_ignore_ascii_case(prefix))
+ };
+ starts("https://") || starts("http://")
+}
+
+impl Urls {
+ fn push(&mut self, url: &str) {
+ self.push_remote(url);
+ let Some(url) = fetchable(url) else { return };
+ if self.in_message.len() < MAX_IMAGE_URLS && !self.in_message.contains(url) {
+ self.in_message.insert(url.to_owned());
+ self.urls.push(url.to_owned());
+ }
+ }
+
+ /// Records a URL that the block holds but the fetcher does not take now, such as one of a hidden img.
+ fn push_remote(&mut self, url: &str) {
+ let url = url.trim();
+ if is_remote(url) {
+ self.remote.insert(url);
+ }
+ }
+
+ /// Takes the URLs one walk found.
+ fn merge(&mut self, walk: Urls) {
+ for url in &walk.urls {
+ self.push(url);
+ }
+ self.remote.extend(walk.remote);
+ }
}
/// The DOM state of a session's windows in this process.
#[derive(Default)]
pub struct DomInspector {
windows: HashMap<String, WindowDom>,
+ evicted: HashSet<String>,
+ clock: u64,
+ /// A full snapshot of any window decoded in this process.
+ seen_snapshot: bool,
+ /// The session's DOM state was evicted, so any window it opens may have lost its DOM.
+ lost: bool,
+ urls: Urls,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
@@ -41,7 +313,11 @@ pub struct Observed {
/// What one walk over serialized nodes found.
#[derive(Default)]
struct Walk {
- ids: Vec<i64>,
+ /// Each node and its parent. A root's parent is `None`.
+ ids: Vec<(i64, Option<i64>)>,
+ /// The walk met more nodes than the node cap, so `ids` stops short.
+ truncated: bool,
+ media: Vec<(i64, Media)>,
nodes: u32,
text_chars: u64,
remote_stylesheets: u32,
@@ -50,18 +326,324 @@ struct Walk {
canvases: u32,
videos: u32,
shadow_roots: u32,
+ style_texts: Vec<i64>,
+ image_urls: Urls,
+ hidden: Vec<(i64, HiddenSources)>,
+ /// `source` elements that are a walk's root, with their srcset. Whether each is a picture source depends on the
+ /// parent that the mutation names.
+ root_sources: Vec<(Option<i64>, Option<Span>)>,
+}
+
+impl Walk {
+ fn push_id(&mut self, id: i64, parent: Option<i64>) {
+ if self.ids.len() < MAX_TRACKED_NODES {
+ self.ids.push((id, parent));
+ } else {
+ self.truncated = true;
+ }
+ }
+
+ fn push_url(&mut self, bytes: &[u8], value: Option<Span>) {
+ if let Some(url) = value
+ .filter(|&v| scan::is_string(bytes, v))
+ .and_then(|v| scan::unescape(bytes, v).ok())
+ {
+ self.push_url_text(&url);
+ }
+ }
+
+ fn push_url_text(&mut self, url: &str) {
+ self.image_urls.push(url);
+ }
+
+ /// The URLs of a slot the fetcher does not take now. The block still holds them, so the writer replaces them.
+ fn push_remote(&mut self, bytes: &[u8], value: Option<Span>, srcset: bool) {
+ if let Some(text) = text(bytes, value) {
+ if srcset {
+ srcset_urls(&text, &mut |url| self.image_urls.push_remote(url));
+ } else {
+ self.image_urls.push_remote(&text);
+ }
+ }
+ }
+
+ fn push_srcset(&mut self, bytes: &[u8], value: Option<Span>) {
+ if let Some(srcset) = text(bytes, value) {
+ srcset_urls(&srcset, &mut |url| self.push_url_text(url));
+ }
+ }
+
+ fn push_css(&mut self, bytes: &[u8], value: Option<Span>) {
+ let Some(value) = value else { return };
+ if let Some(text) = text(bytes, Some(value)) {
+ css::image_urls(&text, &mut |url| self.push_url_text(url));
+ } else if scan::is_object(bytes, value) {
+ let Ok(entries) = scan::object_entries(bytes, value) else {
+ return;
+ };
+ for entry in entries.filter_map(Result::ok).filter(|e| !e.key_escaped) {
+ let property = std::str::from_utf8(&bytes[entry.key.0..entry.key.1]);
+ let declared = text(bytes, style_property_value(bytes, entry.value));
+ if let (Ok(property), Some(declared)) = (property, declared) {
+ css::declaration_image_urls(property, &declared, &mut |url| {
+ self.image_urls.push(url)
+ });
+ }
+ }
+ }
+ }
+}
+
+/// The URLs of a srcset, parsed as HTML parses one: a URL is a run of non-whitespace, so it can hold a comma. A comma
+/// ends a candidate only at the end of its URL or after its descriptors.
+fn srcset_urls(srcset: &str, found: &mut impl FnMut(&str)) {
+ let bytes = srcset.as_bytes();
+ let mut position = 0;
+ loop {
+ while bytes
+ .get(position)
+ .is_some_and(|&b| b.is_ascii_whitespace() || b == b',')
+ {
+ position += 1;
+ }
+ if position >= bytes.len() {
+ return;
+ }
+ let start = position;
+ while bytes
+ .get(position)
+ .is_some_and(|b| !b.is_ascii_whitespace())
+ {
+ position += 1;
+ }
+ let url = srcset[start..position].trim_end_matches(',');
+ found(url);
+ if url.len() < position - start {
+ continue;
+ }
+ let mut in_parens = false;
+ while let Some(&byte) = bytes.get(position) {
+ position += 1;
+ match byte {
+ b'(' => in_parens = true,
+ b')' => in_parens = false,
+ b',' if !in_parens => break,
+ _ => {}
+ }
+ }
+ }
+}
+
+fn style_property_value(bytes: &[u8], span: Span) -> Option<Span> {
+ if scan::is_array(bytes, span) {
+ scan::array_items(bytes, span).ok()?.next()?.ok()
+ } else {
+ Some(span)
+ }
+}
+
+/// A repeated attribute takes its last value, as in `JSON.parse`, so that the inspector names the URL the player loads.
+#[derive(Default)]
+struct Attributes {
+ rel: Option<Span>,
+ href: Option<Span>,
+ xlink_href: Option<Span>,
+ css_text: Option<Span>,
+ style: Option<Span>,
+ src: Option<Span>,
+ rr_src: Option<Span>,
+ srcset: Option<Span>,
+ poster: Option<Span>,
+ hidden: Option<Span>,
+ width: Option<Span>,
+ height: Option<Span>,
+}
+
+impl Attributes {
+ fn slot(&mut self, name: &[u8]) -> Option<&mut Option<Span>> {
+ Some(match name {
+ b"rel" => &mut self.rel,
+ b"href" => &mut self.href,
+ b"xlink:href" => &mut self.xlink_href,
+ b"_cssText" => &mut self.css_text,
+ b"style" => &mut self.style,
+ b"src" => &mut self.src,
+ b"rr_src" => &mut self.rr_src,
+ b"srcset" => &mut self.srcset,
+ b"poster" => &mut self.poster,
+ b"hidden" => &mut self.hidden,
+ b"width" => &mut self.width,
+ b"height" => &mut self.height,
+ _ => return None,
+ })
+ }
+
+ fn read(bytes: &[u8], object: Span) -> Self {
+ let mut attributes = Self::default();
+ if let Ok(entries) = scan::object_entries(bytes, object) {
+ for entry in entries.filter_map(Result::ok).filter(|e| !e.key_escaped) {
+ if let Some(slot) = attributes.slot(&bytes[entry.key.0..entry.key.1]) {
+ *slot = Some(entry.value);
+ }
+ }
+ }
+ attributes
+ }
+
+ /// The sources of a node the window does not know, after a restart, an eviction or the node cap. What the node
+ /// shows is not known, so they are not fetched. The block holds them, so the writer replaces them.
+ fn push_unknown_sources(&self, bytes: &[u8], walk: &mut Walk) {
+ walk.push_remote(bytes, self.src, false);
+ walk.push_remote(bytes, self.rr_src, false);
+ walk.push_remote(bytes, self.srcset, true);
+ walk.push_remote(bytes, self.href, false);
+ walk.push_remote(bytes, self.xlink_href, false);
+ walk.push_remote(bytes, self.poster, false);
+ }
+
+ /// The image URLs v3 fetches from these attributes on an element of this kind, and the URLs in its CSS.
+ fn push_urls(&self, bytes: &[u8], media: Option<Media>, walk: &mut Walk) {
+ match media {
+ Some(Media::Img { visibility }) if !visibility.hides() => {
+ walk.push_url(bytes, self.src);
+ walk.push_url(bytes, self.rr_src);
+ walk.push_srcset(bytes, self.srcset);
+ }
+ Some(Media::Img { .. }) => {
+ walk.push_remote(bytes, self.src, false);
+ walk.push_remote(bytes, self.rr_src, false);
+ walk.push_remote(bytes, self.srcset, true);
+ }
+ Some(Media::SvgImage) => {
+ walk.push_url(bytes, self.href);
+ walk.push_url(bytes, self.xlink_href);
+ }
+ Some(Media::Video) => walk.push_url(bytes, self.poster),
+ Some(Media::PictureSource) => walk.push_srcset(bytes, self.srcset),
+ _ => {}
+ }
+ walk.push_css(bytes, self.style);
+ walk.push_css(bytes, self.css_text);
+ }
+}
+
+/// A CSS or HTML length read as pixels, as in v3: `1`, `1px` and `1.0` are one pixel, other units are unknown.
+fn px_length(text: &str) -> Option<f64> {
+ let text = text.trim().to_ascii_lowercase();
+ let number = text.strip_suffix("px").map_or(text.as_str(), str::trim);
+ number.parse::<f64>().ok()
+}
+
+fn is_at_most_one_pixel(length: Option<f64>) -> bool {
+ length.is_some_and(|length| (0.0..=1.0).contains(&length))
+}
+
+/// What v3 `is_hidden_pixel` reads from an img: the `hidden` attribute, `display: none`, or at most one pixel each way.
+/// An attribute mutation names only the attributes it changes, so the window keeps this to judge the img after one.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+struct Visibility {
+ hidden: bool,
+ display_none: bool,
+ /// Whether the width and the height are at most one pixel, by the inline style and by the attributes. The inline
+ /// style wins where it declares one.
+ style_tiny: [Option<bool>; 2],
+ attribute_tiny: [bool; 2],
+}
+
+impl Visibility {
+ fn hides(&self) -> bool {
+ let tiny = |i: usize| self.style_tiny[i].unwrap_or(self.attribute_tiny[i]);
+ self.hidden || self.display_none || (tiny(0) && tiny(1))
+ }
+
+ fn update(&mut self, bytes: &[u8], attributes: &Attributes) {
+ if let Some(hidden) = attributes.hidden {
+ self.hidden = !scan::is_null(bytes, hidden);
+ }
+ for (i, attribute) in [attributes.width, attributes.height]
+ .into_iter()
+ .enumerate()
+ {
+ if let Some(span) = attribute {
+ self.attribute_tiny[i] = is_at_most_one_pixel(if scan::is_string(bytes, span) {
+ scan::unescape(bytes, span).ok().and_then(|v| px_length(&v))
+ } else {
+ scan::parse_number(bytes, span)
+ });
+ }
+ }
+ let Some(style) = attributes.style else {
+ return;
+ };
+ if let Some(style) = text(bytes, Some(style)) {
+ self.display_none =
+ inline_style_declaration(&style, "display").as_deref() == Some("none");
+ for (i, name) in ["width", "height"].into_iter().enumerate() {
+ self.style_tiny[i] = inline_style_declaration(&style, name)
+ .map(|declared| is_at_most_one_pixel(px_length(&declared)));
+ }
+ } else if scan::is_object(bytes, style) {
+ // rrweb records a change to the style attribute as the properties that changed: a value, a
+ // `[value, priority]` pair, or `false` for a property it removed.
+ let [display, width, height] = fields(bytes, style, [b"display", b"width", b"height"]);
+ let declared = |span: Option<Span>| {
+ let value = style_property_value(bytes, span?)?;
+ Some(
+ text(bytes, Some(value))
+ .map(|v| without_important(&v.trim().to_ascii_lowercase()).to_owned()),
+ )
+ };
+ if let Some(display) = declared(display) {
+ self.display_none = display.as_deref() == Some("none");
+ }
+ for (i, span) in [width, height].into_iter().enumerate() {
+ if let Some(length) = declared(span) {
+ self.style_tiny[i] =
+ length.map(|length| is_at_most_one_pixel(px_length(&length)));
+ }
+ }
+ } else {
+ self.display_none = false;
+ self.style_tiny = [None; 2];
+ }
+ }
+}
+
+/// The last value an inline style gives one property, lowercased and without `!important`.
+fn inline_style_declaration(style: &str, property: &str) -> Option<String> {
+ style
+ .split(';')
+ .filter_map(|declaration| declaration.split_once(':'))
+ .filter(|(name, _)| name.trim().eq_ignore_ascii_case(property))
+ .map(|(_, value)| without_important(&value.trim().to_ascii_lowercase()).to_owned())
+ .next_back()
+}
+
+fn without_important(value: &str) -> &str {
+ let Some(before_keyword) = value.strip_suffix("important") else {
+ return value;
+ };
+ match before_keyword.trim_end().strip_suffix('!') {
+ Some(declared_value) => declared_value.trim_end(),
+ None => value,
+ }
}
#[derive(Default)]
struct NodeFrame {
id: Option<i64>,
is_text: bool,
- tag: Option<Span>,
+ is_style_text: bool,
+ tag: Tag,
text: Option<Span>,
shadow_host: bool,
- rel_stylesheet: bool,
- href: bool,
- inline_css: bool,
+ attributes: Attributes,
+ /// The ids of the children walked so far. A node's id comes after its children, so they wait for it here.
+ children: Vec<i64>,
+ /// Child text, and child `source` elements with their srcset, which count only under a `style` or a `picture`.
+ /// They wait here because the tag can come after the children.
+ child_texts: Vec<(Option<i64>, Span)>,
+ child_sources: Vec<(Option<i64>, Option<Span>)>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -72,13 +654,15 @@ enum FrameKind {
Other,
}
-/// Walks the serialized node at `span` and its descendants, reading each byte once.
-fn walk_nodes(bytes: &[u8], span: Span, walk: &mut Walk) {
+/// Walks the serialized node at `span` and its descendants, reading each byte once. Returns false when the input is
+/// malformed or nested too deep.
+fn walk_nodes(bytes: &[u8], span: Span, walk: &mut Walk) -> bool {
let mut kinds: Vec<FrameKind> = Vec::new();
let mut nodes: Vec<NodeFrame> = Vec::new();
let mut key: Option<Span> = None;
let mut started = false;
- for token in Tokens::new(bytes, span) {
+ let mut tokens = Tokens::new(bytes, span);
+ for token in tokens.by_ref() {
let parent = kinds.last().copied();
let current_key = key.take().map(|k| &bytes[k.0..k.1]);
match token {
@@ -103,7 +687,7 @@ fn walk_nodes(bytes: &[u8], span: Span, walk: &mut Walk) {
Token::ObjectEnd | Token::ArrayEnd => {
if kinds.pop() == Some(FrameKind::Node) {
if let Some(node) = nodes.pop() {
- finish_node(bytes, node, walk);
+ finish_node(bytes, node, nodes.last_mut(), walk);
}
}
}
@@ -118,62 +702,158 @@ fn walk_nodes(bytes: &[u8], span: Span, walk: &mut Walk) {
b"type" => {
node.is_text = scan::parse_number(bytes, value) == Some(TEXT_NODE)
}
- b"tagName" => node.tag = Some(value),
+ b"tagName" => node.tag = tag(bytes, value),
b"textContent" => node.text = Some(value),
b"isShadowHost" => node.shadow_host = &bytes[value.0..value.1] == b"true",
+ b"isStyle" => node.is_style_text = &bytes[value.0..value.1] == b"true",
_ => {}
}
}
(Some(FrameKind::Attributes), Some(name)) => {
- let Some(node) = nodes.last_mut() else {
- continue;
- };
- match name {
- b"rel" => {
- node.rel_stylesheet = attribute_contains(bytes, value, "stylesheet")
- }
- b"href" => node.href = true,
- b"_cssText" => node.inline_css = true,
- _ => {}
+ if let Some(slot) = nodes.last_mut().and_then(|n| n.attributes.slot(name)) {
+ *slot = Some(value);
}
}
_ => {}
},
}
}
+ !tokens.failed
+}
+
+fn finish_node(bytes: &[u8], node: NodeFrame, parent: Option<&mut NodeFrame>, walk: &mut Walk) {
+ walk.nodes += 1;
+ let media = match node.tag {
+ Tag::Img => {
+ let mut visibility = Visibility::default();
+ visibility.update(bytes, &node.attributes);
+ Some(Media::Img { visibility })
+ }
+ Tag::SvgImage => Some(Media::SvgImage),
+ Tag::Video => Some(Media::Video),
+ Tag::Picture => Some(Media::Picture),
+ _ => None,
+ };
+ if node.tag == Tag::Style {
+ for &(id, text) in &node.child_texts {
+ walk.style_texts.extend(id);
+ walk.push_css(bytes, Some(text));
+ }
+ }
+ if node.tag == Tag::Picture {
+ for &(id, srcset) in &node.child_sources {
+ walk.media.extend(id.map(|id| (id, Media::PictureSource)));
+ walk.push_srcset(bytes, srcset);
+ }
+ }
+ match node.id {
+ Some(id) => {
+ for &child in &node.children {
+ walk.push_id(child, Some(id));
+ }
+ if let Some(media) = media {
+ walk.media.push((id, media));
+ }
+ if let Some(Media::Img { visibility }) = media {
+ if visibility.hides() && walk.hidden.len() < MAX_TRACKED_NODES {
+ let sources = HiddenSources::read(bytes, &node.attributes);
+ if !sources.is_empty() {
+ walk.hidden.push((id, sources));
+ }
+ }
+ }
+ }
+ None => {
+ for &child in &node.children {
+ walk.push_id(child, None);
+ }
+ }
+ }
+ if node.is_text {
+ if let Some(text) = node.text {
+ // The escaped length: close enough to count how much text a page holds, without decoding it.
+ walk.text_chars += (text.1 - text.0).saturating_sub(2) as u64;
+ if node.is_style_text {
+ walk.style_texts.extend(node.id);
+ walk.push_css(bytes, Some(text));
+ }
+ }
+ }
+ walk.shadow_roots += u32::from(node.shadow_host);
+ node.attributes.push_urls(bytes, media, walk);
+ let attributes = &node.attributes;
+ match node.tag {
+ Tag::Link if attributes.css_text.is_some() => walk.inline_stylesheets += 1,
+ Tag::Link
+ if attributes.href.is_some()
+ && attributes
+ .rel
+ .is_some_and(|rel| attribute_contains(bytes, rel, "stylesheet")) =>
+ {
+ walk.remote_stylesheets += 1
+ }
+ Tag::Style => walk.inline_stylesheets += 1,
+ Tag::Iframe => walk.iframes += 1,
+ Tag::Canvas => walk.canvases += 1,
+ Tag::Video => walk.videos += 1,
+ _ => {}
+ }
+ match parent {
+ Some(parent) => {
+ parent.children.extend(node.id);
+ if node.is_text && !node.is_style_text {
+ parent
+ .child_texts
+ .extend(node.text.map(|text| (node.id, text)));
+ }
+ if node.tag == Tag::Source {
+ parent.child_sources.push((node.id, node.attributes.srcset));
+ }
+ }
+ None => {
+ if let Some(id) = node.id {
+ walk.push_id(id, None);
+ }
+ if node.tag == Tag::Source {
+ walk.root_sources.push((node.id, node.attributes.srcset));
+ }
+ }
+ }
}
-/// What a full snapshot's data holds.
+/// What a full snapshot does to its window.
enum Snapshot {
- /// Its compressed data does not decode.
- Undecoded,
- /// It has no node to walk.
- Empty,
- Walked(Walk),
+ /// The player drops it, because its data or its node is not an object.
+ Dropped,
+ /// It does not decode or is too deep to walk, and the player may still build a DOM from a payload this deep.
+ Unreadable,
+ Walked(Box<Walk>),
}
/// Walks the DOM in a full snapshot's data, decoded when the event is compressed.
-fn walk_snapshot(inner: &[u8], event: &Event, data: Span) -> Snapshot {
- let expansion;
- let (bytes, root) = if event.compressed && scan::is_string(inner, data) {
- // The decode the message already did, within its budget. An event it skipped is not decoded here.
- expansion = cv::expansion(inner, event);
- let Some(Some(json)) = expansion.json(data) else {
- return Snapshot::Undecoded;
- };
- let Ok(root) = scan::locate_value(json, 0) else {
- return Snapshot::Undecoded;
- };
- (json, root)
+fn walk_snapshot(inner: &[u8], data: Span, expansion: &Expansion) -> Snapshot {
+ let (bytes, root) = if scan::is_string(inner, data) {
+ match expansion.json(data) {
+ Some(Some(json)) => match scan::locate_value(json, 0) {
+ Ok(root) => (json, root),
+ Err(_) => return Snapshot::Unreadable,
+ },
+ Some(None) => return Snapshot::Dropped,
+ None => return Snapshot::Unreadable,
+ }
} else {
(inner, data)
};
- let Some(node) = field(bytes, root, b"node") else {
- return Snapshot::Empty;
+ let Some(node) = field(bytes, root, b"node").filter(|&node| scan::is_object(bytes, node))
+ else {
+ return Snapshot::Dropped;
};
let mut walk = Walk::default();
- walk_nodes(bytes, node, &mut walk);
- Snapshot::Walked(walk)
+ if walk_nodes(bytes, node, &mut walk) {
+ Snapshot::Walked(Box::new(walk))
+ } else {
+ Snapshot::Unreadable
+ }
}
fn attribute_contains(bytes: &[u8], value: Span, word: &str) -> bool {
@@ -181,50 +861,203 @@ fn attribute_contains(bytes: &[u8], value: Span, word: &str) -> bool {
&& scan::unescape(bytes, value).is_ok_and(|v| v.to_ascii_lowercase().contains(word))
}
-fn finish_node(bytes: &[u8], node: NodeFrame, walk: &mut Walk) {
- walk.nodes += 1;
- if let Some(id) = node.id {
- walk.ids.push(id);
+impl WindowDom {
+ fn insert(&mut self, id: i64, parent: Option<i64>) {
+ if self.nodes.len() >= MAX_TRACKED_NODES && !self.nodes.contains_key(&id) {
+ self.unverifiable = true;
+ return;
+ }
+ if let Some(parent) = parent {
+ let children = self.children.entry(parent).or_default();
+ let capacity = children.capacity();
+ children.push(id);
+ self.child_capacity += children.capacity() - capacity;
+ }
+ if self.nodes.insert(id, parent).is_some() {
+ self.mark_stale();
+ }
}
- if node.is_text {
- if let Some(text) = node.text {
- // The escaped length: close enough to count how much text a page holds, without decoding it.
- walk.text_chars += (text.1 - text.0).saturating_sub(2) as u64;
+
+ fn add_media(&mut self, media: &[(i64, Media)]) {
+ for &(id, kind) in media {
+ if self.media.len() < MAX_TRACKED_NODES || self.media.contains_key(&id) {
+ self.media.insert(id, kind);
+ }
}
}
- walk.shadow_roots += u32::from(node.shadow_host);
- let tag = node
- .tag
- .and_then(|t| scan::unescape(bytes, t).ok())
- .map(|t| t.to_ascii_lowercase());
- match tag.as_deref() {
- Some("link") if node.inline_css => walk.inline_stylesheets += 1,
- Some("link") if node.rel_stylesheet && node.href => walk.remote_stylesheets += 1,
- Some("style") => walk.inline_stylesheets += 1,
- Some("iframe") => walk.iframes += 1,
- Some("canvas") => walk.canvases += 1,
- Some("video") => walk.videos += 1,
- _ => {}
+
+ fn add_hidden_sources(&mut self, hidden: &[(i64, HiddenSources)]) {
+ for (id, sources) in hidden {
+ if self.hidden_sources.len() < MAX_TRACKED_NODES || self.hidden_sources.contains_key(id)
+ {
+ self.set_hidden_sources(*id, Some(sources.clone()));
+ }
+ }
}
-}
-impl WindowDom {
- fn insert(&mut self, ids: &[i64]) {
+ fn set_hidden_sources(
+ &mut self,
+ id: i64,
+ sources: Option<HiddenSources>,
+ ) -> Option<HiddenSources> {
+ let sources = sources.filter(|sources| !sources.is_empty());
+ self.hidden_source_bytes += sources.as_ref().map_or(0, HiddenSources::heap_bytes);
+ let previous = match sources {
+ Some(sources) => self.hidden_sources.insert(id, sources),
+ None => self.hidden_sources.remove(&id),
+ };
+ self.hidden_source_bytes -= previous.as_ref().map_or(0, HiddenSources::heap_bytes);
+ previous
+ }
+
+ fn add_style_texts(&mut self, ids: &[i64]) {
for &id in ids {
- if self.nodes.len() >= MAX_TRACKED_NODES {
- self.cap_reached = true;
- return;
+ if self.style_texts.len() < MAX_TRACKED_NODES {
+ self.style_texts.insert(id);
}
- self.nodes.insert(id);
}
}
fn knows(&self, id: i64, added: &HashSet<i64>) -> bool {
- self.nodes.contains(&id) || added.contains(&id)
+ self.nodes.contains_key(&id) || added.contains(&id)
+ }
+
+ /// Removes a node and every node under it, as the page does. Returns how many nodes went.
+ fn remove(&mut self, id: i64) -> u32 {
+ let mut removed = 0;
+ let mut stack = vec![id];
+ while let Some(id) = stack.pop() {
+ if self.nodes.remove(&id).is_none() {
+ continue;
+ }
+ removed += 1;
+ self.media.remove(&id);
+ self.set_hidden_sources(id, None);
+ self.style_texts.remove(&id);
+ if let Some(children) = self.children.remove(&id) {
+ self.child_capacity -= children.capacity();
+ // A node that moved away from this parent stays in its list until compaction, so check it.
+ stack.extend(
+ children
+ .into_iter()
+ .filter(|c| self.nodes.get(c) == Some(&Some(id))),
+ );
+ }
+ }
+ self.mark_stale();
+ removed
+ }
+
+ fn mark_stale(&mut self) {
+ self.stale_children += 1;
+ if self.stale_children > self.nodes.len().max(4096) {
+ self.compact();
+ }
+ }
+
+ fn compact(&mut self) {
+ let nodes = &self.nodes;
+ self.children.retain(|&parent, children| {
+ children.retain(|child| nodes.get(child) == Some(&Some(parent)));
+ children.sort_unstable();
+ children.dedup();
+ children.shrink_to_fit();
+ !children.is_empty()
+ });
+ self.child_capacity = self.children.values().map(Vec::capacity).sum();
+ self.stale_children = 0;
+ }
+}
+
+/// The DOM of `name`, created when the session has not seen it, evicting the window used least recently past the cap.
+fn window_dom<'d>(
+ windows: &'d mut HashMap<String, WindowDom>,
+ evicted: &mut HashSet<String>,
+ lost: bool,
+ clock: u64,
+ name: &str,
+) -> &'d mut WindowDom {
+ if !windows.contains_key(name) {
+ if windows.len() >= MAX_WINDOWS {
+ let oldest = windows
+ .iter()
+ .min_by_key(|(_, dom)| dom.last_used)
+ .map(|(oldest, dom)| (oldest.clone(), dom.has_snapshot || dom.unverifiable));
+ if let Some((oldest, lost_state)) = oldest {
+ windows.remove(&oldest);
+ if lost_state && evicted.len() < MAX_EVICTED_WINDOWS {
+ evicted.insert(oldest);
+ }
+ }
+ }
+ // A window that comes back after eviction lost its DOM, so its mutations go unchecked until its next snapshot.
+ let unverifiable = evicted.remove(name) || lost;
+ windows.insert(
+ name.to_owned(),
+ WindowDom {
+ unverifiable,
+ ..WindowDom::default()
+ },
+ );
+ }
+ let dom = windows
+ .get_mut(name)
+ .expect("the window was inserted above");
+ dom.last_used = clock;
+ dom
+}
+
+/// The heap bytes a hash table of this many slots holds: each slot has an entry and a control byte.
+fn table_bytes<T>(capacity: usize) -> usize {
+ capacity * (std::mem::size_of::<T>() + 1)
+}
+
+impl WindowDom {
+ fn retained_bytes(&self) -> usize {
+ table_bytes::<(i64, Option<i64>)>(self.nodes.capacity())
+ + table_bytes::<(i64, Vec<i64>)>(self.children.capacity())
+ + self.child_capacity * std::mem::size_of::<i64>()
+ + table_bytes::<(i64, Media)>(self.media.capacity())
+ + table_bytes::<(i64, HiddenSources)>(self.hidden_sources.capacity())
+ + self.hidden_source_bytes
+ + table_bytes::<i64>(self.style_texts.capacity())
}
}
impl DomInspector {
+ /// The state of a session whose DOM state was evicted. A window it opens counts as one that came back after
+ /// eviction, until its next full snapshot.
+ pub fn after_eviction() -> Self {
+ Self {
+ lost: true,
+ ..Self::default()
+ }
+ }
+
+ pub fn retained_bytes(&self) -> usize {
+ let windows: usize = self
+ .windows
+ .iter()
+ .map(|(name, dom)| name.capacity() + dom.retained_bytes())
+ .sum();
+ let evicted: usize = self.evicted.iter().map(String::capacity).sum();
+ windows
+ + table_bytes::<(String, WindowDom)>(self.windows.capacity())
+ + evicted
+ + table_bytes::<String>(self.evicted.capacity())
+ }
+
+ /// Starts a message: the image URL cap counts per message.
+ pub fn start_message(&mut self) {
+ self.urls.in_message.clear();
+ }
+
+ /// Ends a message. The URLs it saw go, so that they do not stay in memory that [`Self::retained_bytes`] does not
+ /// count.
+ pub fn finish_message(&mut self) {
+ self.urls.in_message = HashSet::new();
+ }
+
/// Updates the window's DOM with one event and adds what it found to the block.
pub fn observe(
&mut self,
@@ -233,21 +1066,37 @@ impl DomInspector {
window: &str,
stats: &mut BlockStats,
) -> Observed {
- let dom = self.windows.entry(window.to_owned()).or_default();
+ self.clock += 1;
+ let dom = window_dom(
+ &mut self.windows,
+ &mut self.evicted,
+ self.lost,
+ self.clock,
+ window,
+ );
let mut observed = Observed::default();
match (event.kind, event.source) {
(Some(FULL_SNAPSHOT), _) => {
- match event
- .data
- .map_or(Snapshot::Empty, |data| walk_snapshot(inner, event, data))
- {
- Snapshot::Walked(walk) => {
+ let expansion = cv::expansion(inner, event);
+ let last_used = dom.last_used;
+ match event.data.map_or(Snapshot::Dropped, |data| {
+ walk_snapshot(inner, data, &expansion)
+ }) {
+ Snapshot::Walked(mut walk) => {
// A full snapshot replaces the window's DOM.
*dom = WindowDom {
has_snapshot: true,
+ unverifiable: walk.truncated,
+ last_used,
..WindowDom::default()
};
- dom.insert(&walk.ids);
+ for &(id, parent) in &walk.ids {
+ dom.insert(id, parent);
+ }
+ dom.add_media(&walk.media);
+ dom.add_hidden_sources(&walk.hidden);
+ dom.add_style_texts(&walk.style_texts);
+ stats.full_snapshots += 1;
stats.dom_nodes = stats.dom_nodes.max(walk.nodes);
stats.dom_text_chars = stats.dom_text_chars.max(walk.text_chars);
stats.remote_stylesheets += walk.remote_stylesheets;
@@ -256,121 +1105,417 @@ impl DomInspector {
stats.canvases += walk.canvases;
stats.videos += walk.videos;
stats.shadow_roots += walk.shadow_roots;
+ self.urls.merge(std::mem::take(&mut walk.image_urls));
+ self.seen_snapshot = true;
observed.full_snapshot = true;
}
- Snapshot::Undecoded => stats.decode_failures += 1,
- Snapshot::Empty => {}
+ Snapshot::Unreadable => {
+ stats.decode_failures += 1;
+ *dom = WindowDom {
+ unverifiable: true,
+ last_used,
+ ..WindowDom::default()
+ }
+ }
+ // The window keeps the DOM it had, as in the player.
+ Snapshot::Dropped => {}
}
}
- (Some(INCREMENTAL_SNAPSHOT), Some(MUTATION))
- if dom.has_snapshot && !dom.cap_reached =>
- {
+ (Some(INCREMENTAL_SNAPSHOT), Some(MUTATION)) => {
if let Some(data) = event.data {
let expansion = cv::expansion(inner, event);
- let (orphans, size, failed) = observe_mutation(inner, data, &expansion, dom);
+ let (orphans, changed, undecoded) =
+ observe_mutation(inner, data, &expansion, dom, &mut self.urls);
stats.orphan_mutations += orphans;
- stats.decode_failures += u32::from(failed);
- observed.changed = size;
+ stats.decode_failures += u32::from(undecoded);
+ observed.changed = changed;
+ }
+ }
+ (
+ Some(INCREMENTAL_SNAPSHOT),
+ Some(STYLE_SHEET_RULE | STYLE_DECLARATION | ADOPTED_STYLE_SHEET),
+ ) => {
+ if let Some(data) = event.data {
+ let expansion = cv::expansion(inner, event);
+ if matches!(*expansion, Expansion::Failed | Expansion::Skipped) {
+ stats.decode_failures += 1;
+ }
+ style_sheet_urls(inner, data, event.source, &expansion, &mut self.urls);
}
}
_ => {}
}
- if !dom.has_snapshot {
+ if !self.seen_snapshot {
stats.events_before_first_full_snapshot += 1;
}
- stats.node_cap_reached |= dom.cap_reached;
+ stats.node_cap_reached |= dom.unverifiable;
observed
}
- /// Whether any window of the session has a full snapshot in this process.
+ /// The remote image URLs the DOM referenced since the last call.
+ pub fn take_image_urls(&mut self) -> Vec<String> {
+ std::mem::take(&mut self.urls.urls)
+ }
+
+ /// Every remote image URL the events since the last call hold, for the writer to replace.
+ pub fn take_remote_urls(&mut self) -> RemoteUrls {
+ std::mem::take(&mut self.urls.remote)
+ }
+
+ /// Whether a full snapshot of any window of the session decoded in this process.
pub fn has_snapshot(&self) -> bool {
- self.windows.values().any(|w| w.has_snapshot)
+ self.seen_snapshot
}
}
-/// A mutation list's name and its JSON.
-type List<'b> = (&'static [u8], &'b [u8]);
+#[derive(Clone, Copy)]
+struct List<'b> {
+ bytes: &'b [u8],
+ span: Span,
+}
-/// The mutation's four lists, decoded when the event is compressed, and whether the event did not decode.
-fn mutation_lists<'b>(
- inner: &'b [u8],
- data: Span,
- expansion: &'b Expansion,
-) -> (Vec<List<'b>>, bool) {
- if matches!(expansion, Expansion::Failed | Expansion::Skipped) {
- return (Vec::new(), true);
- }
- let mut lists = Vec::new();
- for name in [&b"adds"[..], b"removes", b"texts", b"attributes"] {
- let Some(span) = field(inner, data, name) else {
+/// A mutation's four lists, decoded when the event is compressed.
+#[derive(Default)]
+struct Lists<'b> {
+ adds: Option<List<'b>>,
+ removes: Option<List<'b>>,
+ texts: Option<List<'b>>,
+ attributes: Option<List<'b>>,
+ /// A list is a string that did not decode, so the player drops the whole mutation.
+ failed: bool,
+}
+
+fn mutation_lists<'b>(inner: &'b [u8], data: Span, expansion: &'b Expansion) -> Lists<'b> {
+ let mut lists = Lists::default();
+ let names = [&b"adds"[..], b"removes", b"texts", b"attributes"];
+ let found = fields(inner, data, names);
+ let slots = [
+ &mut lists.adds,
+ &mut lists.removes,
+ &mut lists.texts,
+ &mut lists.attributes,
+ ];
+ let mut failed = false;
+ for (slot, span) in slots.into_iter().zip(found) {
+ let Some(span) = span else { continue };
+ if !scan::is_string(inner, span) {
+ *slot = Some(List { bytes: inner, span });
continue;
- };
+ }
+ // A list in a string is one the player decompresses, or one it cannot read.
match expansion.json(span) {
- Some(Some(json)) => lists.push((name, json)),
- // The player reads an empty string or `null` as absent.
+ Some(Some(json)) => match scan::locate_value(json, 0) {
+ Ok(span) => *slot = Some(List { bytes: json, span }),
+ Err(_) => failed = true,
+ },
Some(None) => {}
- None => lists.push((name, &inner[span.0..span.1])),
+ None => failed = true,
+ }
+ }
+ lists.failed = failed;
+ lists
+}
+
+struct Add {
+ parent: Option<i64>,
+ ids: Range<usize>,
+}
+
+/// Which additions the player's rrweb applies. It queues an addition whose parent is not in its mirror, retries the
+/// queue as the same mutation adds other nodes, and drops what is still waiting. It appends an addition whose `nextId`
+/// sibling is not there.
+fn applied_adds(adds: &[Add], ids: &[(i64, Option<i64>)], dom: &WindowDom) -> Vec<bool> {
+ let mut owner = HashMap::new();
+ for (index, add) in adds.iter().enumerate() {
+ for &(id, _) in &ids[add.ids.clone()] {
+ owner.insert(id, index);
+ }
+ }
+ let mut waiting: HashMap<i64, Vec<usize>> = HashMap::new();
+ let mut missing = vec![0_u32; adds.len()];
+ let mut ready = Vec::new();
+ for (index, add) in adds.iter().enumerate() {
+ if let Some(parent) = add.parent.filter(|parent| !dom.nodes.contains_key(parent)) {
+ missing[index] += 1;
+ if owner.contains_key(&parent) {
+ waiting.entry(parent).or_default().push(index);
+ }
+ }
+ if missing[index] == 0 {
+ ready.push(index);
+ }
+ }
+ let mut applied = vec![false; adds.len()];
+ while let Some(index) = ready.pop() {
+ applied[index] = true;
+ for &(id, _) in &ids[adds[index].ids.clone()] {
+ for waiter in waiting.remove(&id).into_iter().flatten() {
+ missing[waiter] -= 1;
+ if missing[waiter] == 0 {
+ ready.push(waiter);
+ }
+ }
}
}
- (lists, false)
+ applied
}
-/// Applies a mutation to the window's node set. Returns how many of its changes name a node that is not there, how
-/// many nodes it added or removed, and whether a list did not decode.
+/// Applies a mutation to the window's DOM and collects its image URLs. Returns how many of its changes name a node
+/// that is not there, how many nodes it added or removed, and whether the recorder could not read all of it. URLs do
+/// not depend on the DOM state.
fn observe_mutation(
inner: &[u8],
data: Span,
expansion: &Expansion,
dom: &mut WindowDom,
+ urls: &mut Urls,
) -> (u32, u32, bool) {
- let (lists, failed) = mutation_lists(inner, data, expansion);
- // rrweb does not order adds parent first, so a parent added anywhere in the same mutation counts as present.
- let mut added = HashSet::new();
- let mut parents = Vec::new();
- for (name, bytes) in &lists {
- if *name != b"adds" {
- continue;
+ // The recorder did not decode this mutation, so the window's DOM is not known after it.
+ if matches!(expansion, Expansion::Skipped) {
+ dom.unverifiable = true;
+ return (0, 0, true);
+ }
+ let lists = mutation_lists(inner, data, expansion);
+ if lists.failed {
+ return (0, 0, true);
+ }
+ let mut undecoded = false;
+ let mut walk = Walk::default();
+ let mut adds = Vec::new();
+ if let Some(list) = lists.adds {
+ let mut sources = Vec::new();
+ for item in items(list) {
+ let [parent, node] = fields(list.bytes, item, [b"parentId", b"node"]);
+ let parent = number(list.bytes, parent).map(|p| p as i64);
+ let first = walk.ids.len();
+ if let Some(node) = node {
+ let first_source = walk.root_sources.len();
+ if !walk_nodes(list.bytes, node, &mut walk) {
+ dom.unverifiable = true;
+ undecoded = true;
+ }
+ for entry in &mut walk.ids[first..] {
+ entry.1 = entry.1.or(parent);
+ }
+ sources.extend(walk.root_sources.drain(first_source..).map(|s| (parent, s)));
+ }
+ adds.push(Add {
+ parent,
+ ids: first..walk.ids.len(),
+ });
}
- for item in items(bytes) {
- parents.extend(number(bytes, field(bytes, item, b"parentId")).map(|p| p as i64));
- if let Some(node) = field(bytes, item, b"node") {
- let mut walk = Walk::default();
- walk_nodes(bytes, node, &mut walk);
- added.extend(walk.ids);
+ if !sources.is_empty() {
+ let pictures: HashSet<i64> = walk
+ .media
+ .iter()
+ .filter(|(_, media)| *media == Media::Picture)
+ .map(|&(id, _)| id)
+ .collect();
+ for (parent, (id, srcset)) in sources {
+ let Some(parent) = parent else { continue };
+ if pictures.contains(&parent) || dom.media.get(&parent) == Some(&Media::Picture) {
+ walk.media.extend(id.map(|id| (id, Media::PictureSource)));
+ walk.push_srcset(list.bytes, srcset);
+ }
+ }
+ }
+ }
+ dom.add_media(&walk.media);
+ dom.add_hidden_sources(&walk.hidden);
+ dom.add_style_texts(&walk.style_texts);
+ if let Some(texts) = lists.texts {
+ for item in items(texts) {
+ let [id, value] = fields(texts.bytes, item, [b"id", b"value"]);
+ if number(texts.bytes, id).is_some_and(|id| dom.style_texts.contains(&(id as i64))) {
+ walk.push_css(texts.bytes, value);
}
}
}
- let mut orphans = parents.iter().filter(|&&p| !dom.knows(p, &added)).count() as u32;
- for (name, bytes) in &lists {
- if *name == b"texts" || *name == b"attributes" {
- orphans += items(bytes)
- .filter(|&item| {
- number(bytes, field(bytes, item, b"id"))
- .is_some_and(|id| !dom.knows(id as i64, &added))
- })
- .count() as u32;
+ let mut attribute_ids = Vec::new();
+ if let Some(attributes) = lists.attributes {
+ let walked: HashSet<i64> = walk.ids.iter().map(|&(id, _)| id).collect();
+ for (index, item) in items(attributes).enumerate() {
+ if index == MAX_ATTRIBUTE_ITEMS {
+ walk.image_urls.remote.limit = Some(UrlLimit::AttributeItems);
+ break;
+ }
+ let [id, values] = fields(attributes.bytes, item, [b"id", b"attributes"]);
+ let id = number(attributes.bytes, id).map(|id| id as i64);
+ attribute_ids.extend(id);
+ if let Some(values) = values.filter(|&v| scan::is_object(attributes.bytes, v)) {
+ let values = Attributes::read(attributes.bytes, values);
+ let mut media = None;
+ let mut hidden = None;
+ if let Some((id, known)) = id.and_then(|id| dom.media.get_mut(&id).map(|m| (id, m)))
+ {
+ if let Media::Img { visibility } = known {
+ let was_hidden = visibility.hides();
+ visibility.update(attributes.bytes, &values);
+ hidden = Some((id, was_hidden, visibility.hides()));
+ }
+ media = Some(*known);
+ }
+ match hidden {
+ // The sources move out and back, so an update does not copy them.
+ Some((id, _, true)) if HiddenSources::changes(&values) => {
+ let mut sources = dom.set_hidden_sources(id, None).unwrap_or_default();
+ sources.update(attributes.bytes, &values);
+ dom.set_hidden_sources(id, Some(sources));
+ }
+ Some((id, true, false)) => {
+ if let Some(sources) = dom.set_hidden_sources(id, None) {
+ sources.push_revealed(&values, &mut walk);
+ }
+ }
+ _ => {}
+ }
+ let known =
+ id.is_some_and(|id| dom.nodes.contains_key(&id) || walked.contains(&id));
+ if media.is_none() && !known {
+ values.push_unknown_sources(attributes.bytes, &mut walk);
+ }
+ values.push_urls(attributes.bytes, media, &mut walk);
+ }
}
}
+ urls.merge(std::mem::take(&mut walk.image_urls));
+ if walk.truncated {
+ dom.unverifiable = true;
+ }
+ if !dom.has_snapshot || dom.unverifiable {
+ // Without the window's DOM, each node an addition names and each removal counts once.
+ let removes = lists.removes.map_or(0, |removes| items(removes).count());
+ return (0, (walk.ids.len() + removes) as u32, undecoded);
+ }
+
+ let applied = applied_adds(&adds, &walk.ids, dom);
+ let applied: Vec<&Add> = adds
+ .iter()
+ .zip(applied)
+ .filter(|(_, a)| *a)
+ .map(|(add, _)| add)
+ .collect();
+ let mut orphans = (adds.len() - applied.len()) as u32;
+ let added: HashSet<i64> = applied
+ .iter()
+ .flat_map(|add| &walk.ids[add.ids.clone()])
+ .map(|&(id, _)| id)
+ .collect();
+ orphans += attribute_ids
+ .iter()
+ .filter(|&&id| !dom.knows(id, &added))
+ .count() as u32;
+ if let Some(texts) = lists.texts {
+ orphans += items(texts)
+ .filter(|&item| {
+ number(texts.bytes, field(texts.bytes, item, b"id"))
+ .is_some_and(|id| !dom.knows(id as i64, &added))
+ })
+ .count() as u32;
+ }
let mut removed = 0;
- for (name, bytes) in &lists {
- if *name == b"removes" {
- for item in items(bytes) {
- if let Some(id) = number(bytes, field(bytes, item, b"id")) {
- dom.nodes.remove(&(id as i64));
- removed += 1;
+ if let Some(removes) = lists.removes {
+ // A node that moves comes as a removal and an add of the same id, so what the adds installed comes back.
+ let added_media: Vec<(i64, Media)> = walk
+ .media
+ .iter()
+ .filter_map(|&(id, _)| dom.media.get(&id).map(|&media| (id, media)))
+ .collect();
+ let added_hidden: Vec<(i64, HiddenSources)> = walk
+ .hidden
+ .iter()
+ .filter_map(|(id, _)| dom.hidden_sources.get(id).map(|s| (*id, s.clone())))
+ .collect();
+ for item in items(removes) {
+ if let Some(id) = number(removes.bytes, field(removes.bytes, item, b"id")) {
+ removed += dom.remove(id as i64).max(1);
+ }
+ }
+ dom.add_media(&added_media);
+ dom.add_hidden_sources(&added_hidden);
+ dom.add_style_texts(&walk.style_texts);
+ }
+ for add in applied {
+ for &(id, parent) in &walk.ids[add.ids.clone()] {
+ dom.insert(id, parent);
+ }
+ }
+ (orphans, added.len() as u32 + removed, undecoded)
+}
+
+fn style_sheet_urls(
+ inner: &[u8],
+ data: Span,
+ source: Option<u8>,
+ expansion: &Expansion,
+ urls: &mut Urls,
+) {
+ let mut push = |url: &str| urls.push(url);
+ match source {
+ Some(STYLE_SHEET_RULE) => {
+ let [adds, replace, replace_sync] =
+ fields(inner, data, [b"adds", b"replace", b"replaceSync"]);
+ if let Some(adds) = adds.and_then(|adds| decoded_list(inner, adds, expansion)) {
+ for item in items(adds) {
+ if let Some(rule) = text(adds.bytes, field(adds.bytes, item, b"rule")) {
+ css::image_urls(&rule, &mut push);
+ }
+ }
+ }
+ for sheet in [replace, replace_sync] {
+ if let Some(sheet) = text(inner, sheet) {
+ css::image_urls(&sheet, &mut push);
+ }
+ }
+ }
+ Some(STYLE_DECLARATION) => {
+ let set = field(inner, data, b"set");
+ let [property, value] =
+ set.map_or([None; 2], |set| fields(inner, set, [b"property", b"value"]));
+ if let (Some(property), Some(value)) = (text(inner, property), text(inner, value)) {
+ css::declaration_image_urls(&property, &value, &mut push);
+ }
+ }
+ Some(ADOPTED_STYLE_SHEET) => {
+ let Some(styles) = field(inner, data, b"styles") else {
+ return;
+ };
+ for style in items(List {
+ bytes: inner,
+ span: styles,
+ }) {
+ let Some(rules) = field(inner, style, b"rules") else {
+ continue;
+ };
+ for rule in items(List {
+ bytes: inner,
+ span: rules,
+ }) {
+ if let Some(rule) = text(inner, field(inner, rule, b"rule")) {
+ css::image_urls(&rule, &mut push);
+ }
}
}
}
+ _ => {}
}
- let size = added.len() as u32 + removed;
- dom.insert(&added.into_iter().collect::<Vec<_>>());
- (orphans, size, failed)
}
-fn items(bytes: &[u8]) -> impl Iterator<Item = Span> + '_ {
- scan::locate_value(bytes, 0)
+/// A list as the player reads it, decoded when the event compressed it. `None` when it is empty or does not decode.
+fn decoded_list<'b>(inner: &'b [u8], span: Span, expansion: &'b Expansion) -> Option<List<'b>> {
+ if !scan::is_string(inner, span) {
+ return Some(List { bytes: inner, span });
+ }
+ let json = expansion.json(span)??;
+ Some(List {
+ bytes: json,
+ span: scan::locate_value(json, 0).ok()?,
+ })
+}
+
+fn items(list: List<'_>) -> impl Iterator<Item = Span> + '_ {
+ scan::array_items(list.bytes, list.span)
.ok()
- .and_then(|span| scan::array_items(bytes, span).ok())
.into_iter()
.flatten()
.filter_map(Result::ok)
@@ -416,6 +1561,8 @@ mod tests {
{"type": 3, "textContent": "hello", "id": 7},
element(8, "iframe", json!({}), json!([])),
element(9, "canvas", json!({}), json!([])),
+ element(11, "img", json!({"src": "https://cdn.example.com/a.png", "srcset": "https://cdn.example.com/[email protected] 2x, data:image/png;base64,AA 3x"}), json!([])),
+ element(12, "video", json!({"poster": "https://cdn.example.com/p.jpg"}), json!([])),
{"type": 2, "tagName": "div", "attributes": {}, "childNodes": [], "isShadowHost": true, "id": 10},
])),
]))], "id": 1}})
@@ -431,11 +1578,21 @@ mod tests {
};
let message = events(json!([event]));
let mut stats = BlockStats::default();
- DomInspector::default().observe(&message.inner, &message.events[0], "w", &mut stats);
+ let mut dom = DomInspector::default();
+ dom.observe(&message.inner, &message.events[0], "w", &mut stats);
+ // Remote image URLs go to the fetcher. The inline image in the srcset is the image scan's to move.
+ assert_eq!(
+ dom.take_image_urls(),
+ [
+ "https://cdn.example.com/a.png",
+ "https://cdn.example.com/[email protected]",
+ "https://cdn.example.com/p.jpg"
+ ]
+ );
assert_eq!(
(stats.dom_nodes, stats.dom_text_chars),
- (10, 5),
+ (12, 5),
"compressed: {compressed}"
);
assert_eq!((stats.remote_stylesheets, stats.inline_stylesheets), (1, 1));
@@ -446,7 +1603,7 @@ mod tests {
stats.videos,
stats.shadow_roots
),
- (1, 1, 0, 1)
+ (1, 1, 1, 1)
);
assert_eq!(stats.events_before_first_full_snapshot, 0);
}
@@ -464,6 +1621,9 @@ mod tests {
// An unknown parent, and a text change on a node removed by the same mutation's remove list later.
mutation(json!([{"parentId": 500, "node": {"type": 3, "id": 501}}]), json!([{"parentId": 6, "id": 7}]), json!([])),
mutation(json!([]), json!([]), json!([{"id": 7, "value": "gone"}, {"id": 22, "value": "kept"}])),
+ // The player's rrweb appends an addition whose next sibling is not there.
+ mutation(json!([{"parentId": 6, "nextId": 900, "node": {"type": 3, "id": 31}}, {"parentId": 6, "nextId": 33, "node": {"type": 3, "id": 32}}, {"parentId": 6, "nextId": -1, "node": {"type": 3, "id": 33}}]), json!([]), json!([])),
+ mutation(json!([]), json!([]), json!([{"id": 31, "value": "appended"}, {"id": 32, "value": "kept"}])),
]));
let mut dom = DomInspector::default();
let mut stats = BlockStats::default();
@@ -474,30 +1634,368 @@ mod tests {
assert_eq!(stats.orphan_mutations, 2);
}
+ fn mutation(adds: Value, removes: Value, texts: Value, attributes: Value) -> Value {
+ json!({"type": 3, "timestamp": 2, "data": {"source": 0, "adds": adds, "removes": removes, "texts": texts, "attributes": attributes}})
+ }
+
+ fn observe_all(
+ message: &crate::scan::message::Message,
+ window: &str,
+ ) -> (DomInspector, BlockStats) {
+ let mut dom = DomInspector::default();
+ let mut stats = BlockStats::default();
+ dom.start_message();
+ for event in &message.events {
+ dom.observe(&message.inner, event, window, &mut stats);
+ }
+ (dom, stats)
+ }
+
+ #[test]
+ fn removes_a_whole_subtree_and_follows_a_move() {
+ let message = events(json!([
+ {"type": 2, "timestamp": 1, "data": page()},
+ // Moves the img under the head, then removes the body with everything left under it.
+ mutation(json!([{"parentId": 3, "node": element(11, "img", json!({}), json!([]))}]), json!([{"parentId": 6, "id": 11}]), json!([]), json!([])),
+ mutation(json!([]), json!([{"parentId": 2, "id": 6}]), json!([]), json!([])),
+ mutation(json!([]), json!([]), json!([{"id": 7, "value": "gone"}]), json!([{"id": 11, "attributes": {"alt": "moved"}}, {"id": 9, "attributes": {"width": "1"}}])),
+ ]));
+ let (_, stats) = observe_all(&message, "w");
+ // The text node 7 and the canvas 9 went with the body. The img moved out of it first.
+ assert_eq!(stats.orphan_mutations, 2);
+ assert!(!stats.node_cap_reached);
+ }
+
+ #[test]
+ fn stops_checking_a_window_whose_snapshot_does_not_decode() {
+ let deep = format!(
+ r#"{{"node":{{"type":0,"childNodes":[{}{}],"id":1}}}}"#,
+ "[".repeat(1100),
+ "]".repeat(1100)
+ );
+ let deep: String = compression::gzip(deep.as_bytes())
+ .unwrap()
+ .iter()
+ .map(|&b| char::from(b))
+ .collect();
+ for data in [json!("not gzip"), json!(deep)] {
+ let message =
+ events(json!([{"type": 2, "timestamp": 1, "data": data, "cv": "2024-10"}]));
+ let (_, stats) = observe_all(&message, "w");
+ // A snapshot that does not decode is not a full snapshot, so the replay still waits for one.
+ assert_eq!(
+ (
+ stats.full_snapshots,
+ stats.events_before_first_full_snapshot
+ ),
+ (0, 1)
+ );
+ assert!(stats.node_cap_reached, "an unchecked window is flagged");
+ }
+ }
+
#[test]
fn counts_each_event_that_does_not_decode_once() {
let message = events(json!([
{"type": 2, "timestamp": 1, "data": page()},
{"type": 2, "timestamp": 2, "data": "not gzip", "cv": "2024-10"},
{"type": 3, "timestamp": 3, "data": {"source": 0, "adds": "not gzip", "removes": [], "texts": "not gzip", "attributes": []}, "cv": "2024-10"},
- {"type": 3, "timestamp": 4, "data": {"source": 0, "adds": sdk_cv(&json!([])), "removes": sdk_cv(&json!([])), "texts": sdk_cv(&json!([])), "attributes": sdk_cv(&json!([]))}, "cv": "2024-10"},
+ {"type": 3, "timestamp": 4, "data": {"source": 8, "adds": "not gzip", "removes": []}, "cv": "2024-10"},
+ {"type": 3, "timestamp": 5, "data": {"source": 0, "adds": sdk_cv(&json!([])), "removes": sdk_cv(&json!([])), "texts": sdk_cv(&json!([])), "attributes": sdk_cv(&json!([]))}, "cv": "2024-10"},
]));
- let mut dom = DomInspector::default();
- let mut stats = BlockStats::default();
- for event in &message.events {
- dom.observe(&message.inner, event, "w", &mut stats);
+ let (_, stats) = observe_all(&message, "w");
+ assert_eq!(stats.decode_failures, 3);
+ }
+
+ #[test]
+ fn ignores_events_the_player_drops() {
+ let text = |id: i64| {
+ mutation(
+ json!([]),
+ json!([]),
+ json!([{"id": id, "value": "x"}]),
+ json!([]),
+ )
+ };
+ let dropped = [
+ json!({"type": 2, "timestamp": 2, "data": {"node": null}}),
+ json!({"type": 3, "timestamp": 2, "cv": "2024-10", "data": {"source": 0, "adds": sdk_cv(&json!([{"parentId": 6, "node": {"type": 3, "id": 501}}])),
+ "removes": "not gzip", "texts": sdk_cv(&json!([])), "attributes": sdk_cv(&json!([]))}}),
+ ];
+ for event in dropped {
+ let (_, stats) = observe_all(&events(json!([event, text(7)])), "w");
+ assert_eq!(
+ (
+ stats.full_snapshots,
+ stats.events_before_first_full_snapshot
+ ),
+ (0, 2),
+ "{event}"
+ );
+ let (_, stats) = observe_all(
+ &events(
+ json!([{"type": 2, "timestamp": 1, "data": page()}, event, text(7), text(501)]),
+ ),
+ "w",
+ );
+ assert_eq!(
+ (
+ stats.full_snapshots,
+ stats.orphan_mutations,
+ stats.node_cap_reached
+ ),
+ (1, 1, false),
+ "{event}"
+ );
}
- assert_eq!(stats.decode_failures, 2);
+ }
- // An event that the message's decode budget skipped is not decoded again here.
+ #[test]
+ fn flags_a_window_whose_mutation_the_recorder_did_not_decode() {
let mut message = events(json!([
- {"type": 2, "timestamp": 1, "data": sdk_cv(&page()), "cv": "2024-10"},
+ {"type": 2, "timestamp": 1, "data": page()},
+ {"type": 3, "timestamp": 2, "cv": "2024-10", "data": {"source": 0, "adds": sdk_cv(&json!([{"parentId": 6, "node": {"type": 3, "id": 501}}])),
+ "removes": sdk_cv(&json!([])), "texts": sdk_cv(&json!([])), "attributes": sdk_cv(&json!([]))}},
]));
- message.decode_compressed_within(0);
+ message.events[1].expansion = Some(Expansion::Skipped);
+ let (_, stats) = observe_all(&message, "w");
+ assert!(stats.node_cap_reached);
+ }
+
+ #[test]
+ fn collects_remote_image_urls_wherever_the_page_references_them() {
+ let url = |name: &str| format!("https://cdn.example.com/{name}.png");
+ let snapshot = json!({"node": {"type": 0, "childNodes": [element(2, "html", json!({}), json!([
+ element(3, "style", json!({}), json!([{"type": 3, "textContent": format!(".a{{background:url(\"{}\")}} :root{{--x:url({})}}", url("style-text"), url("custom-property")), "id": 4}])),
+ element(5, "link", json!({"rel": "stylesheet", "_cssText": format!(".b{{background-image:image-set(url({}) 1x, url({}) 2x)}}", url("set-1x"), url("set-2x"))}), json!([])),
+ element(6, "div", json!({"style": format!("background: url('{}') no-repeat; color: red", url("style-attribute"))}), json!([])),
+ element(7, "svg", json!({}), json!([element(8, "image", json!({"href": url("svg-href"), "xlink:href": url("svg-xlink")}), json!([]))])),
+ element(9, "img", json!({"rr_src": url("rr-src")}), json!([])),
+ element(10, "img", json!({"src": url("pixel"), "width": "1", "height": 1}), json!([])),
+ element(11, "img", json!({"src": url("display-none"), "style": "display: none !important"}), json!([])),
+ element(12, "img", json!({"src": url("hidden"), "hidden": ""}), json!([])),
+ element(13, "picture", json!({}), json!([element(14, "source", json!({"srcset": format!("{} 2x", url("picture-source"))}), json!([]))])),
+ element(15, "video", json!({}), json!([element(16, "source", json!({"src": url("video-source")}), json!([]))])),
+ element(17, "img", json!({"data-src": url("lazy")}), json!([])),
+ element(18, "iframe", json!({"src": "https://example.com/frame"}), json!([])),
+ element(19, "img", json!({"srcset": format!("{} 640w,{} 2x", url("w_640,q_auto/srcset-comma"), url("srcset-second"))}), json!([])),
+ element(20, "img", json!({"src": url("shown-later"), "srcset": format!("{} 2x", url("shown-later-2x")), "hidden": ""}), json!([])),
+ element(21, "img", json!({"src": format!("https://cdn.example.com/{}.png", "a".repeat(MAX_URL_LEN))}), json!([])),
+ ]))], "id": 1}});
+ let message = events(json!([
+ // URLs do not wait for the first full snapshot.
+ mutation(json!([{"parentId": 1, "node": element(30, "img", json!({"src": url("before-snapshot")}), json!([]))}]), json!([]), json!([]), json!([])),
+ {"type": 2, "timestamp": 1, "data": snapshot},
+ // A lazy loader sets `src` later. The iframe is not an image.
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 17, "attributes": {"src": url("lazy")}}, {"id": 18, "attributes": {"src": url("frame")}}, {"id": 6, "attributes": {"style": format!("background-image:url({})", url("style-mutation"))}}])),
+ // Hidden imgs that a mutation reveals while it sets `src`. The pixel stays a pixel.
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 11, "attributes": {"style": {"display": false}, "src": url("revealed")}}, {"id": 12, "attributes": {"hidden": null, "src": url("unhidden")}}, {"id": 10, "attributes": {"src": url("still-pixel")}}])),
+ // An update that sets no source keeps the hidden img's sources.
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 20, "attributes": {"alt": "x"}}])),
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 20, "attributes": {"hidden": null}}])),
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 6, "attributes": {"style": {"background-image": [format!("url({})", url("style-object")), "important"], "background": format!("url({})", url("style-object-plain")), "color": "red", "mask-image": false}}}])),
+ // A `source` added on its own under a `picture`, one the page has or one the same mutation adds.
+ mutation(json!([{"parentId": 13, "node": element(40, "source", json!({"srcset": format!("{} 2x", url("lone-source"))}), json!([]))},
+ {"parentId": 41, "node": element(42, "source", json!({"srcset": url("same-mutation-source")}), json!([]))},
+ {"parentId": 6, "node": element(41, "picture", json!({}), json!([]))}]), json!([]), json!([]), json!([])),
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 42, "attributes": {"srcset": url("source-srcset-change")}}])),
+ // An img that moves keeps what it is, so a later `src` counts.
+ mutation(json!([{"parentId": 3, "node": element(9, "img", json!({}), json!([]))}]), json!([{"parentId": 2, "id": 9}]), json!([]), json!([])),
+ mutation(json!([]), json!([]), json!([]), json!([{"id": 9, "attributes": {"src": url("moved")}}])),
+ // New text in a `style` is CSS. Text elsewhere is not.
+ mutation(json!([]), json!([]), json!([{"id": 4, "value": format!(".a{{background:url({})}}", url("style-text-change"))}, {"id": 6, "value": format!("background:url({})", url("not-css"))}]), json!([])),
+ // Rules and declarations that a page sets through CSSOM, compressed or not.
+ {"type": 3, "timestamp": 3, "cv": "2024-10", "data": {"source": 8, "id": 3, "adds": sdk_cv(&json!([{"rule": format!(".c{{background:url({})}}", url("sheet-rule")), "index": 0}]))}},
+ {"type": 3, "timestamp": 3, "data": {"source": 8, "id": 3, "replaceSync": format!(".r{{cursor:url({}),auto}}", url("sheet-replace"))}},
+ {"type": 3, "timestamp": 3, "data": {"source": 13, "id": 3, "index": [0], "set": {"property": "background-image", "value": format!("url({})", url("declaration"))}}},
+ {"type": 3, "timestamp": 3, "data": {"source": 13, "id": 3, "index": [0], "set": {"property": "--x", "value": format!("url({})", url("custom-declaration"))}}},
+ {"type": 3, "timestamp": 3, "data": {"source": 15, "id": 1, "styleIds": [1], "styles": [{"styleId": 1, "rules": [{"rule": format!(".d{{background:url({})}}", url("adopted"))}]}]}},
+ ]));
+ let (mut dom, _) = observe_all(&message, "w");
+ // A hidden or one-pixel img is not fetched, but the block holds its URL, so the writer replaces it too.
+ let remote = dom.take_remote_urls().into_urls();
+ for name in ["hidden", "display-none", "pixel", "shown-later", "lazy"] {
+ assert!(remote.contains(&url(name)), "{name}");
+ }
+ let mut found = dom.take_image_urls();
+ found.sort();
+ let mut expected: Vec<String> = [
+ "before-snapshot",
+ "style-text",
+ "set-2x",
+ "style-attribute",
+ "svg-href",
+ "svg-xlink",
+ "rr-src",
+ "picture-source",
+ "lazy",
+ "style-mutation",
+ "revealed",
+ "unhidden",
+ "moved",
+ "style-text-change",
+ "sheet-rule",
+ "sheet-replace",
+ "declaration",
+ "adopted",
+ "w_640,q_auto/srcset-comma",
+ "srcset-second",
+ "shown-later",
+ "shown-later-2x",
+ "style-object",
+ "style-object-plain",
+ "lone-source",
+ "same-mutation-source",
+ "source-srcset-change",
+ ]
+ .into_iter()
+ .map(url)
+ .collect();
+ expected.sort();
+ assert_eq!(found, expected);
+ }
+
+ #[test]
+ fn caps_the_sources_a_hidden_img_keeps() {
+ let srcset = |count: usize| {
+ (0..count)
+ .map(|i| format!("https://cdn.example.com/{i}.png {}w", i + 1))
+ .collect::<Vec<_>>()
+ .join(", ")
+ };
+ let retained = |count: usize| {
+ let snapshot = json!({"node": {"type": 0, "childNodes": [element(2, "img", json!({"srcset": srcset(count), "hidden": ""}), json!([]))], "id": 1}});
+ let (dom, _) = observe_all(
+ &events(json!([{"type": 2, "timestamp": 1, "data": snapshot}])),
+ "w",
+ );
+ dom.retained_bytes()
+ };
+ assert!(retained(1) < retained(MAX_IMAGE_URLS));
+ assert_eq!(retained(MAX_IMAGE_URLS), retained(10 * MAX_IMAGE_URLS));
+ }
+
+ #[test]
+ fn stops_naming_remote_urls_past_a_block_limit() {
+ let url = |i: usize, len: usize| {
+ let mut url = format!("https://cdn.example.com/{i}/");
+ url.extend(std::iter::repeat_n('a', len - url.len()));
+ url
+ };
+ let limit = |urls: &mut dyn Iterator<Item = String>| {
+ let mut remote = RemoteUrls::default();
+ urls.for_each(|u| remote.insert(&u));
+ remote.limit
+ };
+ let longest = MAX_REMOTE_URL_BYTES;
+ let most_long = MAX_BLOCK_REMOTE_URL_BYTES / longest;
+ for (urls, expected) in [
+ (vec![url(0, longest)], None),
+ (vec![url(0, longest + 1)], Some(UrlLimit::UrlLength)),
+ (
+ (0..MAX_BLOCK_REMOTE_URLS).map(|i| url(i, 40)).collect(),
+ None,
+ ),
+ (
+ (0..=MAX_BLOCK_REMOTE_URLS).map(|i| url(i, 40)).collect(),
+ Some(UrlLimit::UrlCount),
+ ),
+ ((0..most_long).map(|i| url(i, longest)).collect(), None),
+ (
+ (0..=most_long).map(|i| url(i, longest)).collect(),
+ Some(UrlLimit::UrlBytes),
+ ),
+ ] {
+ assert_eq!(limit(&mut urls.into_iter()), expected);
+ }
+
+ // A mutation past the attribute cap is not read to its end.
+ let attributes = |count: usize| {
+ let items = vec![r#"{"id":1,"attributes":{}}"#; count].join(",");
+ let inner = format!(
+ r#"{{"properties":{{"$session_id":"s","$snapshot_items":[{{"type":3,"timestamp":2,"data":{{"source":0,"attributes":[{items}]}}}}]}}}}"#
+ );
+ let message = read_message(json!({ "data": inner }).to_string().into_bytes()).unwrap();
+ observe_all(&message, "w").0.take_remote_urls().limit
+ };
+ assert_eq!(attributes(MAX_ATTRIBUTE_ITEMS), None);
+ assert_eq!(
+ attributes(MAX_ATTRIBUTE_ITEMS + 1),
+ Some(UrlLimit::AttributeItems)
+ );
+ }
+
+ #[test]
+ fn caps_distinct_remote_image_urls_per_message() {
+ let img = |i: i64, src: String| json!({"parentId": 1, "node": element(i, "img", json!({"src": src}), json!([]))});
+ // Repeats and inline images come first and do not use up the cap.
+ let mut adds: Vec<Value> = (0..600)
+ .map(|i| img(i, "https://cdn.example.com/icon.png".to_owned()))
+ .chain((600..1200).map(|i| img(i, "data:image/png;base64,AA".to_owned())))
+ .collect();
+ adds.extend((0..600).map(|i| img(2000 + i, format!("https://cdn.example.com/{i}.png"))));
+ let message = events(json!([
+ mutation(json!(adds[..1500]), json!([]), json!([]), json!([])),
+ mutation(json!(adds[1500..]), json!([]), json!([]), json!([])),
+ ]));
+ let (mut dom, _) = observe_all(&message, "w");
+ let found = dom.take_image_urls();
+ assert_eq!(found.len(), MAX_IMAGE_URLS);
+ // The cap limits the fetch jobs only. The writer replaces every remote URL in the block.
+ assert_eq!(dom.take_remote_urls().into_urls().len(), 601);
+ assert_eq!(
+ found[..2],
+ [
+ "https://cdn.example.com/icon.png",
+ "https://cdn.example.com/0.png"
+ ]
+ );
+ }
+
+ #[test]
+ fn compacts_the_child_lists_that_repeated_adds_grow() {
+ let mut dom = WindowDom::default();
+ for _ in 0..100_000 {
+ dom.insert(2, Some(1));
+ }
+ assert!(dom.children[&1].len() <= 4097);
+ let capacity: usize = dom.children.values().map(Vec::capacity).sum();
+ assert!(dom.retained_bytes() >= capacity * std::mem::size_of::<i64>());
+ }
+
+ #[test]
+ fn flags_a_window_that_returns_after_eviction() {
+ let snapshot = json!({"type": 2, "timestamp": 1, "data": page()});
let mut dom = DomInspector::default();
let mut stats = BlockStats::default();
- dom.observe(&message.inner, &message.events[0], "w", &mut stats);
- assert_eq!((stats.decode_failures, dom.has_snapshot()), (1, false));
+ let message = events(json!([
+ snapshot,
+ mutation(
+ json!([]),
+ json!([]),
+ json!([{"id": 7, "value": "x"}]),
+ json!([])
+ )
+ ]));
+ for window in 0..=MAX_WINDOWS {
+ dom.observe(
+ &message.inner,
+ &message.events[0],
+ &window.to_string(),
+ &mut stats,
+ );
+ }
+ assert!(!stats.node_cap_reached);
+ dom.observe(&message.inner, &message.events[1], "0", &mut stats);
+ assert!(stats.node_cap_reached);
+
+ for window in 0..MAX_WINDOWS {
+ let other = format!("other-{window}");
+ dom.observe(&message.inner, &message.events[1], &other, &mut stats);
+ }
+ let mut stats = BlockStats::default();
+ dom.observe(&message.inner, &message.events[1], "0", &mut stats);
+ assert!(stats.node_cap_reached);
}
#[test]
diff --git a/rust/ai-research/replay-core-v4/src/inspect/events.rs b/rust/ai-research/replay-core-v4/src/inspect/events.rs
index 2099620f2594..b5066041ea16 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/events.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/events.rs
@@ -112,7 +112,6 @@ impl EventCounter {
}
let Some(data) = event.data else { return false };
match (event.kind, event.source) {
- (Some(FULL_SNAPSHOT), _) => stats.full_snapshots += 1,
(Some(META | CUSTOM), _) => {
let [href, payload, tag, width, height] = fields(
inner,
@@ -549,15 +548,7 @@ mod tests {
(stats.viewport_width, stats.viewport_height),
(Some(1280), Some(720))
);
- assert_eq!(
- (
- stats.full_snapshots,
- stats.clicks,
- stats.touches,
- stats.keypresses
- ),
- (1, 2, 2, 1)
- );
+ assert_eq!((stats.clicks, stats.touches, stats.keypresses), (2, 2, 1));
// Every mouse interaction counts, of any type, and a touch move is a touch too.
assert_eq!((stats.mouse_interactions, stats.touch_moves), (3, 1));
assert!(stats.touch_input);
diff --git a/rust/ai-research/replay-core-v4/src/inspect/mod.rs b/rust/ai-research/replay-core-v4/src/inspect/mod.rs
index b21f1e1f90c3..8836d7d3ff28 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/mod.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/mod.rs
@@ -1,6 +1,7 @@
//! Sampling metadata for the v4 block index, computed in the same byte pass as image extraction.
pub mod clicks;
+pub mod css;
pub mod dom;
pub mod events;
pub mod rrweb;
diff --git a/rust/ai-research/replay-core-v4/src/inspect/rrweb.rs b/rust/ai-research/replay-core-v4/src/inspect/rrweb.rs
index 8603cc73f7ce..5705afaa9474 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/rrweb.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/rrweb.rs
@@ -14,8 +14,11 @@ pub const VIEWPORT_RESIZE: u8 = 4;
pub const INPUT: u8 = 5;
pub const TOUCH_MOVE: u8 = 6;
pub const MEDIA_INTERACTION: u8 = 7;
+pub const STYLE_SHEET_RULE: u8 = 8;
pub const DRAG: u8 = 12;
+pub const STYLE_DECLARATION: u8 = 13;
pub const SELECTION: u8 = 14;
+pub const ADOPTED_STYLE_SHEET: u8 = 15;
pub const CLICK: u8 = 2;
pub const CONTEXT_MENU: u8 = 3;
diff --git a/rust/ai-research/replay-core-v4/src/inspect/session.rs b/rust/ai-research/replay-core-v4/src/inspect/session.rs
index 6235cc771112..f177c7bc0a11 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/session.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/session.rs
@@ -3,7 +3,7 @@
use std::sync::Arc;
use super::clicks::{ClickKind, ClickTracker};
-use super::dom::DomInspector;
+use super::dom::{DomInspector, RemoteUrls, UrlLimit};
use super::events::{fields, number, Activity, EventCounter};
use super::rrweb::{
is_click, CUSTOM, FULL_SNAPSHOT, INCREMENTAL_SNAPSHOT, META, MOUSE_INTERACTION, MUTATION,
@@ -47,17 +47,54 @@ pub struct SessionInspector {
pub struct BlockInspection {
counter: EventCounter,
moments: Vec<Moment>,
+ image_urls: Vec<String>,
+ remote_urls: RemoteUrls,
events: u32,
}
+/// What the inspector learned about one block.
+pub struct Inspected {
+ pub stats: BlockStats,
+ pub moments: Vec<Moment>,
+ /// Remote image URLs the block's DOM referenced, for the image fetcher.
+ pub image_urls: Vec<String>,
+ /// Every remote URL in an image slot of the block, which the writer replaces with its reference.
+ pub remote_urls: Vec<String>,
+ /// Set when `remote_urls` stops short, so that the block must not be stored.
+ pub url_limit: Option<UrlLimit>,
+}
+
impl BlockInspection {
- pub fn finish(self) -> (BlockStats, Vec<Moment>) {
- (self.counter.finish(), self.moments)
+ pub fn finish(self) -> Inspected {
+ Inspected {
+ stats: self.counter.finish(),
+ moments: self.moments,
+ image_urls: self.image_urls,
+ url_limit: self.remote_urls.limit,
+ remote_urls: self.remote_urls.into_urls(),
+ }
}
}
impl SessionInspector {
+ /// Drops what the session learned about its DOM and keeps its activity, clicks and page: its blocks are cold
+ /// starts until a full snapshot, and each window's mutations go unchecked until that window's next snapshot.
+ pub fn evict_dom(&mut self) {
+ self.dom = DomInspector::after_eviction();
+ self.decided = true;
+ self.cold = true;
+ self.undecided = 0;
+ }
+
+ pub fn retained_bytes(&self) -> usize {
+ std::mem::size_of::<Self>()
+ + self.dom.retained_bytes()
+ + self.activity.retained_bytes()
+ + self.last_href.as_ref().map_or(0, String::capacity)
+ }
+
pub fn observe_message(&mut self, block: &mut BlockInspection, message: &Message) {
+ self.dom.start_message();
let window = message.window_id.clone().unwrap_or_default();
if let Some(id) = message.window_id.as_deref() {
let ids = &mut block.counter.stats.window_ids;
@@ -71,6 +108,7 @@ impl SessionInspector {
for event in &message.events {
self.observe(block, &message.inner, event, &window);
}
+ self.dom.finish_message();
}
fn observe(
@@ -108,7 +146,9 @@ impl SessionInspector {
let observed = self
.dom
.observe(inner, event, window, &mut block.counter.stats);
- if event.kind == Some(FULL_SNAPSHOT) {
+ block.image_urls.extend(self.dom.take_image_urls());
+ block.remote_urls.extend(self.dom.take_remote_urls());
+ if observed.full_snapshot {
self.cold = false;
}
let stats = &mut block.counter.stats;
@@ -197,7 +237,8 @@ mod tests {
fn inspect(session: &mut SessionInspector, message: &Message) -> (BlockStats, Vec<Moment>) {
let mut block = BlockInspection::default();
session.observe_message(&mut block, message);
- block.finish()
+ let inspected = block.finish();
+ (inspected.stats, inspected.moments)
}
fn big_mutation(ts: i64) -> Value {
@@ -259,7 +300,7 @@ mod tests {
session.observe_message(&mut block, &message_in(Some(&window), moved.clone()));
}
let windows: Vec<String> = (0..MAX_WINDOW_IDS).map(|w| format!("w{w}")).collect();
- assert_eq!(block.finish().0.window_ids, windows);
+ assert_eq!(block.finish().stats.window_ids, windows);
}
#[test]
@@ -353,8 +394,10 @@ mod tests {
big_mutation(1),
{"type": 3, "timestamp": 2, "data": {"source": 1, "positions": []}},
]));
- let (stats, _) = inspect(&mut SessionInspector::default(), &mid_session);
+ let (stats, moments) = inspect(&mut SessionInspector::default(), &mid_session);
assert!(stats.cold_start);
+ let kinds: Vec<_> = moments.iter().map(|m| (m.kind, m.event_index)).collect();
+ assert_eq!(kinds, [("dom_change", 0)]);
// Nothing here says the session cannot play: its snapshot came before this process saw it.
assert_eq!(
(
diff --git a/rust/ai-research/replay-core-v4/src/inspect/stats.rs b/rust/ai-research/replay-core-v4/src/inspect/stats.rs
index 732645c5ab41..aef9dcbdacdb 100644
--- a/rust/ai-research/replay-core-v4/src/inspect/stats.rs
+++ b/rust/ai-research/replay-core-v4/src/inspect/stats.rs
@@ -16,6 +16,7 @@ pub struct BlockStats {
pub byte_size: u64,
pub host: Option<String>,
+ /// Full snapshots that decoded.
pub full_snapshots: u32,
/// Events, in any window, before the session's first full snapshot that decoded. A replay shows nothing until then.
/// Events of a session this process joined midway do not count.
diff --git a/rust/ai-research/replay-recorder-v4/Cargo.toml b/rust/ai-research/replay-recorder-v4/Cargo.toml
index 25184f82cfb3..097e412359d0 100644
--- a/rust/ai-research/replay-recorder-v4/Cargo.toml
+++ b/rust/ai-research/replay-recorder-v4/Cargo.toml
@@ -16,6 +16,7 @@ common-metrics = { path = "../../common/metrics" }
lifecycle = { path = "../../common/lifecycle" }
replay-core-v4 = { path = "../replay-core-v4" }
+aho-corasick = { workspace = true }
arc-swap = { workspace = true }
# The major version deltalite links, so the workspace builds one arrow.
arrow-array = "58"
@@ -30,6 +31,7 @@ brotlic = "0.8"
chrono = { workspace = true }
envconfig = { workspace = true }
metrics = { workspace = true }
+moka = { workspace = true }
parquet = "58"
rand = { workspace = true }
rdkafka = { workspace = true }
@@ -39,6 +41,7 @@ thiserror = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }
+url = { workspace = true }
[dev-dependencies]
aes-gcm = "0.10"
diff --git a/rust/ai-research/replay-recorder-v4/src/batch.rs b/rust/ai-research/replay-recorder-v4/src/batch.rs
index 367eb09a891c..a3f353c8eb32 100644
--- a/rust/ai-research/replay-recorder-v4/src/batch.rs
+++ b/rust/ai-research/replay-recorder-v4/src/batch.rs
@@ -3,6 +3,7 @@
use std::collections::{BTreeMap, HashMap};
use std::time::{Duration, Instant};
+use replay_core_v4::inspect::dom::UrlLimit;
use replay_core_v4::inspect::session::{BlockInspection, Moment, SessionInspector};
use replay_core_v4::inspect::stats::BlockStats;
use replay_core_v4::scan::message::Message;
@@ -25,6 +26,12 @@ pub struct Block {
pub messages: Vec<Message>,
pub stats: BlockStats,
pub moments: Vec<Moment>,
+ /// Remote image URLs the block's DOM referenced.
+ pub image_urls: Vec<String>,
+ /// Every remote URL in an image slot of the block, which the writer replaces with its reference.
+ pub remote_urls: Vec<String>,
+ /// Set when the inspector stopped short of naming every remote URL, so that the block must not be stored.
+ pub url_limit: Option<UrlLimit>,
}
pub struct Batch {
@@ -110,12 +117,15 @@ impl Inspectors {
for message in &pending.messages {
inspector.observe_message(&mut block, message);
}
- let (stats, moments) = block.finish();
+ let inspected = block.finish();
blocks.push(Block {
session,
messages: pending.messages,
- stats,
- moments,
+ stats: inspected.stats,
+ moments: inspected.moments,
+ image_urls: inspected.image_urls,
+ remote_urls: inspected.remote_urls,
+ url_limit: inspected.url_limit,
});
}
(blocks, batch.offsets)
diff --git a/rust/ai-research/replay-recorder-v4/src/config.rs b/rust/ai-research/replay-recorder-v4/src/config.rs
index 39b6efc0510b..985ae8c10789 100644
--- a/rust/ai-research/replay-recorder-v4/src/config.rs
+++ b/rust/ai-research/replay-recorder-v4/src/config.rs
@@ -56,6 +56,13 @@ pub struct Config {
#[envconfig(from = "AI_RESEARCH_V4_IMAGES_BUCKET", default = "")]
pub images_bucket: String,
+ /// Where remote image URLs go for the v4 image fetcher.
+ #[envconfig(
+ from = "AI_RESEARCH_V4_IMAGE_FETCH_TOPIC",
+ default = "ai_research_v4_image_fetch"
+ )]
+ pub image_fetch_topic: String,
+
#[envconfig(default = "9104")]
pub metrics_port: u16,
}
diff --git a/rust/ai-research/replay-recorder-v4/src/consumer.rs b/rust/ai-research/replay-recorder-v4/src/consumer.rs
index 20a0523f6b7a..5475ca0beafd 100644
--- a/rust/ai-research/replay-recorder-v4/src/consumer.rs
+++ b/rust/ai-research/replay-recorder-v4/src/consumer.rs
@@ -22,7 +22,11 @@ use crate::batch::{Batch, Block, Inspectors, SessionKey};
use crate::process::{admit, read, sampled};
use crate::store::BlobStore;
use crate::teams::TeamCache;
+use crate::urls::{fetch_jobs, records};
use crate::write::{prepare, write_block_index, write_blocks, write_images, WriteError};
+use rdkafka::message::{Header, OwnedHeaders};
+use rdkafka::producer::{FutureProducer, FutureRecord};
+use rdkafka::util::Timeout;
/// Records the partitions each rebalance takes away, so the loop can drop what it buffered for them.
pub struct RebalanceContext {
@@ -126,6 +130,11 @@ pub struct Writer {
pub store: Arc<dyn BlobStore>,
pub rrweb_bucket: String,
pub images_bucket: String,
+ pub producer: FutureProducer,
+ pub image_fetch_topic: String,
+ /// Remote image references this process sent to the fetcher, by UTC day. A reference goes out again each day, so
+ /// the fetcher sees it within every refresh interval and keeps the image as long as the blocks that reference it.
+ pub sent_urls: moka::sync::Cache<(String, String), ()>,
}
#[derive(Debug, thiserror::Error)]
@@ -257,6 +266,17 @@ async fn flush(blocks: &mut [Block], writer: Option<&Writer>) -> Result<(), Flus
let keys = writer.keys.keys_for_flush(&sessions, &day).await?;
counter!("ai_research_v4_recorder_dropped_sessions_total").increment(keys.dropped.len() as u64);
let prepared = prepare(blocks, &keys, month);
+ // Before the index is written: building the jobs counts each block's image URLs into its stats.
+ // A dropped block's images are not stored, so the fetcher does not fetch them.
+ let kept = blocks
+ .iter_mut()
+ .zip(&prepared.kept)
+ .filter_map(|(block, &kept)| kept.then_some(block));
+ let jobs = fetch_jobs(kept, &keys, month, now.timestamp_millis(), &|reference| {
+ writer
+ .sent_urls
+ .contains_key(&(day.clone(), reference.to_owned()))
+ });
let rows = write_images(
&prepared.images,
&keys,
@@ -289,5 +309,51 @@ async fn flush(blocks: &mut [Block], writer: Option<&Writer>) -> Result<(), Flus
now,
)
.await?;
+ produce_jobs(writer, jobs, &day, now.timestamp_millis()).await;
Ok(())
}
+
+/// Sends the flush's fetch jobs and waits for their delivery before the flush commits, as the v3 mirror does. A send
+/// that fails does not fail the flush, because its blocks are stored by then. The references it did not send stay
+/// unmarked, so a later flush that sees them sends them again.
+async fn produce_jobs(
+ writer: &Writer,
+ jobs: std::collections::BTreeMap<String, Vec<serde_json::Value>>,
+ day: &str,
+ now_ms: i64,
+) {
+ let captured_at = now_ms.to_string();
+ let records = records(jobs);
+ let total: usize = records
+ .iter()
+ .map(|(_, _, references)| references.len())
+ .sum();
+ let mut sent = Vec::new();
+ for (domain, payload, references) in records {
+ let headers = OwnedHeaders::new().insert(Header {
+ key: "capture-timestamp-ms",
+ value: Some(&captured_at),
+ });
+ let record = FutureRecord::to(&writer.image_fetch_topic)
+ .key(&domain)
+ .payload(&payload)
+ .headers(headers);
+ if let Err((error, _)) = writer
+ .producer
+ .send(record, Timeout::After(Duration::from_secs(30)))
+ .await
+ {
+ // The next record would wait as long on the same broker.
+ tracing::warn!(%error, "sending image fetch jobs failed");
+ break;
+ }
+ sent.extend(references);
+ }
+ counter!("ai_research_v4_recorder_image_fetch_jobs_total").increment(sent.len() as u64);
+ counter!("ai_research_v4_recorder_image_fetch_jobs_unsent_total")
+ .increment((total - sent.len()) as u64);
+ for reference in sent {
+ writer.sent_urls.insert((day.to_owned(), reference), ());
+ }
+ metrics::gauge!("ai_research_v4_recorder_sent_urls").set(writer.sent_urls.entry_count() as f64);
+}
diff --git a/rust/ai-research/replay-recorder-v4/src/lib.rs b/rust/ai-research/replay-recorder-v4/src/lib.rs
index e03ec9ea5f19..b3b3f850faf8 100644
--- a/rust/ai-research/replay-recorder-v4/src/lib.rs
+++ b/rust/ai-research/replay-recorder-v4/src/lib.rs
@@ -6,6 +6,8 @@ pub mod config;
pub mod consumer;
pub mod index;
pub mod process;
+pub mod rewrite;
pub mod store;
pub mod teams;
+pub mod urls;
pub mod write;
diff --git a/rust/ai-research/replay-recorder-v4/src/main.rs b/rust/ai-research/replay-recorder-v4/src/main.rs
index 4358f918b1b4..728dcc074838 100644
--- a/rust/ai-research/replay-recorder-v4/src/main.rs
+++ b/rust/ai-research/replay-recorder-v4/src/main.rs
@@ -144,6 +144,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
store: Arc::new(S3Store::new(aws_sdk_s3::Client::new(&aws))),
rrweb_bucket: config.rrweb_bucket.clone(),
images_bucket: config.images_bucket.clone(),
+ producer: rdkafka::ClientConfig::new()
+ .set("bootstrap.servers", &config.kafka.kafka_hosts)
+ .set("compression.codec", "lz4")
+ .set("linger.ms", "20")
+ .create()?,
+ image_fetch_topic: config.image_fetch_topic.clone(),
+ sent_urls: replay_recorder_v4::urls::sent_urls(500_000),
})
} else {
tracing::info!("writes are off: the recorder stores nothing");
diff --git a/rust/ai-research/replay-recorder-v4/src/rewrite.rs b/rust/ai-research/replay-recorder-v4/src/rewrite.rs
new file mode 100644
index 000000000000..b015ff7df02d
--- /dev/null
+++ b/rust/ai-research/replay-recorder-v4/src/rewrite.rs
@@ -0,0 +1,340 @@
+//! Replaces the remote image URLs of a stored block with their `imageurl:v4` references, as v3 replaced them. A URL the
+//! policy declines becomes a marker that names the reason, so that no credential, signature or private host stays in
+//! the block. The inspector names the URLs: those in image slots, CSS included.
+
+use std::borrow::Cow;
+
+use aho_corasick::{AhoCorasick, AhoCorasickKind, MatchKind};
+use metrics::counter;
+use replay_core_v4::bytescan::{unescape, write_json_string};
+use replay_core_v4::seal::image_url_key;
+
+use crate::urls::url_reference;
+
+/// The bytes with each JSON string that holds an escape `write_json_string` does not write, such as `\/` or `\u0041`,
+/// written again as it writes them. Capture writes events that way, but the JSON inside a `cv` payload arrives as the
+/// page wrote it, so a URL could hide from the rewrite behind an escape.
+pub fn canonical_strings(bytes: &[u8]) -> Cow<'_, [u8]> {
+ if !bytes.contains(&b'\\') {
+ return Cow::Borrowed(bytes);
+ }
+ let mut out: Option<Vec<u8>> = None;
+ let mut copied_to = 0;
+ let mut position = 0;
+ while let Some(start) = bytes[position..]
+ .iter()
+ .position(|&b| b == b'"')
+ .map(|at| position + at)
+ {
+ let mut end = start + 1;
+ let mut canonical = true;
+ while end < bytes.len() && bytes[end] != b'"' {
+ if bytes[end] == b'\\' {
+ match bytes.get(end + 1) {
+ Some(b'"' | b'\\' | b'b' | b'f' | b'n' | b'r' | b't') => {}
+ Some(b'u') => canonical &= is_written_escape(bytes.get(end + 2..end + 6)),
+ _ => canonical = false,
+ }
+ end += 1;
+ }
+ end += 1;
+ }
+ if end >= bytes.len() {
+ break;
+ }
+ if !canonical {
+ if let Ok(text) = unescape(bytes, (start, end + 1)) {
+ let out = out.get_or_insert_with(|| Vec::with_capacity(bytes.len()));
+ out.extend_from_slice(&bytes[copied_to..start]);
+ write_json_string(&text, out);
+ copied_to = end + 1;
+ }
+ }
+ position = end + 1;
+ }
+ match out {
+ Some(mut out) => {
+ out.extend_from_slice(&bytes[copied_to..]);
+ Cow::Owned(out)
+ }
+ None => Cow::Borrowed(bytes),
+ }
+}
+
+/// Whether `write_json_string` writes this `\u` escape: a control character without a short escape, in lowercase hex.
+fn is_written_escape(hex: Option<&[u8]>) -> bool {
+ let Some(&[b'0', b'0', high, low]) = hex else {
+ return false;
+ };
+ let digit = |b: u8| matches!(b, b'0'..=b'9' | b'a'..=b'f');
+ digit(high)
+ && digit(low)
+ && high <= b'1'
+ && !matches!((high, low), (b'0', b'8' | b'9' | b'a' | b'c' | b'd'))
+}
+
+/// What a declined URL becomes. The reason is the policy's metric label.
+pub fn declined_marker(reason: &str) -> String {
+ format!("imageurl:v4:declined:{reason}")
+}
+
+/// A byte that a URL can go on with. A match next to one is part of a longer URL, so it stays as it is. A comma, a
+/// parenthesis or a quote can be in a URL too, but in a srcset or a CSS `url()` it ends one.
+fn continues_url(byte: u8) -> bool {
+ byte.is_ascii_alphanumeric() || b"-._~/?#@!$&*+=%:;[]".contains(&byte)
+}
+
+/// Whether the bytes before `at` end with a JSON escape, such as the `\n` of a multi-line srcset. The escape's last
+/// letter is not part of the URL that follows it.
+fn ends_with_escape(bytes: &[u8], at: usize) -> bool {
+ let escaped = |letter: usize| {
+ bytes[..letter]
+ .iter()
+ .rev()
+ .take_while(|&&b| b == b'\\')
+ .count()
+ % 2
+ == 1
+ };
+ let short = at >= 2 && b"\"\\/bfnrt".contains(&bytes[at - 1]) && escaped(at - 1);
+ let unicode = at >= 6
+ && bytes[at - 5] == b'u'
+ && bytes[at - 4..at].iter().all(u8::is_ascii_hexdigit)
+ && escaped(at - 5);
+ short || unicode
+}
+
+struct Target {
+ replacement: Vec<u8>,
+ /// The policy's reason, for a declined URL.
+ declined: Option<&'static str>,
+ found: bool,
+}
+
+pub struct UrlRewrite {
+ matcher: Option<AhoCorasick>,
+ /// The declined URLs alone. `apply` passes over a copy inside a longer URL, so the bytes it returns are scanned
+ /// again for them.
+ declined: Option<AhoCorasick>,
+ targets: Vec<Target>,
+ /// Bytes that `apply` returned still hold a declined URL.
+ declined_kept: bool,
+}
+
+impl UrlRewrite {
+ /// `team_key` is the team's month key for `key_month`, the write month, as for the fetch jobs.
+ pub fn new(urls: &[String], team_id: i64, key_month: &str, team_key: &[u8; 32]) -> Self {
+ let url_key = image_url_key(team_key);
+ let mut patterns = Vec::with_capacity(urls.len());
+ let mut targets = Vec::with_capacity(urls.len());
+ for url in urls {
+ // The block holds the URL as a JSON string holds it.
+ let mut escaped = Vec::with_capacity(url.len() + 2);
+ write_json_string(url, &mut escaped);
+ patterns.push(escaped[1..escaped.len() - 1].to_vec());
+ let (replacement, declined) = match url_reference(url, team_id, key_month, &url_key) {
+ Ok((_, reference)) => (reference, None),
+ Err(decline) => (declined_marker(decline.label()), Some(decline.label())),
+ };
+ targets.push(Target {
+ replacement: replacement.into_bytes(),
+ declined,
+ found: false,
+ });
+ }
+ let matcher = (!patterns.is_empty())
+ .then(|| {
+ // A DFA over long URLs can take hundreds of times their bytes. A contiguous NFA takes about ten.
+ AhoCorasick::builder()
+ .kind(Some(AhoCorasickKind::ContiguousNFA))
+ .match_kind(MatchKind::LeftmostLongest)
+ .build(&patterns)
+ .ok()
+ })
+ .flatten();
+ let declined: Vec<&[u8]> = patterns
+ .iter()
+ .zip(&targets)
+ .filter(|(_, target)| target.declined.is_some())
+ .map(|(pattern, _)| pattern.as_slice())
+ .collect();
+ let declined = (!declined.is_empty())
+ .then(|| {
+ AhoCorasick::builder()
+ .kind(Some(AhoCorasickKind::ContiguousNFA))
+ .build(declined)
+ .ok()
+ })
+ .flatten();
+ Self {
+ matcher,
+ declined,
+ targets,
+ declined_kept: false,
+ }
+ }
+
+ /// The bytes with each URL replaced. Returns the input when it holds none.
+ pub fn apply<'b>(&mut self, bytes: &'b [u8]) -> Cow<'b, [u8]> {
+ let Some(matcher) = &self.matcher else {
+ return Cow::Borrowed(bytes);
+ };
+ let mut out: Option<Vec<u8>> = None;
+ let mut copied_to = 0;
+ for found in matcher.find_iter(bytes) {
+ let (start, end) = (found.start(), found.end());
+ if start.checked_sub(1).is_some_and(|before| {
+ continues_url(bytes[before]) && !ends_with_escape(bytes, start)
+ }) || bytes.get(end).is_some_and(|&after| continues_url(after))
+ {
+ continue;
+ }
+ let target = &mut self.targets[found.pattern().as_usize()];
+ target.found = true;
+ let out = out.get_or_insert_with(|| Vec::with_capacity(bytes.len()));
+ out.extend_from_slice(&bytes[copied_to..start]);
+ out.extend_from_slice(&target.replacement);
+ copied_to = end;
+ }
+ let out = match out {
+ Some(mut out) => {
+ out.extend_from_slice(&bytes[copied_to..]);
+ Cow::Owned(out)
+ }
+ None => Cow::Borrowed(bytes),
+ };
+ if let Some(declined) = &self.declined {
+ self.declined_kept |= declined.is_match(out.as_ref());
+ }
+ out
+ }
+
+ /// Counts the block's URLs. One the block does not hold as the inspector read it, for example with a CSS escape,
+ /// stays as it arrived. Returns false when a URL the policy declines stays, unreplaced or as a second copy that
+ /// `apply` passed over, because the block must not be stored then.
+ pub fn finish(self) -> bool {
+ let mut safe = !self.declined_kept;
+ for target in self.targets {
+ safe &= target.found || target.declined.is_none();
+ let outcome = match (target.found, target.declined) {
+ (false, _) => "unrewritten",
+ (true, None) => "rewritten",
+ (true, Some(_)) => "declined",
+ };
+ counter!(
+ "ai_research_v4_recorder_image_url_rewrites_total",
+ "outcome" => outcome,
+ "reason" => target.declined.unwrap_or("none"),
+ )
+ .increment(1);
+ }
+ safe
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const TEAM_KEY: [u8; 32] = [6; 32];
+
+ fn rewrite(urls: &[&str], bytes: &str) -> String {
+ let urls: Vec<String> = urls.iter().map(|u| (*u).to_owned()).collect();
+ let mut rewrite = UrlRewrite::new(&urls, 7, "2026-10", &TEAM_KEY);
+ String::from_utf8(rewrite.apply(bytes.as_bytes()).into_owned()).unwrap()
+ }
+
+ fn reference(url: &str) -> String {
+ url_reference(url, 7, "2026-10", &image_url_key(&TEAM_KEY))
+ .unwrap()
+ .1
+ }
+
+ #[test]
+ fn keeps_srcset_and_css_syntax_while_it_replaces_each_url() {
+ let (a, b) = (
+ "https://cdn.example.com/w_640,q_auto/a.png",
+ "https://cdn.example.com/b.png",
+ );
+ let event = format!(
+ r#"{{"srcset":"{a} 640w, {b} 2x","style":"background:url({b}) no-repeat","text":".x{{background:url(\"{a}\")}}","other":"{b}?v=2"}}"#
+ );
+ let out = rewrite(&[a, b], &event);
+ let (ra, rb) = (reference(a), reference(b));
+ assert_eq!(
+ out,
+ format!(
+ r#"{{"srcset":"{ra} 640w, {rb} 2x","style":"background:url({rb}) no-repeat","text":".x{{background:url(\"{ra}\")}}","other":"{b}?v=2"}}"#
+ )
+ );
+ assert!(serde_json::from_str::<serde_json::Value>(&out).is_ok());
+
+ // A srcset over several lines holds each URL after an escape, which is no part of the URL.
+ let declined = "https://10.0.0.7/c.png";
+ let event = format!(r#"{{"srcset":"{a} 1x,\n{b} 2x,\t{declined} 3x"}}"#);
+ let mut rewrite = UrlRewrite::new(
+ &[a.to_owned(), b.to_owned(), declined.to_owned()],
+ 7,
+ "2026-10",
+ &TEAM_KEY,
+ );
+ assert_eq!(
+ String::from_utf8(rewrite.apply(event.as_bytes()).into_owned()).unwrap(),
+ format!(
+ r#"{{"srcset":"{ra} 1x,\n{rb} 2x,\t{} 3x"}}"#,
+ declined_marker("non_public_host")
+ )
+ );
+ assert!(rewrite.finish());
+ }
+
+ #[test]
+ fn rewrites_a_url_that_a_json_escape_hid() {
+ let url = "https://cdn.example.com/a.png?token=secret";
+ let hidden = r#"{"src":"https:\/\/cdn.example.com\/a.png?token=secr\u0065t","alt":"a\nb"}"#;
+ let canonical = canonical_strings(hidden.as_bytes());
+ let mut rewrite = UrlRewrite::new(&[url.to_owned()], 7, "2026-10", &TEAM_KEY);
+ assert_eq!(
+ String::from_utf8(rewrite.apply(&canonical).into_owned()).unwrap(),
+ format!(
+ r#"{{"src":"{}","alt":"a\nb"}}"#,
+ declined_marker("credential")
+ )
+ );
+ assert!(rewrite.finish());
+ // An event capture wrote is left as it is.
+ let plain = r#"{"text":"a\"b\\c\u0001","n":1}"#;
+ assert!(matches!(
+ canonical_strings(plain.as_bytes()),
+ Cow::Borrowed(_)
+ ));
+ // A declined URL the block still holds fails the block.
+ let rewrite = UrlRewrite::new(&[url.to_owned()], 7, "2026-10", &TEAM_KEY);
+ assert!(!rewrite.finish());
+ }
+
+ #[test]
+ fn leaves_only_a_marker_where_the_policy_declines_a_url() {
+ for (url, reason) in [
+ ("https://user:[email protected]/a.png", "credential"),
+ (
+ "https://bucket.s3.amazonaws.com/a.png?X-Amz-Signature=abc123",
+ "credential",
+ ),
+ ("https://10.0.0.7/a.png", "non_public_host"),
+ ("http://cdn.example.com/a.png", "bad_scheme"),
+ ] {
+ let out = rewrite(&[url], &format!(r#"{{"src":"{url}"}}"#));
+ assert_eq!(
+ out,
+ format!(r#"{{"src":"{}"}}"#, declined_marker(reason)),
+ "{url}"
+ );
+ }
+ // A second copy inside a longer URL stays as it is, so the block fails.
+ let url = "https://bucket.s3.amazonaws.com/a.png?X-Amz-Signature=abc123";
+ let mut rewrite = UrlRewrite::new(&[url.to_owned()], 7, "2026-10", &TEAM_KEY);
+ rewrite.apply(format!(r#"{{"src":"{url}","alt":"x{url}"}}"#).as_bytes());
+ assert!(!rewrite.finish());
+ }
+}
diff --git a/rust/ai-research/replay-recorder-v4/src/urls.rs b/rust/ai-research/replay-recorder-v4/src/urls.rs
new file mode 100644
index 000000000000..7f7c471c6212
--- /dev/null
+++ b/rust/ai-research/replay-recorder-v4/src/urls.rs
@@ -0,0 +1,310 @@
+//! Fetch jobs for the remote images a flush's blocks referenced, in the v3 fetch topic's job shape.
+
+use std::collections::{BTreeMap, HashSet};
+use std::time::Duration;
+
+use metrics::counter;
+use replay_core_v4::keys::batch::{FlushKeys, SessionId};
+use replay_core_v4::refs::{image_url_ref, reference_hash};
+use replay_core_v4::seal::image_url_key;
+use replay_core_v4::url_policy::{
+ is_public_host, is_tracking_beacon, try_canonicalize, CanonicalUrl, Decline,
+};
+use serde_json::{json, Value};
+
+use crate::batch::Block;
+
+/// The fetcher's limits on one Kafka record: its job count, and the byte length of its value without key or headers.
+const MAX_JOBS_PER_RECORD: usize = 1000;
+const MAX_RECORD_BYTES: usize = 512 * 1024;
+/// How many redirects a job may follow, as in v3.
+const REMAINING_HOPS: u32 = 10;
+
+/// Builds one job per new remote image URL, grouped by registrable domain, the topic's key. Counts each block's URLs
+/// in its stats. `already_sent` names references this process sent today.
+pub fn fetch_jobs<'b>(
+ blocks: impl IntoIterator<Item = &'b mut Block>,
+ keys: &FlushKeys,
+ key_month: &str,
+ now_ms: i64,
+ already_sent: &dyn Fn(&str) -> bool,
+) -> BTreeMap<String, Vec<Value>> {
+ let mut jobs: BTreeMap<String, Vec<Value>> = BTreeMap::new();
+ let mut seen = HashSet::new();
+ for block in blocks {
+ let id = SessionId {
+ team_id: block.session.team_id,
+ session_id: block.session.session_id.clone(),
+ };
+ let (Some(_), Some(team_key)) = (
+ keys.sessions.get(&id),
+ keys.team_months.get(&block.session.team_id),
+ ) else {
+ continue;
+ };
+ let url_key = image_url_key(team_key);
+ for raw in &block.image_urls {
+ let Ok((url, reference)) =
+ url_reference(raw, block.session.team_id, key_month, &url_key)
+ else {
+ continue;
+ };
+ block.stats.image_urls += 1;
+ if already_sent(&reference) || !seen.insert(reference.clone()) {
+ continue;
+ }
+ jobs.entry(url.domain.clone()).or_default().push(json!({
+ "sessionId": block.session.session_id,
+ "originalRef": reference,
+ "currentUrl": url.fetch,
+ "remainingHops": REMAINING_HOPS,
+ "notBeforeMs": 0,
+ "firstSeenAtMs": now_ms,
+ "fetchCount": 0,
+ "republishCount": 0,
+ "lastRepublishReason": null,
+ }));
+ }
+ }
+ jobs
+}
+
+/// The reference of a remote image URL, the same in the fetch job and in the stored block, or why the policy declines
+/// the URL. `url_key` is the team's URL key for `key_month`.
+pub fn url_reference(
+ raw: &str,
+ team_id: i64,
+ key_month: &str,
+ url_key: &[u8; 32],
+) -> Result<(CanonicalUrl, String), Decline> {
+ let url = try_canonicalize(raw)?;
+ let path = url::Url::parse(&url.fetch)
+ .map(|u| u.path().to_owned())
+ .unwrap_or_default();
+ if !is_public_host(&url.host) {
+ return Err(Decline::NonPublicHost);
+ }
+ if is_tracking_beacon(&url.host, &path) {
+ return Err(Decline::TrackingBeacon);
+ }
+ let reference = image_url_ref(
+ team_id,
+ key_month,
+ &reference_hash(url_key, url.dedup.as_bytes()),
+ );
+ Ok((url, reference))
+}
+
+/// Splits each domain's jobs into records the fetcher accepts. Returns (key, payload, references) per record.
+/// The fetcher rejects a whole record whose value exceeds its byte limit, so a job too large for any record is dropped.
+pub fn records(jobs: BTreeMap<String, Vec<Value>>) -> Vec<(String, Vec<u8>, Vec<String>)> {
+ let empty_bytes = payload(Vec::new()).len();
+ let mut records = Vec::new();
+ let mut oversized = 0u64;
+ for (domain, domain_jobs) in jobs {
+ let mut batch: Vec<Value> = Vec::new();
+ let mut bytes = empty_bytes;
+ for job in domain_jobs {
+ let size = job.to_string().len();
+ if empty_bytes + size > MAX_RECORD_BYTES {
+ oversized += 1;
+ continue;
+ }
+ if !batch.is_empty()
+ && (batch.len() >= MAX_JOBS_PER_RECORD || bytes + 1 + size > MAX_RECORD_BYTES)
+ {
+ records.push(record(&domain, std::mem::take(&mut batch)));
+ bytes = empty_bytes;
+ }
+ bytes += size + usize::from(!batch.is_empty());
+ batch.push(job);
+ }
+ if !batch.is_empty() {
+ records.push(record(&domain, batch));
+ }
+ }
+ if oversized > 0 {
+ counter!("ai_research_v4_recorder_dropped_image_fetch_jobs_total", "reason" => "oversized")
+ .increment(oversized);
+ }
+ records
+}
+
+fn record(domain: &str, jobs: Vec<Value>) -> (String, Vec<u8>, Vec<String>) {
+ let references = jobs
+ .iter()
+ .filter_map(|j| j["originalRef"].as_str().map(str::to_owned))
+ .collect();
+ (domain.to_owned(), payload(jobs), references)
+}
+
+/// The record value exactly as the fetcher measures it.
+fn payload(jobs: Vec<Value>) -> Vec<u8> {
+ json!({"v": 2, "jobs": jobs}).to_string().into_bytes()
+}
+
+/// The marks of references sent to the fetcher, by UTC day. The recorder only inserts marks and asks for them with
+/// `contains_key`, which does not count as a read. So moka's default policy would refuse every new mark once the cache
+/// is full, and LRU is the policy that keeps the newest.
+pub fn sent_urls(capacity: u64) -> moka::sync::Cache<(String, String), ()> {
+ moka::sync::Cache::builder()
+ .max_capacity(capacity)
+ // A mark names its UTC day, so it is of no use after a day.
+ .time_to_live(Duration::from_secs(24 * 3600))
+ .eviction_policy(moka::policy::EvictionPolicy::lru())
+ .build()
+}
+
+#[cfg(test)]
+mod tests {
+ use replay_core_v4::inspect::stats::BlockStats;
+ use replay_core_v4::keys::batch::SessionKey as Key;
+
+ use super::*;
+ use crate::batch::SessionKey;
+
+ #[test]
+ fn a_full_sent_cache_still_keeps_new_marks() {
+ let sent = sent_urls(100);
+ let mark = |round: u32, i: u32| ("2026-10-15".to_owned(), format!("{round}-{i}"));
+ for round in 0..2 {
+ for i in 0..100 {
+ sent.insert(mark(round, i), ());
+ }
+ sent.run_pending_tasks();
+ }
+ assert!((0..100).all(|i| sent.contains_key(&mark(1, i))));
+ }
+
+ #[test]
+ fn sends_each_new_public_image_url_once_by_domain() {
+ let urls = [
+ "https://cdn.example.com/a.png",
+ "https://cdn.example.com/a.png",
+ "https://img2.cdn.example.com/b.png",
+ "https://cdn.example.com/sent.png",
+ "http://localhost/private.png",
+ "https://bat.bing.com/action/0",
+ ];
+ let mut blocks = vec![Block {
+ session: SessionKey {
+ team_id: 7,
+ session_id: "s".to_owned(),
+ },
+ messages: Vec::new(),
+ stats: BlockStats::default(),
+ moments: Vec::new(),
+ image_urls: urls.iter().map(|u| (*u).to_owned()).collect(),
+ remote_urls: Vec::new(),
+ url_limit: None,
+ }];
+ let mut keys = FlushKeys::default();
+ keys.sessions.insert(
+ SessionId {
+ team_id: 7,
+ session_id: "s".to_owned(),
+ },
+ Key {
+ key: [1; 32],
+ key_month: "2026-10".to_owned(),
+ },
+ );
+ keys.team_months.insert(7, [2; 32]);
+ let sent_hash = reference_hash(
+ &image_url_key(&[2; 32]),
+ try_canonicalize("https://cdn.example.com/sent.png")
+ .unwrap()
+ .dedup
+ .as_bytes(),
+ );
+ let sent = image_url_ref(7, "2026-10", &sent_hash);
+
+ let jobs = fetch_jobs(&mut blocks, &keys, "2026-10", 1_000, &|reference| {
+ reference == sent
+ });
+ let domains: Vec<_> = jobs.keys().cloned().collect();
+ assert_eq!(domains, ["example.com"]);
+ let fetched: Vec<_> = jobs["example.com"]
+ .iter()
+ .map(|j| j["currentUrl"].as_str().unwrap().to_owned())
+ .collect();
+ assert_eq!(
+ fetched,
+ [
+ "https://cdn.example.com/a.png",
+ "https://img2.cdn.example.com/b.png"
+ ]
+ );
+ let job = &jobs["example.com"][0];
+ assert!(job["originalRef"]
+ .as_str()
+ .unwrap()
+ .starts_with("imageurl:v4:7:2026-10:"));
+ assert_eq!(
+ (job["sessionId"].as_str(), job["remainingHops"].as_u64()),
+ (Some("s"), Some(10))
+ );
+ // Every public URL the block referenced counts, sent before or not.
+ assert_eq!(blocks[0].stats.image_urls, 4);
+ }
+
+ #[test]
+ fn splits_a_domains_jobs_at_the_fetchers_record_limit() {
+ let jobs = BTreeMap::from([(
+ "example.com".to_owned(),
+ (0..2500)
+ .map(|i| json!({"originalRef": format!("r{i}")}))
+ .collect(),
+ )]);
+ let sizes: Vec<_> = records(jobs)
+ .iter()
+ .map(|(_, _, references)| references.len())
+ .collect();
+ assert_eq!(sizes, [1000, 1000, 500]);
+ }
+
+ fn padded(reference: &str, pad: usize) -> Value {
+ json!({"originalRef": reference, "pad": "x".repeat(pad)})
+ }
+
+ #[test]
+ fn fills_a_record_to_the_fetchers_byte_limit_and_no_further() {
+ let empty = payload(Vec::new()).len();
+ let bare = padded("a", 0).to_string().len();
+ // Two jobs and a comma that fill the record value to the exact limit.
+ let first = MAX_RECORD_BYTES - empty - 2 * bare - 1 - 10;
+ for (extra, expected) in [(0, vec![2]), (1, vec![1, 1])] {
+ let jobs = BTreeMap::from([(
+ "example.com".to_owned(),
+ vec![padded("a", first), padded("b", 10 + extra)],
+ )]);
+ let records = records(jobs);
+ let sizes: Vec<_> = records.iter().map(|(_, _, r)| r.len()).collect();
+ assert_eq!(sizes, expected, "extra {extra}");
+ assert!(records.iter().all(|(_, p, _)| p.len() <= MAX_RECORD_BYTES));
+ if extra == 0 {
+ assert_eq!(records[0].1.len(), MAX_RECORD_BYTES);
+ }
+ }
+ }
+
+ #[test]
+ fn drops_only_a_job_too_large_for_any_record() {
+ let room = MAX_RECORD_BYTES - payload(Vec::new()).len() - padded("a", 0).to_string().len();
+ let jobs = BTreeMap::from([(
+ "example.com".to_owned(),
+ vec![
+ padded("fits", 0),
+ padded("a", room + 1),
+ padded("full", room - 3),
+ ],
+ )]);
+ let records = records(jobs);
+ let references: Vec<_> = records.iter().map(|(_, _, r)| r.clone()).collect();
+ assert_eq!(
+ references,
+ [vec!["fits".to_owned()], vec!["full".to_owned()]]
+ );
+ assert_eq!(records[1].1.len(), MAX_RECORD_BYTES);
+ }
+}
diff --git a/rust/ai-research/replay-recorder-v4/src/write.rs b/rust/ai-research/replay-recorder-v4/src/write.rs
index d4056972ca44..3fe258cd0d0b 100644
--- a/rust/ai-research/replay-recorder-v4/src/write.rs
+++ b/rust/ai-research/replay-recorder-v4/src/write.rs
@@ -7,6 +7,7 @@ use std::collections::{BTreeMap, HashSet};
use std::io::Write;
use chrono::{DateTime, Utc};
+use metrics::counter;
use rand::Rng;
use replay_core_v4::bytescan::write_json_string;
use replay_core_v4::envelope::{seal_frame, seal_json_envelope, Codec, Context, Version};
@@ -23,6 +24,7 @@ use crate::batch::{Block, SessionKey};
use crate::index::{
block_index, image_index, write_parquet, BlockIndexRow, ImageIndexRow, IndexError,
};
+use crate::rewrite::{canonical_strings, UrlRewrite};
use crate::store::{BlobStore, StoreError};
/// Brotli settings for blocks, the same as the v3 lane, which uses the same C encoder. The lane keeps blocks for months
@@ -74,6 +76,8 @@ pub struct Prepared {
/// The frames the packs would hold if each session sealed its images under its own key: one per distinct
/// (session, reference) pair, where `images` holds one per reference.
pub session_frames: u64,
+ /// Which of the blocks it was given are stored. The fetch jobs come from these only.
+ pub kept: Vec<bool>,
}
fn unique_suffix(at: DateTime<Utc>) -> String {
@@ -97,11 +101,12 @@ pub fn prepare(blocks: &mut [Block], keys: &FlushKeys, key_month: &str) -> Prepa
blocks: Vec::new(),
images: BTreeMap::new(),
session_frames: 0,
+ kept: vec![false; blocks.len()],
};
// A reference names its team, so it names one frame of the flush.
let mut seen: HashSet<String> = HashSet::new();
let mut seen_in_session: HashSet<(String, String)> = HashSet::new();
- for block in blocks.iter_mut() {
+ for (index, block) in blocks.iter_mut().enumerate() {
let id = SessionId {
team_id: block.session.team_id,
session_id: block.session.session_id.clone(),
@@ -112,9 +117,21 @@ pub fn prepare(blocks: &mut [Block], keys: &FlushKeys, key_month: &str) -> Prepa
) else {
continue;
};
+ // Fail closed: the inspector did not name every URL, so one it missed could be declined.
+ if let Some(limit) = block.url_limit {
+ counter!("ai_research_v4_recorder_dropped_blocks_total", "outcome" => limit.label())
+ .increment(1);
+ continue;
+ }
let content_key = image_content_key(team_key);
+ let mut rewrite = UrlRewrite::new(
+ &block.remote_urls,
+ block.session.team_id,
+ key_month,
+ team_key,
+ );
block.stats.url_fingerprints = url_fingerprints(&key.key, &block_urls(block));
- let images = prepared.images.entry(block.session.team_id).or_default();
+ let mut block_images = Vec::new();
let mut lines = Vec::with_capacity(
block.stats.byte_size as usize + block.stats.event_count as usize * 16,
);
@@ -136,11 +153,12 @@ pub fn prepare(blocks: &mut [Block], keys: &FlushKeys, key_month: &str) -> Prepa
lines.push(b'[');
lines.extend_from_slice(&window);
lines.push(b',');
- lines.extend_from_slice(
+ let canonical = canonical_strings(
extracted
.as_deref()
.unwrap_or(&message.inner[event.span.0..event.span.1]),
);
+ lines.extend_from_slice(&rewrite.apply(&canonical));
lines.extend_from_slice(b"]\n");
let line = (lines.len() - line_start) as u64;
block.stats.written_jsonl_bytes += line;
@@ -153,15 +171,24 @@ pub fn prepare(blocks: &mut [Block], keys: &FlushKeys, key_month: &str) -> Prepa
.map(|i| i.bytes.len() as u64)
.sum::<u64>();
block.stats.images_inline += sink.left_inline;
- for image in sink.images {
- if seen_in_session.insert((id.session_id.clone(), image.reference.clone())) {
- prepared.session_frames += 1;
- }
- if seen.insert(image.reference.clone()) {
- images.push(image);
- }
+ block_images.extend(sink.images);
+ }
+ // Fail closed: a declined URL, a credential or a private host, must not reach storage.
+ if !rewrite.finish() {
+ counter!("ai_research_v4_recorder_dropped_blocks_total", "outcome" => "declined_unrewritten")
+ .increment(1);
+ continue;
+ }
+ let images = prepared.images.entry(block.session.team_id).or_default();
+ for image in block_images {
+ if seen_in_session.insert((id.session_id.clone(), image.reference.clone())) {
+ prepared.session_frames += 1;
+ }
+ if seen.insert(image.reference.clone()) {
+ images.push(image);
}
}
+ prepared.kept[index] = true;
prepared.blocks.push(PreparedBlock {
session: block.session.clone(),
key: key.clone(),
@@ -396,6 +423,7 @@ mod tests {
use bytes::Bytes;
use parquet::arrow::arrow_reader::ParquetRecordBatchReaderBuilder;
use replay_core_v4::envelope::open_frame;
+ use replay_core_v4::inspect::dom::MAX_REMOTE_URL_BYTES;
use replay_core_v4::inspect::session::Moment;
use replay_core_v4::inspect::stats::BlockStats;
use replay_core_v4::scan::message::read_message;
@@ -433,9 +461,16 @@ mod tests {
}
fn block(session: &str, events: Value) -> Block {
- let inner = json!({"event": "$snapshot_items", "properties": {"$session_id": session, "$window_id": "w1", "$snapshot_items": events}});
+ block_of(session, &events.to_string())
+ }
+
+ /// A block of the events JSON as it is written, escapes included.
+ fn block_of(session: &str, events: &str) -> Block {
+ let inner = format!(
+ r#"{{"event":"$snapshot_items","properties":{{"$session_id":"{session}","$window_id":"w1","$snapshot_items":{events}}}}}"#
+ );
let message = read_message(
- json!({"distinct_id": "d", "data": inner.to_string()})
+ json!({"distinct_id": "d", "data": inner})
.to_string()
.into_bytes(),
)
@@ -448,6 +483,9 @@ mod tests {
messages: vec![message],
stats: BlockStats::default(),
moments: Vec::new(),
+ image_urls: Vec::new(),
+ remote_urls: Vec::new(),
+ url_limit: None,
}
}
@@ -462,6 +500,149 @@ mod tests {
format!("data:image/png;base64,{}", STANDARD.encode(bytes))
}
+ /// The block's stored lines, after the inspector named its remote URLs.
+ fn stored_lines(events: &str, extra: &[&str]) -> String {
+ let mut inspected = block_of("kept", events);
+ let mut inspector = replay_core_v4::inspect::session::SessionInspector::default();
+ let mut inspection = replay_core_v4::inspect::session::BlockInspection::default();
+ for message in &inspected.messages {
+ inspector.observe_message(&mut inspection, message);
+ }
+ let found = inspection.finish();
+ inspected.remote_urls = found.remote_urls;
+ inspected.url_limit = found.url_limit;
+ inspected
+ .remote_urls
+ .extend(extra.iter().map(|url| (*url).to_owned()));
+ let mut keys = FlushKeys::default();
+ keys.sessions.insert(
+ SessionId {
+ team_id: 7,
+ session_id: "kept".to_owned(),
+ },
+ Key {
+ key: [5; 32],
+ key_month: "2026-10".to_owned(),
+ },
+ );
+ keys.team_months.insert(7, [6; 32]);
+ let mut blocks = vec![inspected];
+ let prepared = prepare(&mut blocks, &keys, "2026-10");
+ prepared
+ .blocks
+ .first()
+ .map(|b| String::from_utf8(b.lines.clone()).unwrap())
+ .unwrap_or_default()
+ }
+
+ #[test]
+ fn replaces_the_sources_of_a_node_the_inspector_does_not_know() {
+ let (signed, public) = (
+ "https://bucket.s3.amazonaws.com/avatar.png?X-Amz-Signature=abc123",
+ "HTTPS://cdn.example.com/avatar.png",
+ );
+ // This process never saw node 99: the session started before a restart.
+ let events = json!([{"type": 3, "timestamp": 1, "data": {"source": 0, "adds": [], "removes": [], "texts": [],
+ "attributes": [{"id": 99, "attributes": {"src": signed, "srcset": format!("{public} 2x")}}]}}])
+ .to_string();
+ let lines = stored_lines(&events, &[]);
+ let reference = crate::urls::url_reference(
+ public,
+ 7,
+ "2026-10",
+ &replay_core_v4::seal::image_url_key(&[6; 32]),
+ )
+ .unwrap()
+ .1;
+ assert!(
+ lines.contains(&format!(
+ r#""src":"{}","srcset":"{reference} 2x""#,
+ crate::rewrite::declined_marker("credential")
+ )),
+ "{lines}"
+ );
+ // A URL past the length cap is not named, so the block is not stored.
+ let long = |len: usize| {
+ let url = format!("https://cdn.example.com/{}", "a".repeat(len - 24));
+ json!([{"type": 3, "timestamp": 1, "data": {"source": 0, "adds": [], "removes": [], "texts": [],
+ "attributes": [{"id": 99, "attributes": {"src": url}}]}}])
+ .to_string()
+ };
+ assert!(!stored_lines(&long(MAX_REMOTE_URL_BYTES), &[]).is_empty());
+ assert_eq!(stored_lines(&long(MAX_REMOTE_URL_BYTES + 1), &[]), "");
+ // Keys written with escapes hide no URL.
+ let escaped = events
+ .replace(r#""src""#, r#""\u0073rc""#)
+ .replace(r#""srcset""#, r#""src\u0073et""#);
+ assert_eq!(stored_lines(&escaped, &[]), lines);
+ // The player loads the last of a repeated attribute, so the inspector names that one.
+ for events in [
+ format!(
+ r#"[{{"type":3,"timestamp":1,"data":{{"source":0,"adds":[],"removes":[],"texts":[],"attributes":[{{"id":99,"attributes":{{"src":"{public}","src":"{signed}"}}}}]}}}}]"#
+ ),
+ format!(
+ r#"[{{"type":3,"timestamp":1,"data":{{"source":0,"adds":[{{"parentId":1,"node":{{"type":2,"tagName":"img","attributes":{{"src":"{public}","src":"{signed}"}},"childNodes":[],"id":5}}}}],"removes":[],"texts":[],"attributes":[]}}}}]"#
+ ),
+ ] {
+ let lines = stored_lines(&events, &[]);
+ assert!(
+ lines.contains(&crate::rewrite::declined_marker("credential"))
+ && !lines.contains("X-Amz-Signature"),
+ "{lines}"
+ );
+ }
+ // A declined URL the inspector named but the stored bytes do not show as it read it fails the whole block.
+ let event =
+ json!([{"type": 4, "timestamp": 1, "data": {"href": "https://app.example.com/"}}])
+ .to_string();
+ assert_eq!(stored_lines(&event, &[signed]), "");
+ assert!(!stored_lines(&event, &[public]).is_empty());
+ }
+
+ #[test]
+ fn a_block_carries_the_reference_its_fetch_job_names() {
+ let (fetched, declined) = (
+ "https://cdn.example.com/a.png",
+ "https://cdn.example.com/a.png?token=secret",
+ );
+ let events = json!([{"type": 2, "timestamp": 1, "data": {"node": {"attributes": {"src": fetched, "srcset": format!("{declined} 2x")}}}}]);
+ let mut blocks = vec![block("kept", events.clone()), block("dropped", events)];
+ for block in &mut blocks {
+ block.image_urls = vec![fetched.to_owned()];
+ block.remote_urls = vec![fetched.to_owned(), declined.to_owned()];
+ }
+ blocks[1].url_limit = Some(replay_core_v4::inspect::dom::UrlLimit::UrlLength);
+ let mut keys = FlushKeys::default();
+ for session in ["kept", "dropped"] {
+ keys.sessions.insert(
+ SessionId {
+ team_id: 7,
+ session_id: session.to_owned(),
+ },
+ Key {
+ key: [5; 32],
+ key_month: "2026-10".to_owned(),
+ },
+ );
+ }
+ keys.team_months.insert(7, [6; 32]);
+ let prepared = prepare(&mut blocks, &keys, "2026-10");
+ // Only a stored block sends fetch jobs.
+ assert_eq!(prepared.kept, [true, false]);
+ let jobs = crate::urls::fetch_jobs(&mut blocks[..1], &keys, "2026-10", 1, &|_| false);
+ let lines = String::from_utf8(prepared.blocks[0].lines.clone()).unwrap();
+ let reference = jobs["example.com"][0]["originalRef"].as_str().unwrap();
+ assert!(
+ lines.contains(&format!(r#""src":"{reference}""#)),
+ "{lines}"
+ );
+ assert!(lines.contains(&format!(
+ r#""srcset":"{} 2x""#,
+ crate::rewrite::declined_marker("credential")
+ )));
+ assert!(!lines.contains("cdn.example.com"));
+ }
+
#[tokio::test]
async fn stores_images_once_and_blocks_that_point_at_them() {
let events = json!([