diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py index c0a31da1320..6c628a1f8d7 100644 --- a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py +++ b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face.py @@ -6,6 +6,7 @@ from typing import Any from ..assertions import assert_equal, record_contract from ..config import REPO_ROOT from .font_face_css_order import run_css_font_order_contract, run_projected_local_font_order_contract +from .font_face_fallback_identity import run_font_fallback_identity_contract from .font_face_matching import run_font_matching_contract @@ -14,6 +15,7 @@ async def run_font_face_payload_group( fixture: str, results: list[dict[str, Any]], ) -> None: + await run_font_fallback_identity_contract(browser, results) await run_css_font_order_contract(browser, results) await run_projected_local_font_order_contract(browser, results) context = await browser.new_context() diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_fallback_identity.py b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_fallback_identity.py new file mode 100644 index 00000000000..c2f0c014fb7 --- /dev/null +++ b/moli-cdp-smoke/moli_cdp_smoke/groups/font_face_fallback_identity.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import asyncio +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any + +from ..assertions import assert_equal, record_contract +from ..config import REPO_ROOT + + +async def run_font_fallback_identity_contract(browser: Any, results: list[dict[str, Any]]) -> None: + fixtures = REPO_ROOT / "moli-layout/tests/fixtures" + fonts = {name: (fixtures / f"moli-ahem-{width}.ttf").read_bytes() + for name, width in [("a", "narrow"), ("b", "wide")]} + requests: list[str] = [] + + class Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: + requests.append(self.path) + if self.path.endswith("style.css"): + body = b"@font-face{font-family:FallbackIdentity;src:url(data:font/woff2;base64,YmFk),url(font.ttf)}" + content_type = "text/css" + elif self.path.endswith("font.ttf"): + body = fonts[self.path.split("/")[-2]] + content_type = "font/ttf" + else: + body = b"" + content_type = "text/html" + self.send_response(200) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_: Any) -> None: + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + observed = [] + try: + for index, order in enumerate([["a", "b"], ["b", "a"]]): + context = await browser.new_context() + try: + page = await context.new_page() + await page.goto(f"http://127.0.0.1:{server.server_port}/round-{index}/page", wait_until="load") + observed.append(await page.evaluate("""async order => { + const target=document.createElement('span'); + target.textContent='AAAA'; + target.style.cssText='display:inline-block;font:40px FallbackIdentity'; + document.body.append(target); + const widths=[], counts=[]; + for (const directory of order) { + const link=document.createElement('link');link.rel='stylesheet'; + link.href=directory+'/style.css'; + const loaded=new Promise((resolve,reject)=>{link.onload=resolve;link.onerror=reject}); + document.head.append(link);await loaded; + const faces=[...document.fonts].filter(face=>face.family==='FallbackIdentity'); + counts.push(faces.length); + await Promise.all(faces.map(face=>face.load())); + widths.push(target.getBoundingClientRect().width); + } + return {widths,counts}; + }""", order)) + finally: + await context.close() + finally: + await asyncio.to_thread(server.shutdown) + server.server_close() + thread.join() + assert_equal(observed, [{"widths": [80, 160], "counts": [1, 2]}, + {"widths": [160, 80], "counts": [1, 2]}], + "relative fallbacks in identical stylesheet text keep independent resources") + font_requests = sorted(path for path in requests if path.endswith("font.ttf")) + assert_equal(font_requests, [f"/round-{index}/{directory}/font.ttf" + for index in range(2) for directory in ["a", "b"]], + "each stylesheet requests its own resolved fallback") + record_contract(results, "font_face_resolved_fallback_identity", + contract="Font resource identity includes the ordered resolved fallback list.", + source="CSS Fonts source fallback and stylesheet URL resolution", + commands=["Runtime.evaluate"], observed={"geometry": observed, "requests": font_requests}) diff --git a/moli-renderer-v8/src/css_resource_urls.rs b/moli-renderer-v8/src/css_resource_urls.rs index 1fee945a0ad..28e3548cff5 100644 --- a/moli-renderer-v8/src/css_resource_urls.rs +++ b/moli-renderer-v8/src/css_resource_urls.rs @@ -215,11 +215,20 @@ fn stylesheet_web_font_resource_with_descriptor( // projections of the same parsed rule (the import response and the later // retained style world) must converge on one slot. Conversely, identical // relative declarations parsed under different stylesheet bases must not - // alias, so identity includes the resolved request URL. - let mut slot_material = Vec::with_capacity(request_url.as_str().len() + css_text.len() + 1); - slot_material.extend_from_slice(request_url.as_str().as_bytes()); - slot_material.push(0); + // alias, so identity includes every resolved fallback, its kind and order. + // Length-prefix strings so source boundaries cannot collide. + let mut slot_material = Vec::new(); + slot_material.extend_from_slice(&(css_text.len() as u64).to_le_bytes()); slot_material.extend_from_slice(css_text.as_bytes()); + for source in &sources { + let (kind, value) = match source { + moli_css_parse::CssFontSource::Local(value) => (0, value), + moli_css_parse::CssFontSource::Url(value) => (1, value), + }; + slot_material.push(kind); + slot_material.extend_from_slice(&(value.len() as u64).to_le_bytes()); + slot_material.extend_from_slice(value.as_bytes()); + } let slot = format!("stylesheet-font:{}", sha256_hex(&slot_material)); StylesheetLoadBlockingResource::font( request_url, @@ -486,6 +495,46 @@ mod tests { ); } + #[test] + fn font_slot_includes_every_resolved_fallback_in_source_order() { + use moli_css_parse::CssFontSource::{Local, Url as SourceUrl}; + let css = + "@font-face{font-family:Fallback;src:url(data:font/woff2;base64,YmFk),url(font.woff2)}"; + let first = stylesheet_web_font_resource( + css, + &Url::parse("https://example.test/a/style.css").unwrap(), + ) + .unwrap(); + let second = stylesheet_web_font_resource( + css, + &Url::parse("https://example.test/b/style.css").unwrap(), + ) + .unwrap(); + assert_eq!(first.request_url(), second.request_url()); + assert_ne!( + first.web_font().unwrap().slot(), + second.web_font().unwrap().slot() + ); + let slot = |sources| { + stylesheet_web_font_resource_with_resolved_sources(css, sources) + .unwrap() + .web_font() + .unwrap() + .slot() + .to_owned() + }; + let url = "https://example.test/font.woff2".to_owned(); + let other = "https://example.test/other.woff2".to_owned(); + assert_ne!( + slot(vec![SourceUrl(url.clone()), SourceUrl(other.clone())]), + slot(vec![SourceUrl(other.clone()), SourceUrl(url.clone())]), + ); + assert_ne!( + slot(vec![SourceUrl(url.clone()), Local(other.clone())]), + slot(vec![SourceUrl(url), SourceUrl(other)]), + ); + } + #[test] fn load_blocking_font_selection_ignores_image_and_unrelated_bits() { let css = r#"