Skip to content

Truly independent web browser

LibWeb: Implement PerformanceServerTiming in Rust

Shannon Boothed3ea9e407fb
diff --git a/Cargo.lock b/Cargo.lock
index e7f9f9f789c..96a6abee2fb 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1962,6 +1962,7 @@ dependencies = [
"libcompositing_rust",
"libcompress_rust",
"libgfx_rust",
+ "libhttp_rust",
"libjs_rust",
"libtextcodec_rust",
"libunicode_rust",
diff --git a/Libraries/LibWeb/Bindings/Rust/Cargo.toml b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
index 20d6bd8be08..4ed944215c3 100644
--- a/Libraries/LibWeb/Bindings/Rust/Cargo.toml
+++ b/Libraries/LibWeb/Bindings/Rust/Cargo.toml
@@ -24,6 +24,7 @@ ladybird_allocator = { path = "../../../RustAllocator", optional = true }
libcompositing_rust = { path = "../../../LibCompositing/Rust" }
libcompress_rust = { path = "../../../LibCompress/Rust" }
libgfx_rust = { path = "../../../LibGfx/Rust", default-features = false }
+libhttp_rust = { path = "../../../LibHTTP/Rust" }
libjs_rust = { path = "../../../LibJS/Rust", default-features = false }
libtextcodec_rust = { path = "../../../LibTextCodec/Rust" }
libunicode_rust = { path = "../../../LibUnicode/Rust", default-features = false }
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 229aa35cca2..87d2e2717a5 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -65,6 +65,8 @@ pub(crate) mod message_channel;
#[cfg(not(test))]
pub(crate) mod message_port;
#[cfg(not(test))]
+pub(crate) mod numbers;
+#[cfg(not(test))]
pub(crate) mod offscreen_canvas_rendering_context2d;
#[cfg(not(test))]
pub(crate) mod path2d;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/numbers.rs b/Libraries/LibWeb/Bindings/Rust/src/html/numbers.rs
new file mode 100644
index 00000000000..482d2c7dd48
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/numbers.rs
@@ -0,0 +1,16 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+unsafe extern "C" {
+ fn web_html_parse_floating_point_number(string: ak::Span<'_, u8>, value: *mut f64) -> bool;
+}
+
+/// https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#rules-for-parsing-floating-point-number-values
+pub(crate) fn parse_floating_point_number(string: &str) -> Option<f64> {
+ let mut value = 0.0;
+ // SAFETY: The string and the value outlive the call.
+ unsafe { web_html_parse_floating_point_number(ak::Span::new(string.as_bytes()), &raw mut value) }.then_some(value)
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/lib.rs b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
index 58a9eb1bae3..461118a08dc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/lib.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/lib.rs
@@ -132,6 +132,15 @@ pub(crate) mod notifications_api;
not(web_idl_bindings),
allow(dead_code, reason = "only the generated bindings use the interfaces")
)]
+#[allow(
+ clippy::unnecessary_wraps,
+ reason = "the bindings call every attribute and operation as one that can throw"
+)]
+pub(crate) mod server_timing;
+#[cfg_attr(
+ not(web_idl_bindings),
+ allow(dead_code, reason = "only the generated bindings use the interfaces")
+)]
pub(crate) mod speech;
#[cfg_attr(
not(web_idl_bindings),
diff --git a/Libraries/LibWeb/Bindings/Rust/src/server_timing/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/server_timing/mod.rs
new file mode 100644
index 00000000000..cbf624f5bd3
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/server_timing/mod.rs
@@ -0,0 +1,10 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Server Timing, https://w3c.github.io/server-timing/
+
+#[cfg(not(test))]
+pub(crate) mod performance_server_timing;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/server_timing/performance_server_timing.rs b/Libraries/LibWeb/Bindings/Rust/src/server_timing/performance_server_timing.rs
new file mode 100644
index 00000000000..1668e250e0f
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/server_timing/performance_server_timing.rs
@@ -0,0 +1,147 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! PerformanceServerTiming, https://w3c.github.io/server-timing/#the-performanceservertiming-interface
+
+use core::ffi::c_void;
+use std::collections::HashMap;
+
+use ak::{GenericLexer, Utf16String};
+use libhttp_rust::http::{
+ collect_an_http_quoted_string_extracting_the_value, is_http_tab_or_space, is_http_token_code_point,
+};
+use libjs_rust::api::{Trace, Vm};
+
+use crate::bindings::interface::{Wrappable, allocate, cell_into_abi};
+use crate::bindings::{CallContext, WebIdlResult};
+use crate::html::numbers::parse_floating_point_number;
+
+fn consume_token<'a>(lexer: &mut GenericLexer<'a, u8>) -> &'a [u8] {
+ let token = lexer.consume_while(is_http_token_code_point);
+ lexer.ignore_while(is_http_tab_or_space);
+ token
+}
+
+// https://w3c.github.io/server-timing/#dfn-parse-a-server-timing-header-field
+// INTEROP: The parsing algorithm in the spec accepts metric names and parameter values that are not tokens, and matches
+// parameter names case-sensitively. Other engines and WPT instead follow the ABNF of the header field, which is
+// what we do here:
+//
+// Server-Timing = #server-timing-metric
+// server-timing-metric = metric-name *( OWS ";" OWS server-timing-param )
+// metric-name = token
+// server-timing-param = server-timing-param-name OWS "=" OWS server-timing-param-value
+// server-timing-param-name = token
+// server-timing-param-value = token / quoted-string
+//
+// Parameter names are matched ASCII case-insensitively, only the first instance of each parameter is
+// considered, and extraneous characters after a metric name or a parameter value are ignored.
+fn parse_a_server_timing_header_field(field: &[u8]) -> Option<PerformanceServerTiming> {
+ let mut lexer = GenericLexer::new(field);
+
+ lexer.ignore_while(is_http_tab_or_space);
+
+ let name = consume_token(&mut lexer);
+ if name.is_empty() {
+ return None;
+ }
+
+ let mut metric = PerformanceServerTiming {
+ metric_name: String::from_utf8(name.to_vec()).expect("a token is ASCII"),
+ params: HashMap::new(),
+ };
+
+ lexer.ignore_until(b';');
+
+ while lexer.consume_specific(b';') {
+ lexer.ignore_while(is_http_tab_or_space);
+
+ let param_name = consume_token(&mut lexer);
+ if param_name.is_empty() {
+ break;
+ }
+
+ let mut param_value = String::new();
+ if lexer.consume_specific(b'=') {
+ lexer.ignore_while(is_http_tab_or_space);
+
+ if lexer.peek() == Some(b'"') {
+ let quoted_string = collect_an_http_quoted_string_extracting_the_value(&mut lexer);
+ if quoted_string.closed {
+ // NB: A quoted-string can contain obs-text, which is not necessarily valid UTF-8.
+ param_value = String::from_utf8_lossy(&quoted_string.value).into_owned();
+ }
+ } else {
+ param_value = String::from_utf8(consume_token(&mut lexer).to_vec()).expect("a token is ASCII");
+ }
+
+ lexer.ignore_until(b';');
+ }
+
+ let lowercase_param_name = String::from_utf8(param_name.to_ascii_lowercase()).expect("a token is ASCII");
+ metric.params.entry(lowercase_param_name).or_insert(param_value);
+ }
+
+ Some(metric)
+}
+
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct PerformanceServerTiming {
+ // https://w3c.github.io/server-timing/#dfn-metric-name
+ metric_name: String,
+
+ // https://w3c.github.io/server-timing/#dfn-params
+ params: HashMap<String, String>,
+}
+
+impl Wrappable for PerformanceServerTiming {}
+
+impl PerformanceServerTiming {
+ // https://w3c.github.io/server-timing/#dom-performanceservertiming-name
+ pub(crate) fn name(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ Ok(Utf16String::from_utf8(&self.metric_name))
+ }
+
+ // https://w3c.github.io/server-timing/#dom-performanceservertiming-duration
+ pub(crate) fn duration(&self, _: &mut CallContext) -> WebIdlResult<f64> {
+ // 1. If this’s params["dur"] does not exist, return 0.
+ let Some(dur_param) = self.params.get("dur") else {
+ return Ok(0.0);
+ };
+
+ // 2. Let dur be the result of parsing this’s params["dur"] using the rules for parsing floating-point number
+ // values.
+ let dur = parse_floating_point_number(dur_param);
+
+ // 3. If dur is an error, return 0; Otherwise return dur.
+ Ok(dur.unwrap_or(0.0))
+ }
+
+ // https://w3c.github.io/server-timing/#dom-performanceservertiming-description
+ pub(crate) fn description(&self, _: &mut CallContext) -> WebIdlResult<Utf16String> {
+ // The description getter steps are to return this’s params["desc"] if it exists, otherwise the empty string.
+ Ok(Utf16String::from_utf8(
+ self.params.get("desc").map_or("", String::as_str),
+ ))
+ }
+}
+
+/// # Safety
+///
+/// `vm` must be the live VM.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_performance_server_timing_parse_a_server_timing_header_field(
+ vm: *mut c_void,
+ field: ak::Span<'_, u8>,
+) -> *mut c_void {
+ let Some(metric) = parse_a_server_timing_header_field(field.as_slice()) else {
+ return core::ptr::null_mut();
+ };
+ // SAFETY: The caller passes the live VM.
+ let vm = unsafe { &*vm.cast::<Vm>() };
+ cell_into_abi(allocate(vm, |_| metric))
+}
diff --git a/Libraries/LibWeb/HTML/Numbers.cpp b/Libraries/LibWeb/HTML/Numbers.cpp
index 567ffb0c1bc..5c8ae4be5a0 100644
--- a/Libraries/LibWeb/HTML/Numbers.cpp
+++ b/Libraries/LibWeb/HTML/Numbers.cpp
@@ -460,4 +460,19 @@ WebIDL::ExceptionOr<String> convert_non_negative_integer_to_string(WebIDL::Long
return String::number(value);
}
+extern "C" {
+
+// Called from Bindings/Rust/src/html/numbers.rs.
+bool web_html_parse_floating_point_number(ReadonlyBytes string, double* value);
+}
+
+bool web_html_parse_floating_point_number(ReadonlyBytes string, double* value)
+{
+ auto result = parse_floating_point_number(Utf16String::from_utf8(StringView { string }));
+ if (!result.has_value())
+ return false;
+ *value = *result;
+ return true;
+}
+
}
diff --git a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.cpp b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.cpp
index ef81b3df0e5..5aeb849fae4 100644
--- a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.cpp
+++ b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.cpp
@@ -4,133 +4,21 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/GenericLexer.h>
-#include <AK/StringBuilder.h>
-#include <AK/Utf16String.h>
-#include <LibGC/Heap.h>
-#include <LibHTTP/HTTP.h>
-#include <LibWeb/HTML/Numbers.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
#include <LibWeb/ServerTiming/PerformanceServerTiming.h>
namespace Web::ServerTiming {
-GC_DEFINE_ALLOCATOR(PerformanceServerTiming);
+extern "C" {
-PerformanceServerTiming::PerformanceServerTiming(String metric_name)
- : m_metric_name(move(metric_name))
-{
+// Defined in Bindings/Rust/src/server_timing/performance_server_timing.rs.
+void* web_performance_server_timing_parse_a_server_timing_header_field(JSVM*, ReadonlyBytes field);
}
-PerformanceServerTiming::~PerformanceServerTiming() = default;
-
-// NB: Consumes a quoted-string, and returns its value with the quoted-pairs unescaped. Returns an empty Optional if
-// the quoted-string is not terminated.
-static Optional<String> consume_quoted_string(GenericLexer& lexer)
-{
- VERIFY(lexer.next_is('"'));
- lexer.ignore(1);
-
- StringBuilder builder;
- while (!lexer.is_eof()) {
- auto code_point = lexer.consume();
- if (code_point == '"') {
- lexer.ignore_while(HTTP::is_http_tab_or_space);
- // NB: A quoted-string can contain obs-text, which is not necessarily valid UTF-8.
- return String::from_utf8_with_replacement_character(builder.string_view(), String::WithBOMHandling::No);
- }
- if (code_point == '\\') {
- if (lexer.is_eof())
- return {};
- code_point = lexer.consume();
- }
- builder.append(code_point);
- }
- return {};
-}
-
-// https://w3c.github.io/server-timing/#dfn-parse-a-server-timing-header-field
-// INTEROP: The parsing algorithm in the spec accepts metric names and parameter values that are not tokens, and matches
-// parameter names case-sensitively. Other engines and WPT instead follow the ABNF of the header field, which is
-// what we do here:
-//
-// Server-Timing = #server-timing-metric
-// server-timing-metric = metric-name *( OWS ";" OWS server-timing-param )
-// metric-name = token
-// server-timing-param = server-timing-param-name OWS "=" OWS server-timing-param-value
-// server-timing-param-name = token
-// server-timing-param-value = token / quoted-string
-//
-// Parameter names are matched ASCII case-insensitively, only the first instance of each parameter is
-// considered, and extraneous characters after a metric name or a parameter value are ignored.
GC::Ptr<PerformanceServerTiming> PerformanceServerTiming::parse_a_server_timing_header_field(StringView field)
{
- GenericLexer lexer { field };
-
- auto consume_token = [&] {
- auto token = lexer.consume_while(HTTP::is_http_token_code_point);
- lexer.ignore_while(HTTP::is_http_tab_or_space);
- return token;
- };
-
- lexer.ignore_while(HTTP::is_http_tab_or_space);
-
- auto name = consume_token();
- if (name.is_empty())
- return nullptr;
-
- auto metric = GC::Heap::the().allocate<PerformanceServerTiming>(MUST(String::from_utf8(name)));
-
- lexer.ignore_until(';');
-
- while (lexer.consume_specific(';')) {
- lexer.ignore_while(HTTP::is_http_tab_or_space);
-
- auto param_name = consume_token();
- if (param_name.is_empty())
- break;
-
- String param_value;
- if (lexer.consume_specific('=')) {
- lexer.ignore_while(HTTP::is_http_tab_or_space);
-
- if (lexer.next_is('"')) {
- param_value = consume_quoted_string(lexer).value_or({});
- } else {
- param_value = MUST(String::from_utf8(consume_token()));
- }
-
- lexer.ignore_until(';');
- }
-
- auto lowercase_param_name = MUST(String::from_utf8(param_name)).to_ascii_lowercase();
- if (!metric->m_params.contains(lowercase_param_name))
- metric->m_params.set(move(lowercase_param_name), move(param_value));
- }
-
- return metric;
-}
-
-// https://w3c.github.io/server-timing/#dom-performanceservertiming-duration
-HighResolutionTime::DOMHighResTimeStamp PerformanceServerTiming::duration() const
-{
- // 1. If this’s params["dur"] does not exist, return 0.
- auto dur_param = m_params.get("dur"sv);
- if (!dur_param.has_value())
- return 0;
-
- // 2. Let dur be the result of parsing this’s params["dur"] using the rules for parsing floating-point number
- // values.
- auto dur = HTML::parse_floating_point_number(Utf16String::from_utf8(*dur_param));
-
- // 3. If dur is an error, return 0; Otherwise return dur.
- return dur.value_or(0);
-}
-
-// https://w3c.github.io/server-timing/#dom-performanceservertiming-description
-String PerformanceServerTiming::description() const
-{
- // The description getter steps are to return this’s params["desc"] if it exists, otherwise the empty string.
- return m_params.get("desc"sv).value_or(String {});
+ return static_cast<PerformanceServerTiming*>(web_performance_server_timing_parse_a_server_timing_header_field(JS::HostABI::vm_to_abi(JS::VM::the()), field.bytes()));
}
}
diff --git a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.h b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.h
index c7a45a021fb..2bcb9f51999 100644
--- a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.h
+++ b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.h
@@ -6,35 +6,19 @@
#pragma once
-#include <AK/HashMap.h>
-#include <AK/String.h>
-#include <LibWeb/Bindings/Wrappable.h>
-#include <LibWebCommon/HighResolutionTime/DOMHighResTimeStamp.h>
+#include <AK/StringView.h>
+#include <LibGC/Ptr.h>
+#include <LibWeb/Bindings/PerformanceServerTiming.h>
+#include <LibWeb/Bindings/RustInterface.h>
namespace Web::ServerTiming {
// https://w3c.github.io/server-timing/#the-performanceservertiming-interface
-class PerformanceServerTiming final : public Bindings::GCAllocatedWrappable {
- WEB_WRAPPABLE(PerformanceServerTiming, Bindings::GCAllocatedWrappable);
- GC_DECLARE_ALLOCATOR(PerformanceServerTiming);
+class PerformanceServerTiming : public Bindings::RustInterfaceCell {
+ WEB_RUST_INTERFACE(PerformanceServerTiming, performance_server_timing)
public:
static GC::Ptr<PerformanceServerTiming> parse_a_server_timing_header_field(StringView field);
-
- virtual ~PerformanceServerTiming() override;
-
- String const& name() const { return m_metric_name; }
- HighResolutionTime::DOMHighResTimeStamp duration() const;
- String description() const;
-
-private:
- explicit PerformanceServerTiming(String metric_name);
-
- // https://w3c.github.io/server-timing/#dfn-metric-name
- String m_metric_name;
-
- // https://w3c.github.io/server-timing/#dfn-params
- OrderedHashMap<String, String> m_params;
};
}
diff --git a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.idl b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.idl
index 9856fe8246d..9f4bbab5600 100644
--- a/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.idl
+++ b/Libraries/LibWeb/ServerTiming/PerformanceServerTiming.idl
@@ -1,5 +1,5 @@
// https://w3c.github.io/server-timing/#the-performanceservertiming-interface
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface PerformanceServerTiming {
readonly attribute DOMString name;
readonly attribute DOMHighResTimeStamp duration;