Skip to content

Truly independent web browser

LibWeb: Implement EventSource in Rust

Shannon Booth5155ef3eb922
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
index 1ad6bf298a8..90bfcd24b9a 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/event_target.rs
@@ -75,6 +75,7 @@ unsafe extern "C" {
ports: *const *mut c_void,
count: usize,
origin: *const FfiOrigin,
+ last_event_id: ak::Span<'_, u8>,
source: *mut c_void,
) -> *mut c_void;
fn web_bindings_message_event_data(event: u64) -> u64;
@@ -287,12 +288,13 @@ impl CppEvent {
data: Value,
ports: &[Gc<Object>],
origin: Option<&Origin>,
+ last_event_id: &str,
source: Option<&CppCell>,
) -> Self {
let ports: Vec<*mut c_void> = ports.iter().map(|port| port.as_ptr().cast()).collect();
let create = |origin: *const FfiOrigin| {
- // SAFETY: The realm, the data, the ports and the source are live, the type, the ports and the origin are
- // lent for the call, and LibWeb returns a live event.
+ // SAFETY: The realm, the data, the ports and the source are live, the type, the ports, the origin and the
+ // last event ID are lent for the call, and LibWeb returns a live event.
Self(unsafe {
CppCell::from_raw(web_bindings_create_message_event(
realm.as_ptr().cast(),
@@ -301,6 +303,7 @@ impl CppEvent {
ports.as_ptr(),
ports.len(),
origin,
+ ak::Span::new(last_event_id.as_bytes()),
source.map_or(core::ptr::null_mut(), CppCell::as_ptr),
))
})
diff --git a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
index b907bc545d2..de02c2204fc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/bindings/promise.rs
@@ -81,6 +81,7 @@ pub(crate) enum TaskSource {
Clipboard = 17,
Permissions = 18,
FontLoading = 19,
+ RemoteEvent = 20,
Gamepad = 25,
WebGL = 26,
Crypto = 27,
diff --git a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs
index ec6bf6433f0..8941b8428dd 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/fetch/infrastructure/http/requests.rs
@@ -9,6 +9,7 @@ use core::ptr::NonNull;
unsafe extern "C" {
fn web_fetch_request_done(request: *mut c_void) -> bool;
+ fn web_fetch_request_set_header(request: *mut c_void, name: ak::Span<'_, u8>, value: ak::Span<'_, u8>);
fn web_fetch_request_unref(request: *mut c_void);
}
@@ -32,6 +33,12 @@ impl CppRequest {
// SAFETY: This holds a reference to the request.
unsafe { web_fetch_request_done(self.0.as_ptr()) }
}
+
+ /// https://fetch.spec.whatwg.org/#concept-header-list-set
+ pub(crate) fn set_header(&self, name: &[u8], value: &[u8]) {
+ // SAFETY: This holds a reference to the request, and the name and the value are lent for the call.
+ unsafe { web_fetch_request_set_header(self.0.as_ptr(), ak::Span::new(name), ak::Span::new(value)) };
+ }
}
impl Drop for CppRequest {
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
index 919169edfc5..f7219066fea 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/broadcast_channel.rs
@@ -339,6 +339,7 @@ impl BroadcastChannel {
Value::NULL,
&[],
Some(&message.source_origin),
+ "",
None,
);
event.set_is_trusted(true);
@@ -348,8 +349,15 @@ impl BroadcastChannel {
// 4. Fire an event named message at destination, using MessageEvent, with the data attribute initialized to data and
// its origin initialized to sourceOrigin.
- let event =
- CppEvent::create_message_event(target_realm, "message", data, &[], Some(&message.source_origin), None);
+ let event = CppEvent::create_message_event(
+ target_realm,
+ "message",
+ data,
+ &[],
+ Some(&message.source_origin),
+ "",
+ None,
+ );
event.set_is_trusted(true);
destination.event_target.dispatch_event(&event);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs b/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs
new file mode 100644
index 00000000000..ccc4b4fc586
--- /dev/null
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/event_source.rs
@@ -0,0 +1,662 @@
+/*
+ * Copyright (c) 2024, Tim Flynn <[email protected]>
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! EventSource, https://html.spec.whatwg.org/multipage/server-sent-events.html#the-eventsource-interface
+
+use core::cell::{Cell, OnceCell, RefCell};
+use core::ffi::c_void;
+use core::ptr::NonNull;
+use std::time::{Duration, Instant};
+
+use ak::Utf16String;
+use libjs_rust::api::{EmbedderCell, Gc, GcRefCell, GcWeak, MarkedVec, PrimitiveString, Realm, Trace, Value, Vm};
+use liburl_rust::url::ExcludeFragment;
+use liburl_rust::{RustUrl, Url};
+
+use crate::bindings::conversions::UsvString;
+use crate::bindings::environment_settings_object::relevant_settings_object;
+use crate::bindings::event_target::{CppEvent, CppEventTarget, GetTheParent};
+use crate::bindings::interface::{Ref, Wrappable, Wrapped, allocate, cell_into_abi};
+use crate::bindings::promise::{TaskSource, queue_a_task};
+use crate::bindings::{CallContext, Exception, WebIdlResult};
+use crate::fetch::infrastructure::fetch_controller::CppFetchController;
+use crate::fetch::infrastructure::http::requests::CppRequest;
+use crate::fetch::infrastructure::http::response_view::CppResponseView;
+use crate::platform::timer::CppTimer;
+
+unsafe extern "C" {
+ fn web_html_event_source_create_request(
+ settings: *mut c_void,
+ url: *const RustUrl,
+ use_credentials: bool,
+ ) -> *mut c_void;
+ fn web_html_event_source_fetch(realm: *mut c_void, request: *mut c_void, event_source: *mut c_void) -> *mut c_void;
+ fn web_html_event_source_incrementally_read_body(
+ realm: *mut c_void,
+ response: *mut c_void,
+ event_source: *mut c_void,
+ );
+}
+
+/// The dictionary EventSourceInit of HTML/EventSource.idl.
+pub(crate) struct EventSourceInit {
+ pub(crate) with_credentials: bool,
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+#[repr(u16)]
+enum ReadyState {
+ Connecting = 0,
+ Open = 1,
+ Closed = 2,
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#eventsource
+#[derive(Trace)]
+#[gc(crate = libjs_rust)]
+pub(crate) struct EventSource {
+ event_target: CppEventTarget,
+ realm: Gc<Realm>,
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-url
+ #[gc(untraced)]
+ url: OnceCell<Url>,
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-request
+ #[gc(untraced)]
+ request: OnceCell<CppRequest>,
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-reconnection-time
+ #[gc(untraced)]
+ reconnection_time: Cell<Duration>,
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-last-event-id
+ #[gc(untraced)]
+ last_event_id: RefCell<String>,
+
+ #[gc(untraced)]
+ event_type: RefCell<String>,
+ #[gc(untraced)]
+ data: RefCell<String>,
+
+ with_credentials: Cell<bool>,
+
+ #[gc(untraced)]
+ ready_state: Cell<ReadyState>,
+
+ /// The bytes of the body that follow its last line break, and whether none of the body has been interpreted yet.
+ #[gc(untraced)]
+ pending_data: RefCell<Vec<u8>>,
+ is_start_of_stream: Cell<bool>,
+
+ /// When the delay of step 2 of reestablishing the connection ends.
+ #[gc(untraced)]
+ end_of_delay: Cell<Option<Instant>>,
+
+ fetch_controller: GcRefCell<Option<CppFetchController>>,
+ reconnection_timer: GcRefCell<Option<CppTimer>>,
+}
+
+impl Wrappable for EventSource {
+ fn relevant_realm(&self) -> Option<Gc<Realm>> {
+ Some(self.realm)
+ }
+
+ fn cpp_parent(&self) -> Option<NonNull<c_void>> {
+ self.event_target.as_cpp_parent()
+ }
+}
+
+impl GetTheParent for EventSource {
+ fn get_the_parent(&self) -> Option<CppEventTarget> {
+ None
+ }
+}
+
+/// The event sources of the thread's agent: references that do not keep them alive, which a collected event source
+/// leaves empty. The empty ones are pruned once the list has grown to twice what was live after the last pruning.
+struct EventSources {
+ event_sources: Vec<GcWeak<EmbedderCell<Wrapped<EventSource>>>>,
+ live_after_pruning: usize,
+}
+
+impl EventSources {
+ const EVENT_SOURCES_BEFORE_FIRST_PRUNING: usize = 128;
+
+ fn add(&mut self, vm: &Vm, event_source: Ref<EventSource>) {
+ if self.event_sources.len() >= (2 * self.live_after_pruning).max(Self::EVENT_SOURCES_BEFORE_FIRST_PRUNING) {
+ self.event_sources.retain(|event_source| event_source.get().is_some());
+ self.live_after_pruning = self.event_sources.len();
+ }
+ self.event_sources.push(GcWeak::new(vm.heap(), event_source));
+ }
+}
+
+thread_local! {
+ static EVENT_SOURCES: RefCell<EventSources> = const {
+ RefCell::new(EventSources {
+ event_sources: Vec::new(),
+ live_after_pruning: 0,
+ })
+ };
+}
+
+/// Forgets the event sources of the thread's agent, whose references into its heap have to go before the heap does.
+pub(crate) fn forget_event_sources_of_agent() {
+ EVENT_SOURCES.with_borrow_mut(|event_sources| {
+ event_sources.event_sources.clear();
+ event_sources.live_after_pruning = 0;
+ });
+}
+
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
+fn for_each_line(string: &str, mut callback: impl FnMut(&str)) {
+ let mut substart = 0;
+ let mut last_was_cr = false;
+ for (i, ch) in string.char_indices() {
+ if ch == '\n' {
+ if !last_was_cr {
+ callback(&string[substart..i]);
+ }
+ substart = i + 1;
+ last_was_cr = false;
+ } else if ch == '\r' {
+ callback(&string[substart..i]);
+ substart = i + 1;
+ last_was_cr = true;
+ } else {
+ last_was_cr = false;
+ }
+ }
+ if substart < string.len() {
+ callback(&string[substart..]);
+ }
+}
+
+impl EventSource {
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+ pub(crate) fn construct(
+ cx: &mut CallContext,
+ url: UsvString,
+ event_source_init_dict: EventSourceInit,
+ ) -> WebIdlResult<Ref<Self>> {
+ let vm = cx.vm();
+ let realm = cx.realm();
+
+ // 1. Let ev be a new EventSource object.
+ let ev = allocate(vm, |_| Self {
+ event_target: CppEventTarget::new(),
+ realm,
+ url: OnceCell::new(),
+ request: OnceCell::new(),
+ reconnection_time: Cell::new(Duration::from_secs(3)),
+ last_event_id: RefCell::new(String::new()),
+ event_type: RefCell::new(String::new()),
+ data: RefCell::new(String::new()),
+ with_credentials: Cell::new(false),
+ ready_state: Cell::new(ReadyState::Connecting),
+ pending_data: RefCell::new(Vec::new()),
+ is_start_of_stream: Cell::new(true),
+ end_of_delay: Cell::new(None),
+ fetch_controller: GcRefCell::new(None),
+ reconnection_timer: GcRefCell::new(None),
+ });
+ ev.event_target.set_owner(ev);
+
+ // 2. Let settings be ev's relevant settings object.
+ let settings = relevant_settings_object(realm.global_object());
+
+ // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
+ let url_record = settings.encoding_parse_url(url.as_utf16_string());
+
+ // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
+ let Some(url_record) = url_record else {
+ return Err(Exception::Dom(
+ "SyntaxError",
+ Utf16String::from_utf8(&format!(
+ "Invalid URL '{}'",
+ String::from_utf16_lossy(url.as_utf16_string().to_utf16().as_ref())
+ )),
+ ));
+ };
+
+ // 5. Set ev's url to urlRecord.
+ let url_record = ev.url.get_or_init(|| url_record);
+
+ // 6. Let corsAttributeState be Anonymous.
+ let mut use_credentials = false;
+
+ // 7. If the value of eventSourceInitDict's withCredentials member is true, then set corsAttributeState to Use Credentials
+ // and set ev's withCredentials attribute to true.
+ if event_source_init_dict.with_credentials {
+ use_credentials = true;
+ ev.with_credentials.set(true);
+ }
+
+ // Steps 8-12.
+ let rust_url = RustUrl::from_url(url_record);
+ // SAFETY: The settings object is live, the URL is lent for the call, and LibWeb hands over a reference to the
+ // request.
+ let request = unsafe {
+ CppRequest::adopt(web_html_event_source_create_request(
+ settings.as_ptr(),
+ &raw const rust_url,
+ use_credentials,
+ ))
+ };
+
+ // 13. Set ev's request to request.
+ let request = ev.request.get_or_init(|| request);
+
+ // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then
+ // reestablish the connection.
+ // NB: See process_event_source_end_of_body().
+
+ // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody and processResponse set to the
+ // following steps given response res:
+ // NB: See process_response().
+ Self::fetch(ev, request);
+ EVENT_SOURCES.with_borrow_mut(|event_sources| event_sources.add(vm, ev));
+ ev.update_pending_activity();
+
+ // 16. Return ev.
+ Ok(ev)
+ }
+
+ fn fetch(this: Ref<Self>, request: &CppRequest) {
+ // SAFETY: The realm, the request and this are live, and LibWeb returns a live fetch controller.
+ let fetch_controller = unsafe {
+ CppFetchController::from_raw(web_html_event_source_fetch(
+ this.realm.as_ptr().cast(),
+ request.as_ptr(),
+ cell_into_abi(this),
+ ))
+ };
+ this.fetch_controller.replace(Some(fetch_controller));
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+ pub(crate) fn process_event_source_end_of_body(this: Ref<Self>, vm: &Vm, response: CppResponseView) {
+ if !response.is_network_error() {
+ Self::reestablish_the_connection(this, vm);
+ }
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+ pub(crate) fn process_response(this: Ref<Self>, vm: &Vm, response: CppResponseView) {
+ let content_type_is_text_event_stream = || {
+ response.extract_mime_type().is_some_and(|content_type| {
+ let essence = content_type.essence();
+ essence.type_ == "text" && essence.subtype == "event-stream"
+ })
+ };
+
+ // 1. If res is an aborted network error, then fail the connection.
+ if response.is_network_error() && response.aborted() {
+ Self::fail_the_connection(this, vm);
+ }
+ // 2. Otherwise, if res is a network error, then reestablish the connection, unless the user agent knows that
+ // to be futile, in which case the user agent may fail the connection.
+ else if response.is_network_error() {
+ Self::reestablish_the_connection(this, vm);
+ }
+ // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` is not `text/event-stream`, then fail
+ // the connection.
+ else if response.status() != 200 || !content_type_is_text_event_stream() {
+ Self::fail_the_connection(this, vm);
+ }
+ // 4. Otherwise, announce the connection and interpret res's body line by line.
+ else {
+ Self::announce_the_connection(this, vm);
+
+ this.pending_data.borrow_mut().clear();
+ this.is_start_of_stream.set(true);
+ // SAFETY: The realm, the response and this are live.
+ unsafe {
+ web_html_event_source_incrementally_read_body(
+ this.realm.as_ptr().cast(),
+ response.as_ptr(),
+ cell_into_abi(this),
+ );
+ }
+ }
+ }
+
+ pub(crate) fn process_body_chunk(this: Ref<Self>, vm: &Vm, body: &[u8]) {
+ let mut pending_data = this.pending_data.borrow_mut();
+ pending_data.extend_from_slice(body);
+
+ let Some(last_line_break) = pending_data.iter().rposition(|byte| *byte == b'\r' || *byte == b'\n') else {
+ return;
+ };
+
+ let end_index = last_line_break + 1;
+ let response: Vec<u8> = pending_data.drain(..end_index).collect();
+ drop(pending_data);
+
+ Self::interpret_response(this, vm, &response, this.is_start_of_stream.get());
+ this.is_start_of_stream.set(false);
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-url
+ pub(crate) fn url(&self, _: &mut CallContext) -> WebIdlResult<UsvString> {
+ let url = self.url.get().expect("The constructor sets the URL");
+ Ok(UsvString::from_utf8(url.serialize(ExcludeFragment::No)))
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-withcredentials
+ pub(crate) fn with_credentials(&self, _: &mut CallContext) -> WebIdlResult<bool> {
+ Ok(self.with_credentials.get())
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate
+ pub(crate) fn ready_state(&self, _: &mut CallContext) -> WebIdlResult<u16> {
+ Ok(self.ready_state.get() as u16)
+ }
+
+ fn set_ready_state(&self, ready_state: ReadyState) {
+ self.ready_state.set(ready_state);
+ self.update_pending_activity();
+ }
+
+ fn update_pending_activity(&self) {
+ self.event_target
+ .set_has_pending_activity(self.realm, self.ready_state.get() != ReadyState::Closed);
+ }
+
+ fn abort_the_fetch(&self) {
+ if let Some(fetch_controller) = self.fetch_controller.borrow().as_ref() {
+ fetch_controller.abort(self.realm);
+ }
+ if let Some(reconnection_timer) = self.reconnection_timer.borrow().as_ref() {
+ reconnection_timer.stop();
+ }
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-close
+ pub(crate) fn close(&self, _: &mut CallContext) -> WebIdlResult<()> {
+ // The close() method must abort any instances of the fetch algorithm started for this EventSource object, and must
+ // set the readyState attribute to CLOSED.
+ self.abort_the_fetch();
+ self.set_ready_state(ReadyState::Closed);
+ Ok(())
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-forcibly-close
+ fn forcibly_close(&self) {
+ // If a user agent is to forcibly close an EventSource object (this happens when a Document object goes away
+ // permanently), the user agent must abort any instances of the fetch algorithm started for this EventSource
+ // object, and must set the readyState attribute to CLOSED.
+ self.abort_the_fetch();
+ self.set_ready_state(ReadyState::Closed);
+ }
+
+ /// Forcibly closes the event sources whose relevant realm is the realm.
+ pub(crate) fn forcibly_close_all(vm: &Vm, realm: Gc<Realm>) {
+ let event_sources = MarkedVec::new(vm);
+ EVENT_SOURCES.with_borrow(|all_event_sources| {
+ for event_source in all_event_sources.event_sources.iter().filter_map(GcWeak::get) {
+ if event_source.realm == realm {
+ event_sources.push(event_source);
+ }
+ }
+ });
+ for event_source in event_sources.values().iter() {
+ event_source.forcibly_close();
+ }
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#announce-the-connection
+ fn announce_the_connection(this: Ref<Self>, vm: &Vm) {
+ // When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute
+ // is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the
+ // EventSource object.
+ queue_a_task(vm, TaskSource::RemoteEvent, this, |_, this| {
+ if this.ready_state.get() != ReadyState::Closed {
+ this.set_ready_state(ReadyState::Open);
+ this.event_target.dispatch_event(&this.create_associated_event("open"));
+ }
+ });
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#reestablish-the-connection
+ fn reestablish_the_connection(this: Ref<Self>, vm: &Vm) {
+ // OPTIMIZATION: readyState never leaves CLOSED, so both tasks below would return without doing anything.
+ if this.ready_state.get() == ReadyState::Closed {
+ return;
+ }
+
+ this.end_of_delay
+ .set(Some(Instant::now() + this.reconnection_time.get()));
+
+ // 1. Queue a task to run the following steps:
+ queue_a_task(vm, TaskSource::RemoteEvent, this, |vm, this| {
+ // 1. If the readyState attribute is set to CLOSED, abort the task.
+ if this.ready_state.get() == ReadyState::Closed {
+ return;
+ }
+
+ // 2. Set the readyState attribute to CONNECTING.
+ this.set_ready_state(ReadyState::Connecting);
+
+ // 3. Fire an event named error at the EventSource object.
+ this.event_target.dispatch_event(&this.create_associated_event("error"));
+
+ // NB: Step 4 waits for this task to finish, and an error event handler can spin a nested event loop. So the
+ // timer for the rest of the delay of step 2 starts only once this task has finished.
+ if this.ready_state.get() != ReadyState::Closed {
+ Self::start_the_reconnection_timer(this, vm);
+ }
+ });
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#reestablish-the-connection
+ fn start_the_reconnection_timer(this: Ref<Self>, vm: &Vm) {
+ let end_of_delay = this
+ .end_of_delay
+ .get()
+ .expect("Reestablishing the connection sets the end of the delay");
+ let remaining_delay = end_of_delay.saturating_duration_since(Instant::now());
+
+ // 2. Wait a delay equal to the reconnection time of the event source.
+ let timer = CppTimer::create_single_shot(
+ vm,
+ u64::try_from(remaining_delay.as_millis()).unwrap_or(u64::MAX),
+ this,
+ |vm, this| {
+ // 3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce
+ // an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if
+ // the operating system has reported that there is no network connectivity, user agents might wait for the
+ // operating system to announce that the network connection has returned before retrying.
+
+ // 4. Wait until the aforementioned task has run, if it has not yet run.
+ // NB: The timer starts only once that task has run. See step 1.
+
+ // 5. Queue a task to run the following steps:
+ queue_a_task(vm, TaskSource::RemoteEvent, this, |_, this| {
+ // 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.
+ if this.ready_state.get() != ReadyState::Connecting {
+ return;
+ }
+
+ // 2. Let request be the EventSource object's request.
+ let request = this.request.get().expect("The constructor sets the request");
+
+ // 3. If the EventSource object's last event ID string is not the empty string, then:
+ let last_event_id = this.last_event_id.borrow();
+ if !last_event_id.is_empty() {
+ // 1. Let lastEventIDValue be the EventSource object's last event ID string, encoded as UTF-8.
+ let last_event_id_value = last_event_id.as_bytes();
+ // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.
+ request.set_header(b"Last-Event-ID", last_event_id_value);
+ }
+ drop(last_event_id);
+
+ // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this
+ // section.
+ Self::fetch(this, request);
+ });
+ },
+ );
+ this.reconnection_timer.replace(Some(timer));
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#fail-the-connection
+ fn fail_the_connection(this: Ref<Self>, vm: &Vm) {
+ // When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute
+ // is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the
+ // EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect.
+ queue_a_task(vm, TaskSource::RemoteEvent, this, |_, this| {
+ if this.ready_state.get() != ReadyState::Closed {
+ this.set_ready_state(ReadyState::Closed);
+ this.event_target.dispatch_event(&this.create_associated_event("error"));
+ }
+ });
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
+ fn interpret_response(this: Ref<Self>, vm: &Vm, response: &[u8], is_start_of_stream: bool) {
+ // Streams must be decoded using the UTF-8 decode algorithm.
+ let response = if is_start_of_stream {
+ response.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(response)
+ } else {
+ response
+ };
+ let response_string = String::from_utf8_lossy(response);
+
+ // Lines must be processed, in the order they are received, as follows:
+ for_each_line(&response_string, |line| {
+ // -> If the line is empty (a blank line)
+ if line.is_empty() {
+ // Dispatch the event, as defined below.
+ Self::dispatch_the_event(this, vm);
+ }
+ // -> If the line starts with a U+003A COLON character (:)
+ else if line.starts_with(':') {
+ // Ignore the line.
+ }
+ // -> If the line contains a U+003A COLON character (:)
+ else if let Some((field, value)) = line.split_once(':') {
+ // Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.
+ // Collect the characters on the line after the first U+003A COLON character (:), and let value be that string.
+ // If value starts with a U+0020 SPACE character, remove it from value.
+ let value = value.strip_prefix(' ').unwrap_or(value);
+
+ // Process the field using the steps described below, using field as the field name and value as the field value.
+ this.process_field(field, value);
+ }
+ // -> Otherwise, the string is not empty but does not contain a U+003A COLON character (:)
+ else {
+ // Process the field using the steps described below, using the whole line as the field name, and the empty
+ // string as the field value.
+ this.process_field(line, "");
+ }
+ });
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#processField
+ fn process_field(&self, field: &str, value: &str) {
+ match field {
+ // -> If the field name is "event"
+ "event" => {
+ // Set the event type buffer to the field value.
+ *self.event_type.borrow_mut() = value.to_owned();
+ }
+ // -> If the field name is "data"
+ "data" => {
+ // Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.
+ let mut data = self.data.borrow_mut();
+ data.push_str(value);
+ data.push('\n');
+ }
+ // -> If the field name is "id"
+ "id" => {
+ // If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value.
+ // Otherwise, ignore the field.
+ if !value.contains('\0') {
+ *self.last_event_id.borrow_mut() = value.to_owned();
+ }
+ }
+ // -> If the field name is "retry"
+ "retry" => {
+ // If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten,
+ // and set the event stream's reconnection time to that integer. Otherwise, ignore the field.
+ if value.bytes().all(|byte| byte.is_ascii_digit())
+ && let Ok(retry) = value.parse::<i64>()
+ {
+ self.reconnection_time.set(Duration::from_millis(retry.unsigned_abs()));
+ }
+ }
+ // -> Otherwise
+ _ => {
+ // The field is ignored.
+ }
+ }
+ }
+
+ // https://html.spec.whatwg.org/multipage/server-sent-events.html#dispatchMessage
+ fn dispatch_the_event(this: Ref<Self>, vm: &Vm) {
+ // 1. Set the last event ID string of the event source to the value of the last event ID buffer. The buffer does not
+ // get reset, so the last event ID string of the event source remains set to this value until the next time it is
+ // set by the server.
+ let last_event_id = this.last_event_id.borrow();
+
+ // 2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and return.
+ let mut data = this.data.borrow_mut();
+ let mut event_type = this.event_type.borrow_mut();
+ let mut data_buffer = data.as_str();
+
+ if data_buffer.is_empty() {
+ event_type.clear();
+ data.clear();
+ return;
+ }
+
+ // 3. If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
+ if let Some(stripped) = data_buffer.strip_suffix('\n') {
+ data_buffer = stripped;
+ }
+
+ // 4. Let event be the result of creating an event using MessageEvent, in the relevant realm of the EventSource object.
+ // 5. Initialize event's type attribute to "message", its data attribute to data, its origin to the origin of the event
+ // stream's final URL (i.e., the URL after redirects), and its lastEventId attribute to the last event ID string of
+ // the event source.
+ // 6. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal
+ // the value of the event type buffer.
+ let r#type = if event_type.is_empty() {
+ "message"
+ } else {
+ event_type.as_str()
+ };
+ let origin = this.url.get().expect("The constructor sets the URL").origin();
+ let event = CppEvent::create_message_event(
+ this.realm,
+ r#type,
+ Value::from_string(PrimitiveString::create(vm, Utf16String::from_utf8(data_buffer))),
+ &[],
+ Some(&origin),
+ &last_event_id,
+ None,
+ );
+
+ // 7. Set the data buffer and the event type buffer to the empty string.
+ event_type.clear();
+ data.clear();
+
+ // 8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created
+ // event at the EventSource object.
+ queue_a_task(vm, TaskSource::RemoteEvent, (this, event), |_, (this, event)| {
+ if this.ready_state.get() != ReadyState::Closed {
+ this.event_target.dispatch_event(&event);
+ }
+ });
+ }
+
+ fn create_associated_event(&self, event_name: &str) -> CppEvent {
+ CppEvent::create(self.realm, event_name, false, false, false)
+ }
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
index 7556a442342..eacd8426b2d 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/exports.rs
@@ -16,10 +16,11 @@ use core::ptr::NonNull;
use ak::Utf16String;
use libgfx_rust::image_frame::ImageFrameHandle;
-use libjs_rust::api::{Gc, MarkedVec, Object, RawNativeFunctionResult, Value, Vm};
+use libjs_rust::api::{Gc, JSVM, MarkedVec, Object, RawNativeFunctionResult, Value, Vm, vm_from_abi};
use liburl_rust::FfiOrigin;
use super::broadcast_channel::{BROADCAST_CHANNEL_MESSAGE_CLASS, BroadcastChannel, BroadcastChannelMessage};
+use super::event_source::EventSource;
use super::image_bitmap::ImageBitmap;
use super::image_bitmap_rendering_context::ImageBitmapRenderingContext;
use super::image_data::ImageData;
@@ -38,6 +39,7 @@ use crate::bindings::interface::{Interface, Ref, allocate, cell_from_abi, cell_i
use crate::bindings::structured_data::{TransferDataReader, TransferDataWriter, Transferable};
use crate::canvas_2d::canvas::Canvas;
use crate::dom::event::EventInit;
+use crate::fetch::infrastructure::http::response_view::CppResponseView;
use crate::html::port_channel::give_up_on_parked_end;
use crate::html::structured_serialize::cpp::SerializedTransferRecord;
use crate::html::structured_serialize::message_record::MessageRecord;
@@ -469,6 +471,7 @@ pub unsafe extern "C" fn web_rust_shut_down_agent(vm: *mut c_void) {
let vm = unsafe { &*vm.cast::<Vm>() };
MessagePort::shut_down_ports_of_agent(vm);
crate::html::broadcast_channel::forget_broadcast_channels_of_agent();
+ crate::html::event_source::forget_event_sources_of_agent();
crate::web_gl::context_loss::forget_contexts_of_agent();
crate::web_assembly::Agent::shut_down();
crate::indexed_db::internal::storage::shut_down_storage();
@@ -856,3 +859,81 @@ pub unsafe extern "C" fn web_text_track_cue_set_order_added(cue: *mut c_void, or
// SAFETY: The caller passes a live cell.
unsafe { AnyTextTrackCue::from_abi(cue) }.set_order_added(order_added);
}
+
+/// # Safety
+///
+/// `vm` must be the live VM, and `event_source` the live cell of an EventSource.
+unsafe fn event_source_arguments<'vm>(vm: *mut JSVM, event_source: *mut c_void) -> (&'vm Vm, Ref<EventSource>) {
+ // SAFETY: The caller passes the live VM and the live cell of an EventSource.
+ unsafe { (vm_from_abi(vm), cell_from_abi(event_source)) }
+}
+
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `event_source` the live cell of an EventSource, and `response` a live ResponseView.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_event_source_process_response(
+ vm: *mut JSVM,
+ event_source: *mut c_void,
+ response: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, the live cell of an EventSource and a live ResponseView.
+ let ((vm, event_source), response) = unsafe {
+ (
+ event_source_arguments(vm, event_source),
+ CppResponseView::from_raw(response),
+ )
+ };
+ EventSource::process_response(event_source, vm, response);
+}
+
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `event_source` the live cell of an EventSource, and `response` a live ResponseView.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_event_source_process_response_end_of_body(
+ vm: *mut JSVM,
+ event_source: *mut c_void,
+ response: *mut c_void,
+) {
+ // SAFETY: The caller passes the live VM, the live cell of an EventSource and a live ResponseView.
+ let ((vm, event_source), response) = unsafe {
+ (
+ event_source_arguments(vm, event_source),
+ CppResponseView::from_raw(response),
+ )
+ };
+ EventSource::process_event_source_end_of_body(event_source, vm, response);
+}
+
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+///
+/// # Safety
+///
+/// `vm` must be the live VM, `event_source` the live cell of an EventSource, and the bytes lent for the call.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_event_source_process_body_chunk(
+ vm: *mut JSVM,
+ event_source: *mut c_void,
+ bytes: ak::Span<'_, u8>,
+) {
+ // SAFETY: The caller passes the live VM and the live cell of an EventSource.
+ let (vm, event_source) = unsafe { event_source_arguments(vm, event_source) };
+ EventSource::process_body_chunk(event_source, vm, bytes.as_slice());
+}
+
+/// https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-forcibly-close
+///
+/// # Safety
+///
+/// `vm` must be the live VM and `realm` a live realm.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn web_rust_event_source_forcibly_close_all(vm: *mut c_void, realm: *mut c_void) {
+ // SAFETY: The caller passes the live VM and a live realm.
+ let (vm, realm) = unsafe { realm_arguments(vm, realm) };
+ EventSource::forcibly_close_all(vm, realm);
+}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
index f8d328d686e..006e9ec4f35 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/message_port.rs
@@ -516,7 +516,7 @@ impl MessagePort {
TransferRecord::discard(serialize_with_transfer_result);
let Ok(deserialize_record) = deserialize_record else {
// If this throws an exception, catch it, fire an event named messageerror at messageEventTarget, using MessageEvent, and then return.
- let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], None, None);
+ let event = CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], None, "", None);
event.set_is_trusted(true);
message_event_target.dispatch_event(&event);
return;
@@ -535,8 +535,15 @@ impl MessagePort {
}
// 7. Fire an event named message at messageEventTarget, using MessageEvent, with the data attribute initialized to messageClone and the ports attribute initialized to newPorts.
- let event =
- CppEvent::create_message_event(target_realm, "message", message_clone, &new_ports.values(), None, None);
+ let event = CppEvent::create_message_event(
+ target_realm,
+ "message",
+ message_clone,
+ &new_ports.values(),
+ None,
+ "",
+ None,
+ );
event.set_is_trusted(true);
message_event_target.dispatch_event(&event);
}
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
index 13800cf04c6..f0fb1a55a79 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/mod.rs
@@ -7,8 +7,8 @@
//! The 2D canvas contexts, with the attributes and operations of each of their mixins in the module of its IDL file,
//! the objects that they draw with, the images that they and WebGL read and write the pixels of, and the operations of
//! a path that Path2D and the contexts share. The state that the contexts share is in crate::canvas_2d. The message
-//! ports and channels of web messaging, the broadcast channels, Web Storage and the cues of text tracks are here as
-//! well.
+//! ports and channels of web messaging, the broadcast channels, server-sent events, Web Storage and the cues of text
+//! tracks are here as well.
pub(crate) mod canvas_path;
pub(crate) mod color_stops;
@@ -56,6 +56,8 @@ pub(crate) mod canvas_text_drawing_styles;
#[cfg(not(test))]
pub(crate) mod canvas_transform;
#[cfg(not(test))]
+pub(crate) mod event_source;
+#[cfg(not(test))]
pub(crate) mod exports;
#[cfg(not(test))]
pub(crate) mod global_event_handlers;
diff --git a/Libraries/LibWeb/Bindings/Rust/src/html/window.rs b/Libraries/LibWeb/Bindings/Rust/src/html/window.rs
index 99cc9c5ec4a..58c3c7251cc 100644
--- a/Libraries/LibWeb/Bindings/Rust/src/html/window.rs
+++ b/Libraries/LibWeb/Bindings/Rust/src/html/window.rs
@@ -241,7 +241,7 @@ fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMess
// with its origin initialized to origin and the source attribute initialized to source, and then return.
let Ok(deserialize_record) = deserialize_record else {
let event =
- CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], Some(origin), source);
+ CppEvent::create_message_event(target_realm, "messageerror", Value::NULL, &[], Some(origin), "", source);
event.set_is_trusted(true);
target_window.dispatch_event(&event);
return;
@@ -269,6 +269,7 @@ fn posted_message_task_steps(vm: &Vm, posted_message: Gc<EmbedderCell<PostedMess
message_clone,
&new_ports.values(),
Some(origin),
+ "",
source,
);
event.set_is_trusted(true);
diff --git a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
index dbb25ef1de8..80a382c551c 100644
--- a/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
+++ b/Libraries/LibWeb/Bindings/RustBindingsServices.cpp
@@ -547,6 +547,7 @@ static_assert(to_underlying(HTML::Task::Source::FileReading) == 13);
static_assert(to_underlying(HTML::Task::Source::PerformanceTimeline) == 15);
static_assert(to_underlying(HTML::Task::Source::Clipboard) == 17);
static_assert(to_underlying(HTML::Task::Source::Permissions) == 18);
+static_assert(to_underlying(HTML::Task::Source::RemoteEvent) == 20);
static_assert(to_underlying(HTML::Task::Source::WebGL) == 26);
static_assert(to_underlying(HTML::Task::Source::Crypto) == 27);
static_assert(to_underlying(HTML::Task::Source::Storage) == 29);
diff --git a/Libraries/LibWeb/Bindings/RustEventTarget.cpp b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
index bca0b13ba6f..6d85ab13e50 100644
--- a/Libraries/LibWeb/Bindings/RustEventTarget.cpp
+++ b/Libraries/LibWeb/Bindings/RustEventTarget.cpp
@@ -119,7 +119,7 @@ void web_bindings_add_event_listener_without_options(DOM::EventTarget*, Readonly
void web_bindings_remove_event_listener_without_options(DOM::EventTarget*, ReadonlyBytes type, WebIDL::CallbackType*);
DOM::Event* web_bindings_create_event(void* realm, ReadonlyBytes type, bool bubbles, bool cancelable, bool composed);
RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubbles, bool cancelable, bool composed);
-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, HTML::WindowProxy* source);
+DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, ReadonlyBytes last_event_id, HTML::WindowProxy* source);
JSValue web_bindings_message_event_data(JSValue event);
void web_bindings_set_event_owner(RustEvent*, u16 interface_name, RustInterfaceCell* owner);
void web_bindings_event_set_is_trusted(DOM::Event*, bool is_trusted);
@@ -212,11 +212,12 @@ RustEvent* web_bindings_create_rust_event(void* realm, FlatPtr type, bool bubble
return RustEvent::create(Utf16FlyString::from_utf16(type_string.utf16_view()), event_init, HighResolutionTime::current_high_resolution_time(js_realm.global_object())).ptr();
}
-DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, HTML::WindowProxy* source)
+DOM::Event* web_bindings_create_message_event(void* realm, ReadonlyBytes type, JSValue data, JSObject* const* ports, size_t count, URL::FFI::FfiOrigin const* origin, ReadonlyBytes last_event_id, HTML::WindowProxy* source)
{
auto& js_realm = *static_cast<JS::Realm*>(realm);
HTML::MessageEventInit event_init;
event_init.data = JS::HostABI::value_from_abi(data);
+ event_init.last_event_id = Utf16String::from_utf8_without_validation(last_event_id);
if (source)
event_init.source = GC::Ref { *source };
for (size_t i = 0; i < count; ++i) {
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
index fea514a76c8..af34cc78286 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
@@ -22,6 +22,7 @@ extern "C" {
// Called by Bindings/Rust/src/fetch/infrastructure/http/requests.rs.
bool web_fetch_request_done(Request*);
+void web_fetch_request_set_header(Request*, ReadonlyBytes name, ReadonlyBytes value);
void web_fetch_request_unref(Request*);
}
@@ -653,6 +654,11 @@ bool web_fetch_request_done(Request* request)
return request->done();
}
+void web_fetch_request_set_header(Request* request, ReadonlyBytes name, ReadonlyBytes value)
+{
+ request->header_list()->set({ ByteString { name }, ByteString { value } });
+}
+
void web_fetch_request_unref(Request* request)
{
request->unref();
diff --git a/Libraries/LibWeb/Forward.h b/Libraries/LibWeb/Forward.h
index 8d15dec4363..aa9869de6f3 100644
--- a/Libraries/LibWeb/Forward.h
+++ b/Libraries/LibWeb/Forward.h
@@ -679,7 +679,6 @@ class ElementInternals;
class ErrorEvent;
class EventHandler;
class EventLoop;
-class EventSource;
class External;
class FormAssociatedElement;
class FormAssociatedTextControlElement;
diff --git a/Libraries/LibWeb/HTML/EventSource.cpp b/Libraries/LibWeb/HTML/EventSource.cpp
index 7f855e1485d..be04b7b6712 100644
--- a/Libraries/LibWeb/HTML/EventSource.cpp
+++ b/Libraries/LibWeb/HTML/EventSource.cpp
@@ -4,102 +4,52 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-#include <AK/ScopeGuard.h>
-#include <AK/Utf16String.h>
-#include <LibCore/EventLoop.h>
+#include <AK/ByteBuffer.h>
#include <LibGC/Heap.h>
-#include <LibJS/Runtime/PrimitiveString.h>
-#include <LibJS/Runtime/Realm.h>
-#include <LibWeb/Bindings/EventSource.h>
-#include <LibWeb/DOM/Event.h>
+#include <LibJS/HostClassBuilder.h>
+#include <LibJS/Runtime/VM.h>
+#include <LibURL/URL.h>
#include <LibWeb/Fetch/Fetching/Fetching.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
#include <LibWeb/Fetch/Infrastructure/FetchController.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
-#include <LibWeb/Fetch/Infrastructure/HTTP/MIME.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/Requests.h>
#include <LibWeb/Fetch/Infrastructure/HTTP/ResponseView.h>
#include <LibWeb/HTML/CORSSettingAttribute.h>
-#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/EventNames.h>
-#include <LibWeb/HTML/EventSource.h>
-#include <LibWeb/HTML/MessageEvent.h>
#include <LibWeb/HTML/PotentialCORSRequest.h>
#include <LibWeb/HTML/Scripting/Environments.h>
-#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
-#include <LibWeb/HighResolutionTime/TimeOrigin.h>
-#include <LibWeb/Platform/Timer.h>
namespace Web::HTML {
-GC_DEFINE_ALLOCATOR(EventSource);
+extern "C" {
-template<typename Callback>
-static void for_each_line(Utf16View string, Callback&& callback)
-{
- size_t substart = 0;
- bool last_was_cr = false;
- for (size_t i = 0; i < string.length_in_code_units(); ++i) {
- auto ch = string.code_unit_at(i);
- if (ch == '\n') {
- if (!last_was_cr)
- callback(string.substring_view(substart, i - substart));
- substart = i + 1;
- last_was_cr = false;
- } else if (ch == '\r') {
- callback(string.substring_view(substart, i - substart));
- substart = i + 1;
- last_was_cr = true;
- } else {
- last_was_cr = false;
- }
- }
- if (substart < string.length_in_code_units())
- callback(string.substring_view(substart));
+// Defined in Bindings/Rust/src/html/exports.rs.
+void web_rust_event_source_process_response(JSVM*, void* event_source, Fetch::Infrastructure::ResponseView*);
+void web_rust_event_source_process_response_end_of_body(JSVM*, void* event_source, Fetch::Infrastructure::ResponseView*);
+void web_rust_event_source_process_body_chunk(JSVM*, void* event_source, ReadonlyBytes);
+
+// Called by Bindings/Rust/src/html/event_source.rs.
+Fetch::Infrastructure::Request* web_html_event_source_create_request(EnvironmentSettingsObject*, URL::FFI::RustUrl const*, bool use_credentials);
+Fetch::Infrastructure::FetchController* web_html_event_source_fetch(void* realm, Fetch::Infrastructure::Request*, void* event_source);
+void web_html_event_source_incrementally_read_body(void* realm, Fetch::Infrastructure::ResponseView*, void* event_source);
}
-static GC::Ref<DOM::Event> create_message_event(JS::Realm& realm, Utf16FlyString const& type, Utf16View data, Utf16String const& last_event_id, URL::Origin const& origin)
+static JSVM* vm_abi()
{
- HTML::MessageEventInit init;
- init.data = JS::PrimitiveString::create(realm.vm(), Utf16String::from_utf16(data));
- init.last_event_id = last_event_id;
- return HTML::MessageEvent::create(realm.global_object(), type, init, origin);
+ return JS::HostABI::vm_to_abi(JS::VM::the());
}
// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
-WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create(WindowOrWorkerGlobalScopeMixin& global_scope, Utf16View url, EventSourceInit const& event_source_init)
+Fetch::Infrastructure::Request* web_html_event_source_create_request(EnvironmentSettingsObject* settings, URL::FFI::RustUrl const* url, bool use_credentials)
{
- // 1. Let ev be a new EventSource object.
- auto event_source = GC::Heap::the().allocate<EventSource>(global_scope.this_impl());
-
- // 2. Let settings be ev's relevant settings object.
- auto& settings = relevant_settings_object(global_scope);
-
- // 3. Let urlRecord be the result of encoding-parsing a URL given url, relative to settings.
- auto url_record = settings.encoding_parse_url(url);
-
- // 4. If urlRecord is failure, then throw a "SyntaxError" DOMException.
- if (!url_record.has_value())
- return WebIDL::SyntaxError::create(Utf16String::formatted("Invalid URL '{}'", url));
-
- // 5. Set ev's url to urlRecord.
- event_source->m_url = url_record.release_value();
-
- // 6. Let corsAttributeState be Anonymous.
- auto cors_attribute_state = CORSSettingAttribute::Anonymous;
-
- // 7. If the value of eventSourceInitDict's withCredentials member is true, then set corsAttributeState to Use Credentials
- // and set ev's withCredentials attribute to true.
- if (event_source_init.with_credentials) {
- cors_attribute_state = CORSSettingAttribute::UseCredentials;
- event_source->m_with_credentials = true;
- }
+ URL::URL url_record;
+ url_record.set_from_rust(*url);
// 8. Let request be the result of creating a potential-CORS request given urlRecord, the empty string, and corsAttributeState.
- auto request = create_potential_CORS_request(event_source->m_url, {}, cors_attribute_state);
+ auto request = create_potential_CORS_request(url_record, {}, use_credentials ? CORSSettingAttribute::UseCredentials : CORSSettingAttribute::Anonymous);
// 9. Set request's client to settings.
- request->set_client(settings.address());
+ request->set_client(settings->address());
// 10. User agents may set (`Accept`, `text/event-stream`) in request's header list.
request->header_list()->set({ "Accept"sv, "text/event-stream"sv });
@@ -110,420 +60,41 @@ WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create(WindowOrWorkerGlob
// 12. Set request's initiator type to "other".
request->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Other);
- // 13. Set ev's request to request.
- event_source->m_request = request;
+ return &request.leak_ref();
+}
- // 14. Let processEventSourceEndOfBody given response res be the following step: if res is not a network error, then
- // reestablish the connection.
- auto process_event_source_end_of_body = GC::create_function(event_source->heap(), GC::captures(event_source), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {
- if (!response->is_network_error())
- event_source->reestablish_the_connection();
- });
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+Fetch::Infrastructure::FetchController* web_html_event_source_fetch(void* realm, Fetch::Infrastructure::Request* request, void* event_source)
+{
+ GC::Ref<GC::Cell> event_source_cell = *static_cast<GC::Cell*>(event_source);
- // 15. Fetch request, with processResponseEndOfBody set to processEventSourceEndOfBody and processResponse set to the
- // following steps given response res:
Fetch::Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Fetch::Engine::BodyIntent::DeliverStreamToConsumerAgent };
- fetch_algorithms_input.process_response_end_of_body = move(process_event_source_end_of_body);
-
- fetch_algorithms_input.process_response = GC::create_function(event_source->heap(), GC::captures(event_source), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {
- auto& realm = HTML::relevant_realm(event_source->relevant_global_object());
-
+ fetch_algorithms_input.process_response_end_of_body = GC::create_function(GC::Heap::the(), GC::captures(event_source_cell), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {
+ web_rust_event_source_process_response_end_of_body(vm_abi(), event_source.ptr(), response.ptr());
+ });
+ fetch_algorithms_input.process_response = GC::create_function(GC::Heap::the(), GC::captures(event_source_cell), [](auto& event_source, GC::Ref<Fetch::Infrastructure::ResponseView> response) {
// FIXME: If the response is CORS cross-origin, we must use its internal response to query any of its data. See:
// https://github.com/whatwg/html/issues/9355
- response = response->unsafe_response();
-
- auto content_type_is_text_event_stream = [&]() {
- auto content_type = Fetch::Infrastructure::extract_mime_type(response->header_list());
- if (!content_type.has_value())
- return false;
-
- return content_type->essence() == "text/event-stream"sv;
- };
-
- // 1. If res is an aborted network error, then fail the connection.
- if (response->is_aborted_network_error()) {
- event_source->fail_the_connection();
- }
- // 2. Otherwise, if res is a network error, then reestablish the connection, unless the user agent knows that
- // to be futile, in which case the user agent may fail the connection.
- else if (response->is_network_error()) {
- event_source->reestablish_the_connection();
- }
- // 3. Otherwise, if res's status is not 200, or if res's `Content-Type` is not `text/event-stream`, then fail
- // the connection.
- else if (response->status() != 200 || !content_type_is_text_event_stream()) {
- event_source->fail_the_connection();
- }
- // 4. Otherwise, announce the connection and interpret res's body line by line.
- else {
- event_source->announce_the_connection();
-
- auto process_body_chunk = GC::create_function(GC::Heap::the(), GC::captures(event_source, ByteBuffer(), true), [](auto& event_source, auto& pending_data, auto& is_start_of_stream, ByteBuffer body) {
- if (pending_data.is_empty())
- pending_data = move(body);
- else
- pending_data.append(body);
-
- auto last_line_break = AK::StringUtils::find_any_of(pending_data, "\r\n"sv, AK::StringUtils::SearchDirection::Backward);
- if (!last_line_break.has_value())
- return;
-
- auto end_index = *last_line_break + 1;
- event_source->interpret_response(pending_data.bytes().slice(0, end_index), is_start_of_stream);
- is_start_of_stream = false;
-
- pending_data = MUST(pending_data.slice(end_index, pending_data.size() - end_index));
- });
-
- auto process_end_of_body = GC::create_function(GC::Heap::the(), []() {
- // This case is handled by `process_event_source_end_of_body` above.
- });
- auto process_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) {
- // This case is handled by `process_event_source_end_of_body` above.
- });
-
- response->body()->incrementally_read(realm, process_body_chunk, process_end_of_body, process_body_error, { realm.global_object() });
- }
+ web_rust_event_source_process_response(vm_abi(), event_source.ptr(), response->unsafe_response().ptr());
});
- event_source->m_fetch_algorithms = Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input));
- event_source->m_fetch_controller = Fetch::Fetching::fetch(HTML::relevant_realm(global_scope), request, *event_source->m_fetch_algorithms);
-
- // 16. Return ev.
- return event_source;
-}
-
-WebIDL::ExceptionOr<GC::Ref<EventSource>> EventSource::create_for_constructor(JS::Object& relevant_global_object, Utf16View url, EventSourceInit const& event_source_init)
-{
- return create(relevant_window_or_worker_global_scope(relevant_global_object), url, event_source_init);
-}
-
-EventSource::EventSource(GC::Ref<DOM::EventTarget> relevant_global_object)
- : EventTarget()
- , m_global_object(relevant_global_object)
-{
- relevant_global().register_event_source({}, *this);
-}
-
-EventSource::~EventSource() = default;
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#garbage-collection
-void EventSource::finalize()
-{
- Base::finalize();
-
- // If an EventSource object is garbage collected while its connection is still open, the user agent must abort any
- // instance of the fetch algorithm opened by this EventSource.
- if (m_ready_state != ReadyState::Closed) {
- auto& realm = HTML::relevant_realm(relevant_global_object());
- if (m_fetch_controller)
- m_fetch_controller->abort(realm, {});
- }
-
- relevant_global().unregister_event_source({}, *this);
-}
-
-void EventSource::visit_edges(Cell::Visitor& visitor)
-{
- Base::visit_edges(visitor);
- visitor.visit(m_fetch_algorithms);
- visitor.visit(m_fetch_controller);
- visitor.visit(m_reconnection_timer);
- visitor.visit(m_global_object);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onopen
-void EventSource::set_onopen(WebIDL::CallbackType* event_handler)
-{
- set_event_handler_attribute(HTML::EventNames::open, event_handler);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onopen
-WebIDL::CallbackType* EventSource::onopen()
-{
- return event_handler_attribute(HTML::EventNames::open);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onmessage
-void EventSource::set_onmessage(WebIDL::CallbackType* event_handler)
-{
- set_event_handler_attribute(HTML::EventNames::message, event_handler);
+ return Fetch::Fetching::fetch(*static_cast<JS::Realm*>(realm), *request, Fetch::Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input))).ptr();
}
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onmessage
-WebIDL::CallbackType* EventSource::onmessage()
-{
- return event_handler_attribute(HTML::EventNames::message);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onerror
-void EventSource::set_onerror(WebIDL::CallbackType* event_handler)
-{
- set_event_handler_attribute(HTML::EventNames::error, event_handler);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#handler-eventsource-onerror
-WebIDL::CallbackType* EventSource::onerror()
-{
- return event_handler_attribute(HTML::EventNames::error);
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-close
-void EventSource::close()
-{
- // The close() method must abort any instances of the fetch algorithm started for this EventSource object, and must
- // set the readyState attribute to CLOSED.
- auto& realm = HTML::relevant_realm(relevant_global_object());
- if (m_fetch_controller)
- m_fetch_controller->abort(realm, {});
- if (m_reconnection_timer)
- m_reconnection_timer->stop();
-
- m_ready_state = ReadyState::Closed;
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-forcibly-close
-void EventSource::forcibly_close()
-{
- // If a user agent is to forcibly close an EventSource object (this happens when a Document object goes away
- // permanently), the user agent must abort any instances of the fetch algorithm started for this EventSource
- // object, and must set the readyState attribute to CLOSED.
- auto& realm = HTML::relevant_realm(relevant_global_object());
- if (m_fetch_controller)
- m_fetch_controller->abort(realm, {});
- if (m_reconnection_timer)
- m_reconnection_timer->stop();
-
- m_ready_state = ReadyState::Closed;
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#announce-the-connection
-void EventSource::announce_the_connection()
-{
- // When a user agent is to announce the connection, the user agent must queue a task which, if the readyState attribute
- // is set to a value other than CLOSED, sets the readyState attribute to OPEN and fires an event named open at the
- // EventSource object.
- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {
- if (self.m_ready_state != ReadyState::Closed) {
- self.m_ready_state = ReadyState::Open;
- self.dispatch_event(self.create_associated_event(HTML::EventNames::open));
- }
- }));
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#reestablish-the-connection
-void EventSource::reestablish_the_connection()
-{
- // OPTIMIZATION: readyState never leaves CLOSED, so both tasks below would return without doing anything.
- if (m_ready_state == ReadyState::Closed)
- return;
-
- auto end_of_delay = MonotonicTime::now() + m_reconnection_time;
-
- // 1. Queue a task to run the following steps:
- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, end_of_delay), [](auto& self, auto& end_of_delay) {
- // NB: Step 4 waits for this task to finish, and an error event handler can spin a nested event loop. So the
- // timer for the rest of the delay of step 2 starts only once this task has finished.
- ScopeGuard start_the_reconnection_timer { [&self, end_of_delay] {
- if (self.m_ready_state != ReadyState::Closed)
- self.m_reconnection_timer->start(max(end_of_delay - MonotonicTime::now(), AK::Duration::zero()));
- } };
-
- // 1. If the readyState attribute is set to CLOSED, abort the task.
- if (self.m_ready_state == ReadyState::Closed)
- return;
-
- // 2. Set the readyState attribute to CONNECTING.
- self.m_ready_state = ReadyState::Connecting;
-
- // 3. Fire an event named error at the EventSource object.
- self.dispatch_event(self.create_associated_event(HTML::EventNames::error));
- }));
-
- // 2. Wait a delay equal to the reconnection time of the event source.
- m_reconnection_timer = Platform::Timer::create_single_shot(GC::Heap::the(), m_reconnection_time, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {
- // 3. Optionally, wait some more. In particular, if the previous attempt failed, then user agents might introduce
- // an exponential backoff delay to avoid overloading a potentially already overloaded server. Alternatively, if
- // the operating system has reported that there is no network connectivity, user agents might wait for the
- // operating system to announce that the network connection has returned before retrying.
-
- // 4. Wait until the aforementioned task has run, if it has not yet run.
- // NB: The timer starts only once that task has run. See step 1.
-
- // 5. Queue a task to run the following steps:
- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(self), [](auto& self) {
- // 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.
- if (self.m_ready_state != ReadyState::Connecting)
- return;
-
- // 2. Let request be the EventSource object's request.
- NonnullRefPtr request { *self.m_request };
-
- // 3. If the EventSource object's last event ID string is not the empty string, then:
- if (!self.m_last_event_id.is_empty()) {
- // 1. Let lastEventIDValue be the EventSource object's last event ID string, encoded as UTF-8.
- auto last_event_id_value = self.m_last_event_id.to_utf8();
- // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.
- request->header_list()->set({ "Last-Event-ID"sv, last_event_id_value.to_byte_string() });
- }
-
- // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this
- // section.
- auto& realm = HTML::relevant_realm(self.relevant_global_object());
- self.m_fetch_controller = Fetch::Fetching::fetch(realm, request, *self.m_fetch_algorithms);
- }));
- }));
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#fail-the-connection
-void EventSource::fail_the_connection()
-{
- // When a user agent is to fail the connection, the user agent must queue a task which, if the readyState attribute
- // is set to a value other than CLOSED, sets the readyState attribute to CLOSED and fires an event named error at the
- // EventSource object. Once the user agent has failed the connection, it does not attempt to reconnect.
- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this), [](auto& self) {
- if (self.m_ready_state != ReadyState::Closed) {
- self.m_ready_state = ReadyState::Closed;
- self.dispatch_event(self.create_associated_event(HTML::EventNames::error));
- }
- }));
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#event-stream-interpretation
-void EventSource::interpret_response(ReadonlyBytes response, bool is_start_of_stream)
+// https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource
+void web_html_event_source_incrementally_read_body(void* realm, Fetch::Infrastructure::ResponseView* response, void* event_source)
{
- // Streams must be decoded using the UTF-8 decode algorithm.
- auto response_string = Utf16String::from_utf8_with_replacement_character(response, is_start_of_stream ? Utf16String::WithBOMHandling::Yes : Utf16String::WithBOMHandling::No);
-
- // Lines must be processed, in the order they are received, as follows:
- for_each_line(response_string.utf16_view(), [&](auto line) {
- // -> If the line is empty (a blank line)
- if (line.is_empty()) {
- // Dispatch the event, as defined below.
- dispatch_the_event();
- }
- // -> If the line starts with a U+003A COLON character (:)
- else if (line.starts_with(':')) {
- // Ignore the line.
- }
- // -> If the line contains a U+003A COLON character (:)
- else if (auto index = line.find_code_unit_offset(':'); index.has_value()) {
- // Collect the characters on the line before the first U+003A COLON character (:), and let field be that string.
- auto field = line.substring_view(0, *index);
+ auto& js_realm = *static_cast<JS::Realm*>(realm);
+ GC::Ref<GC::Cell> event_source_cell = *static_cast<GC::Cell*>(event_source);
- // Collect the characters on the line after the first U+003A COLON character (:), and let value be that string.
- // If value starts with a U+0020 SPACE character, remove it from value.
- auto value = line.substring_view(*index + 1);
-
- if (value.starts_with(' '))
- value = value.substring_view(1);
-
- // Process the field using the steps described below, using field as the field name and value as the field value.
- process_field(field, value);
- }
- // -> Otherwise, the string is not empty but does not contain a U+003A COLON character (:)
- else {
- // Process the field using the steps described below, using the whole line as the field name, and the empty
- // string as the field value.
- process_field(line, {});
- }
+ auto process_body_chunk = GC::create_function(GC::Heap::the(), GC::captures(event_source_cell), [](auto& event_source, ByteBuffer bytes) {
+ web_rust_event_source_process_body_chunk(vm_abi(), event_source.ptr(), bytes);
});
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#processField
-void EventSource::process_field(Utf16View field, Utf16View value)
-{
- // -> If the field name is "event"
- if (field == u"event"sv) {
- // Set the event type buffer to the field value.
- m_event_type = Utf16FlyString::from_utf16(value);
- }
- // -> If the field name is "data"
- else if (field == u"data"sv) {
- // Append the field value to the data buffer, then append a single U+000A LINE FEED (LF) character to the data buffer.
- m_data.append(value);
- m_data.append_ascii('\n');
- }
- // -> If the field name is "id"
- else if (field == u"id"sv) {
- // If the field value does not contain U+0000 NULL, then set the last event ID buffer to the field value.
- // Otherwise, ignore the field.
- if (!value.contains('\0'))
- m_last_event_id = Utf16String::from_utf16(value);
- }
- // -> If the field name is "retry"
- else if (field == u"retry"sv) {
- // If the field value consists of only ASCII digits, then interpret the field value as an integer in base ten,
- // and set the event stream's reconnection time to that integer. Otherwise, ignore the field.
- if (all_of(value, is_ascii_digit)) {
- if (auto retry = value.to_number<i64>(TrimWhitespace::No); retry.has_value())
- m_reconnection_time = AK::Duration::from_milliseconds(*retry);
- }
- }
- // -> Otherwise
- else {
- // The field is ignored.
- }
-}
-
-// https://html.spec.whatwg.org/multipage/server-sent-events.html#dispatchMessage
-void EventSource::dispatch_the_event()
-{
- // 1. Set the last event ID string of the event source to the value of the last event ID buffer. The buffer does not
- // get reset, so the last event ID string of the event source remains set to this value until the next time it is
- // set by the server.
- auto const& last_event_id = m_last_event_id;
-
- // 2. If the data buffer is an empty string, set the data buffer and the event type buffer to the empty string and return.
- auto data_buffer = m_data.view();
-
- if (data_buffer.is_empty()) {
- m_event_type = Utf16FlyString {};
- m_data.clear();
- return;
- }
+ // NB: processEventSourceEndOfBody handles the end of the body and its errors.
+ auto process_end_of_body = GC::create_function(GC::Heap::the(), [] { });
+ auto process_body_error = GC::create_function(GC::Heap::the(), [](JS::Value) { });
- // 3. If the data buffer's last character is a U+000A LINE FEED (LF) character, then remove the last character from the data buffer.
- if (data_buffer.ends_with('\n'))
- data_buffer = data_buffer.substring_view(0, data_buffer.length_in_code_units() - 1);
-
- // 4. Let event be the result of creating an event using MessageEvent, in the relevant realm of the EventSource object.
- // 5. Initialize event's type attribute to "message", its data attribute to data, its origin to the origin of the event
- // stream's final URL (i.e., the URL after redirects), and its lastEventId attribute to the last event ID string of
- // the event source.
- // 6. If the event type buffer has a value other than the empty string, change the type of the newly created event to equal
- // the value of the event type buffer.
- auto& realm = HTML::relevant_realm(relevant_global_object());
-
- auto type = m_event_type.is_empty() ? HTML::EventNames::message : m_event_type;
- auto event = create_message_event(realm, type, data_buffer, last_event_id, m_url.origin());
-
- // 7. Set the data buffer and the event type buffer to the empty string.
- m_event_type = Utf16FlyString {};
- m_data.clear();
-
- // 8. Queue a task which, if the readyState attribute is set to a value other than CLOSED, dispatches the newly created
- // event at the EventSource object.
- HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), GC::captures(*this, event), [](auto& self, auto& event) {
- if (self.m_ready_state != ReadyState::Closed)
- self.dispatch_event(event);
- }));
-}
-
-JS::Object& EventSource::relevant_global_object() const
-{
- return HTML::relevant_global_object(relevant_global());
-}
-
-GC::Ref<DOM::Event> EventSource::create_associated_event(Utf16FlyString const& event_name) const
-{
- return DOM::Event::create(event_name,
- HighResolutionTime::current_high_resolution_time(relevant_global_object()));
-}
-
-WindowOrWorkerGlobalScopeMixin& EventSource::relevant_global() const
-{
- return HTML::relevant_window_or_worker_global_scope(*m_global_object);
+ response->body()->incrementally_read(js_realm, process_body_chunk, process_end_of_body, process_body_error, { js_realm.global_object() });
}
}
diff --git a/Libraries/LibWeb/HTML/EventSource.h b/Libraries/LibWeb/HTML/EventSource.h
deleted file mode 100644
index 8036c1ca6d7..00000000000
--- a/Libraries/LibWeb/HTML/EventSource.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2024, Tim Flynn <[email protected]>
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-#pragma once
-
-#include <AK/Span.h>
-#include <AK/Time.h>
-#include <AK/Utf16FlyString.h>
-#include <AK/Utf16String.h>
-#include <AK/Utf16StringBuilder.h>
-#include <AK/Utf16View.h>
-#include <LibGC/Ptr.h>
-#include <LibJS/Forward.h>
-#include <LibURL/URL.h>
-#include <LibWeb/DOM/EventTarget.h>
-#include <LibWeb/Forward.h>
-#include <LibWeb/Infra/SerializedURL.h>
-#include <LibWeb/WebIDL/ExceptionOr.h>
-#include <LibWebCommon/WebIDL/Types.h>
-
-namespace Web::Bindings {
-
-struct EventSourceInit;
-
-}
-
-namespace Web::HTML {
-
-using EventSourceInit = Bindings::EventSourceInit;
-
-class EventSource : public DOM::EventTarget {
- WEB_WRAPPABLE(EventSource, DOM::EventTarget);
- GC_DECLARE_ALLOCATOR(EventSource);
-
-public:
- virtual ~EventSource() override;
-
- static WebIDL::ExceptionOr<GC::Ref<EventSource>> create(WindowOrWorkerGlobalScopeMixin&, Utf16View url, EventSourceInit const&);
- static WebIDL::ExceptionOr<GC::Ref<EventSource>> create_for_constructor(JS::Object&, Utf16View url, EventSourceInit const&);
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-url
- Utf16String url() const { return utf16_string_from_url_ascii(m_url.serialize()); }
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-withcredentials
- bool with_credentials() const { return m_with_credentials; }
-
- enum class ReadyState : WebIDL::UnsignedShort {
- Connecting = 0,
- Open = 1,
- Closed = 2,
- };
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#dom-eventsource-readystate
- ReadyState ready_state() const { return m_ready_state; }
-
- void set_onopen(WebIDL::CallbackType*);
- WebIDL::CallbackType* onopen();
-
- void set_onmessage(WebIDL::CallbackType*);
- WebIDL::CallbackType* onmessage();
-
- void set_onerror(WebIDL::CallbackType*);
- WebIDL::CallbackType* onerror();
-
- void close();
- void forcibly_close();
-
-private:
- explicit EventSource(GC::Ref<DOM::EventTarget> relevant_global_object);
-
- virtual void finalize() override;
- virtual void visit_edges(Cell::Visitor&) override;
-
- void announce_the_connection();
- void reestablish_the_connection();
- void fail_the_connection();
-
- void interpret_response(ReadonlyBytes, bool is_start_of_stream);
- void process_field(Utf16View field, Utf16View value);
- void dispatch_the_event();
- JS::Object& relevant_global_object() const;
- GC::Ref<DOM::Event> create_associated_event(Utf16FlyString const&) const;
- WindowOrWorkerGlobalScopeMixin& relevant_global() const;
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-eventsource-url
- URL::URL m_url;
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-request
- RefPtr<Fetch::Infrastructure::Request> m_request;
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-reconnection-time
- AK::Duration m_reconnection_time { AK::Duration::from_seconds(3) };
-
- // https://html.spec.whatwg.org/multipage/server-sent-events.html#concept-event-stream-last-event-id
- Utf16String m_last_event_id;
-
- Utf16FlyString m_event_type;
- Utf16StringBuilder m_data;
-
- bool m_with_credentials { false };
-
- ReadyState m_ready_state { ReadyState::Connecting };
-
- GC::Ptr<Fetch::Infrastructure::FetchAlgorithms> m_fetch_algorithms;
- GC::Ptr<Fetch::Infrastructure::FetchController> m_fetch_controller;
- GC::Ptr<Platform::Timer> m_reconnection_timer;
- GC::Ref<DOM::EventTarget> m_global_object;
-};
-
-}
diff --git a/Libraries/LibWeb/HTML/EventSource.idl b/Libraries/LibWeb/HTML/EventSource.idl
index 6c0dd83d840..57626e28a3c 100644
--- a/Libraries/LibWeb/HTML/EventSource.idl
+++ b/Libraries/LibWeb/HTML/EventSource.idl
@@ -1,5 +1,5 @@
// https://html.spec.whatwg.org/multipage/server-sent-events.html#eventsource
-[Exposed=(Window,Worker)]
+[Exposed=(Window,Worker), ImplementedIn=Rust]
interface EventSource : EventTarget {
constructor(USVString url, optional EventSourceInit eventSourceInitDict = {});
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
index a22b8b3a638..62c69cb66c1 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.cpp
@@ -39,7 +39,6 @@
#include <LibWeb/Fetch/FetchMethod.h>
#include <LibWeb/HTML/CanvasRenderingContext2D.h>
#include <LibWeb/HTML/EventLoop/EventLoop.h>
-#include <LibWeb/HTML/EventSource.h>
#include <LibWeb/HTML/HTMLImageElement.h>
#include <LibWeb/HTML/ImageData.h>
#include <LibWeb/HTML/LocalNavigable.h>
@@ -109,7 +108,6 @@ void WindowOrWorkerGlobalScopeMixin::visit_edges(JS::Cell::Visitor& visitor)
{
visitor.visit(m_timers);
visitor.visit(m_indexed_db);
- visitor.visit(m_registered_event_sources);
visitor.visit(m_strongly_referenced_broadcast_channels);
visitor.visit(m_objects_with_pending_activity);
@@ -225,6 +223,7 @@ extern "C" {
// Defined in Bindings/Rust/src/canvas_2d/exports.rs.
bool web_canvas_2d_read_back_video_frame(void* video_wrapper, Optional<Gfx::DecodedImageFrame>* out_frame);
// Defined in Bindings/Rust/src/html/exports.rs.
+void web_rust_event_source_forcibly_close_all(JSVM*, void* realm);
JSCompletion web_rust_structured_clone(JSVM*, void* realm, JSValue, JSObject* const* transfer, size_t count);
// Defined in Bindings/Rust/src/performance_timeline/exports.rs.
HighResolutionTime::Performance* web_rust_performance_timeline_performance(JSVM*, void* realm);
@@ -1072,20 +1071,10 @@ void WindowOrWorkerGlobalScopeMixin::add_performance_entry(GC::Ref<PerformanceTi
web_rust_performance_timeline_add_performance_entry(JS::HostABI::vm_to_abi(realm.vm()), &realm, new_entry.ptr(), check_if_performance_buffer_is_full == CheckIfPerformanceBufferIsFull::Yes);
}
-void WindowOrWorkerGlobalScopeMixin::register_event_source(Badge<EventSource>, GC::Ref<EventSource> event_source)
-{
- m_registered_event_sources.set(event_source);
-}
-
-void WindowOrWorkerGlobalScopeMixin::unregister_event_source(Badge<EventSource>, GC::Ref<EventSource> event_source)
-{
- m_registered_event_sources.remove(event_source);
-}
-
void WindowOrWorkerGlobalScopeMixin::forcibly_close_all_event_sources()
{
- for (auto event_source : m_registered_event_sources)
- event_source->forcibly_close();
+ auto& realm = relevant_realm(*this);
+ web_rust_event_source_forcibly_close_all(JS::HostABI::vm_to_abi(realm.vm()), &realm);
}
void WindowOrWorkerGlobalScopeMixin::add_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget> channel)
diff --git a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
index 60a762cd538..0677c89e2ab 100644
--- a/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
+++ b/Libraries/LibWeb/HTML/WindowOrWorkerGlobalScope.h
@@ -69,9 +69,7 @@ public:
void queue_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry);
void add_performance_entry(GC::Ref<PerformanceTimeline::PerformanceEntry> new_entry, CheckIfPerformanceBufferIsFull check_if_performance_buffer_is_full = CheckIfPerformanceBufferIsFull::No);
- void register_event_source(Badge<EventSource>, GC::Ref<EventSource>);
void register_permission_status(DOM::EventTarget&);
- void unregister_event_source(Badge<EventSource>, GC::Ref<EventSource>);
void forcibly_close_all_event_sources();
void add_strong_reference_to_broadcast_channel(GC::Ref<DOM::EventTarget>);
@@ -177,8 +175,6 @@ private:
// When a chained timer last ran while the document was hidden (see throttled_timer_delay()).
Optional<double> m_last_chained_timer_wake_up;
- HashTable<GC::Ref<EventSource>> m_registered_event_sources;
-
// https://html.spec.whatwg.org/multipage/web-messaging.html#broadcasting-to-other-browsing-contexts
// The open BroadcastChannel objects with a message or messageerror listener, which this global keeps alive. They're
// held here rather than rooted — so a channel that's never closed can't keep its global alive.
diff --git a/Services/WebContent/Worker/WorkerHost.cpp b/Services/WebContent/Worker/WorkerHost.cpp
index b4c05c0f0d1..51378d2fef4 100644
--- a/Services/WebContent/Worker/WorkerHost.cpp
+++ b/Services/WebContent/Worker/WorkerHost.cpp
@@ -57,8 +57,7 @@ void WorkerHost::run_closing_steps()
// 16. Clear the worker global scope's map of active timers.
m_worker_global_scope->clear_map_of_active_timers();
- // NB: The connection of an EventSource goes with the worker, whose global scope is not there for the finalizer of the
- // EventSource to reach anymore.
+ // NB: The connection of an EventSource goes with the worker.
m_worker_global_scope->forcibly_close_all_event_sources();
// 17. Disentangle all the ports in the list of the worker's ports.