Skip to content

Truly independent web browser

LibWeb: Wait for the EventSource reconnection time with a timer

Tim Ledbetterf698fd7b9f36
diff --git a/Libraries/LibWeb/HTML/EventSource.cpp b/Libraries/LibWeb/HTML/EventSource.cpp
index 4464ba02c85..533e659b4a3 100644
--- a/Libraries/LibWeb/HTML/EventSource.cpp
+++ b/Libraries/LibWeb/HTML/EventSource.cpp
@@ -28,6 +28,7 @@
#include <LibWeb/HTML/Scripting/Environments.h>
#include <LibWeb/HTML/WindowOrWorkerGlobalScope.h>
#include <LibWeb/HighResolutionTime/TimeOrigin.h>
+#include <LibWeb/Platform/Timer.h>
namespace Web::HTML {
@@ -228,6 +229,7 @@ void EventSource::visit_edges(Cell::Visitor& visitor)
visitor.visit(m_request);
visitor.visit(m_fetch_algorithms);
visitor.visit(m_fetch_controller);
+ visitor.visit(m_reconnection_timer);
visitor.visit(m_global_object);
}
@@ -275,6 +277,8 @@ void EventSource::close()
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;
}
@@ -288,6 +292,8 @@ void EventSource::forcibly_close()
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;
}
@@ -309,11 +315,20 @@ void EventSource::announce_the_connection()
// https://html.spec.whatwg.org/multipage/server-sent-events.html#reestablish-the-connection
void EventSource::reestablish_the_connection()
{
- IGNORE_USE_IN_ESCAPING_LAMBDA bool initial_task_has_run { false };
+ // 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(), [&]() {
- ScopeGuard guard { [&]() { initial_task_has_run = true; } };
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this, 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 { [this, end_of_delay] {
+ if (m_ready_state != ReadyState::Closed)
+ 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 (m_ready_state == ReadyState::Closed)
@@ -327,41 +342,38 @@ void EventSource::reestablish_the_connection()
}));
// 2. Wait a delay equal to the reconnection time of the event source.
- HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), [&, delay_start = MonotonicTime::now()]() {
- return (MonotonicTime::now() - delay_start) >= m_reconnection_time;
- }));
-
- // 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.
- if (!initial_task_has_run) {
- HTML::main_thread_event_loop().spin_until(GC::create_function(GC::Heap::the(), [&]() { return initial_task_has_run; }));
- }
-
- // 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(), [this]() {
- // 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.
- if (m_ready_state != ReadyState::Connecting)
- return;
-
- // 2. Let request be the EventSource object's request.
- GC::Ref request { *m_request };
-
- // 3. If the EventSource object's last event ID string is not the empty string, then:
- if (!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 = m_last_event_id.to_utf8();
- // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.
- auto header = HTTP::Header::isomorphic_encode("Last-Event-ID"sv, last_event_id_value);
- request->header_list()->set(move(header));
- }
-
- // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this section.
- auto& realm = HTML::relevant_realm(relevant_global_object());
- m_fetch_controller = Fetch::Fetching::fetch(realm, request, *m_fetch_algorithms);
+ m_reconnection_timer = Platform::Timer::create_single_shot(GC::Heap::the(), m_reconnection_time, GC::create_function(GC::Heap::the(), [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:
+ HTML::queue_a_task(HTML::Task::Source::RemoteEvent, nullptr, nullptr, GC::create_function(GC::Heap::the(), [this]() {
+ // 1. If the EventSource object's readyState attribute is not set to CONNECTING, then return.
+ if (m_ready_state != ReadyState::Connecting)
+ return;
+
+ // 2. Let request be the EventSource object's request.
+ GC::Ref request { *m_request };
+
+ // 3. If the EventSource object's last event ID string is not the empty string, then:
+ if (!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 = m_last_event_id.to_utf8();
+ // 2. Set (`Last-Event-ID`, lastEventIDValue) in request's header list.
+ auto header = HTTP::Header::isomorphic_encode("Last-Event-ID"sv, last_event_id_value);
+ request->header_list()->set(move(header));
+ }
+
+ // 4. Fetch request and process the response obtained in this fashion, if any, as described earlier in this
+ // section.
+ auto& realm = HTML::relevant_realm(relevant_global_object());
+ m_fetch_controller = Fetch::Fetching::fetch(realm, request, *m_fetch_algorithms);
+ }));
}));
}
diff --git a/Libraries/LibWeb/HTML/EventSource.h b/Libraries/LibWeb/HTML/EventSource.h
index 871c9ce287d..357f97f7193 100644
--- a/Libraries/LibWeb/HTML/EventSource.h
+++ b/Libraries/LibWeb/HTML/EventSource.h
@@ -106,6 +106,7 @@ private:
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/Tests/LibWeb/TestConfig.ini b/Tests/LibWeb/TestConfig.ini
index 71215206475..4e47b75a1d4 100644
--- a/Tests/LibWeb/TestConfig.ini
+++ b/Tests/LibWeb/TestConfig.ini
@@ -273,6 +273,10 @@ Text/input/wpt-import/html/semantics/scripting-1/the-script-element/css-module/c
Text/input/wpt-import/eventsource/format-bom-2.any.html
Text/input/wpt-import/eventsource/format-bom.any.html
Text/input/wpt-import/eventsource/format-field-id-null.window.html
+Text/input/wpt-import/eventsource/format-field-retry-bogus.any.html
+Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.html
+Text/input/wpt-import/eventsource/format-field-retry.any.html
+Text/input/wpt-import/eventsource/format-field-retry.any.worker.html
Text/input/wpt-import/eventsource/request-credentials.window.html
Text/input/wpt-import/html/semantics/scripting-1/the-script-element/json-module/module.html
Text/input/wpt-import/html/semantics/scripting-1/the-script-element/css-module/charset-bom.html
diff --git a/Tests/LibWeb/Text/expected/HTML/EventSource-reconnect-after-error-event-handlers.txt b/Tests/LibWeb/Text/expected/HTML/EventSource-reconnect-after-error-event-handlers.txt
new file mode 100644
index 00000000000..9d057cbe36a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/EventSource-reconnect-after-error-event-handlers.txt
@@ -0,0 +1 @@
+opens before close: 1
diff --git a/Tests/LibWeb/Text/expected/HTML/EventSource-reestablish-the-connection-in-parallel.txt b/Tests/LibWeb/Text/expected/HTML/EventSource-reestablish-the-connection-in-parallel.txt
new file mode 100644
index 00000000000..34b20c531d2
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/HTML/EventSource-reestablish-the-connection-in-parallel.txt
@@ -0,0 +1,3 @@
+message: one
+readyState: 0
+resource timing entries: 1
diff --git a/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.txt b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.txt
new file mode 100644
index 00000000000..d222d2914e5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass EventSource: "retry" field (bogus)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.worker.txt
new file mode 100644
index 00000000000..d222d2914e5
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry-bogus.any.worker.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass EventSource: "retry" field (bogus)
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.txt b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.txt
new file mode 100644
index 00000000000..6e0fa48ff5a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass EventSource: "retry" field
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.worker.txt b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.worker.txt
new file mode 100644
index 00000000000..6e0fa48ff5a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/wpt-import/eventsource/format-field-retry.any.worker.txt
@@ -0,0 +1,6 @@
+Harness status: OK
+
+Found 1 tests
+
+1 Pass
+Pass EventSource: "retry" field
\ No newline at end of file
diff --git a/Tests/LibWeb/Text/input/HTML/EventSource-reconnect-after-error-event-handlers.html b/Tests/LibWeb/Text/input/HTML/EventSource-reconnect-after-error-event-handlers.html
new file mode 100644
index 00000000000..3e73749294b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/EventSource-reconnect-after-error-event-handlers.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const streamURL = await server.createEcho("GET", "/event-source-reconnect-after-error-event-handlers", {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream", "Access-Control-Allow-Origin": "*" },
+ body: "retry: 0\ndata: one\n\n",
+ });
+ const scriptURL = await server.createEcho("GET", "/event-source-reconnect-after-error-event-handlers.js", {
+ status: 200,
+ headers: { "Content-Type": "text/javascript", "Access-Control-Allow-Origin": "*" },
+ body: "",
+ delay_ms: 250,
+ });
+
+ const worker = new Worker(URL.createObjectURL(new Blob([`
+ const source = new EventSource(${JSON.stringify(streamURL)});
+ let opens = 0;
+ let errors = 0;
+ source.onopen = () => ++opens;
+ source.onerror = () => {
+ if (++errors !== 1)
+ return;
+ importScripts(${JSON.stringify(scriptURL)});
+ source.close();
+ postMessage(opens);
+ };
+ `])));
+ const opens = await new Promise(resolve => (worker.onmessage = event => resolve(event.data)));
+ worker.terminate();
+ println(`opens before close: ${opens}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/HTML/EventSource-reestablish-the-connection-in-parallel.html b/Tests/LibWeb/Text/input/HTML/EventSource-reestablish-the-connection-in-parallel.html
new file mode 100644
index 00000000000..3d9f5b500a7
--- /dev/null
+++ b/Tests/LibWeb/Text/input/HTML/EventSource-reestablish-the-connection-in-parallel.html
@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const url = await server.createEcho("GET", "/event-source-reestablish-the-connection-in-parallel", {
+ status: 200,
+ headers: { "Content-Type": "text/event-stream", "Access-Control-Allow-Origin": "*" },
+ body: "data: one\n\n",
+ });
+
+ const source = new EventSource(url);
+ await new Promise(resolve => {
+ source.onmessage = event => println(`message: ${event.data}`);
+ source.onerror = () => {
+ println(`readyState: ${source.readyState}`);
+ println(`resource timing entries: ${performance.getEntriesByName(url).length}`);
+ source.close();
+ resolve();
+ };
+ });
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.html b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.html
new file mode 100644
index 00000000000..ded90746a8b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>EventSource: "retry" field (bogus)</title>
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../eventsource/format-field-retry-bogus.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.js b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.js
new file mode 100644
index 00000000000..86d9b9ea409
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.js
@@ -0,0 +1,19 @@
+// META: title=EventSource: "retry" field (bogus)
+ var test = async_test()
+ test.step(function() {
+ var timeoutms = 3000,
+ source = new EventSource("resources/message.py?message=retry%3A3000%0Aretry%3A1000x%0Adata%3Ax"),
+ opened = 0
+ source.onopen = function() {
+ test.step(function() {
+ if(opened == 0)
+ opened = new Date().getTime()
+ else {
+ var diff = (new Date().getTime()) - opened
+ assert_true(Math.abs(1 - diff / timeoutms) < 0.25) // allow 25% difference
+ this.close();
+ test.done()
+ }
+ }, this)
+ }
+ })
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.html b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.html
new file mode 100644
index 00000000000..87ecad57a7e
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>EventSource: "retry" field (bogus)</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+fetch_tests_from_worker(new Worker("../eventsource/format-field-retry-bogus.any.worker.js"));
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.js b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.js
new file mode 100644
index 00000000000..4d596a817aa
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry-bogus.any.worker.js
@@ -0,0 +1,10 @@
+
+self.GLOBAL = {
+ isWindow: function() { return false; },
+ isWorker: function() { return true; },
+ isShadowRealm: function() { return false; },
+};
+importScripts("/resources/testharness.js");
+self.META_TITLE = "EventSource: \"retry\" field (bogus)";
+importScripts("/eventsource/format-field-retry-bogus.any.js");
+done();
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.html b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.html
new file mode 100644
index 00000000000..112f32a159f
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>EventSource: "retry" field</title>
+<script>
+self.GLOBAL = {
+ isWindow: function() { return true; },
+ isWorker: function() { return false; },
+ isShadowRealm: function() { return false; },
+};
+</script>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+
+<div id=log></div>
+<script src="../eventsource/format-field-retry.any.js"></script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.js b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.js
new file mode 100644
index 00000000000..819241dbd40
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.js
@@ -0,0 +1,21 @@
+// META: title=EventSource: "retry" field
+ var test = async_test();
+ test.step(function() {
+ var timeoutms = 3000,
+ timeoutstr = "03000", // 1536 in octal, but should be 3000
+ source = new EventSource("resources/message.py?message=retry%3A" + timeoutstr + "%0Adata%3Ax"),
+ opened = 0
+ source.onopen = function() {
+ test.step(function() {
+ if(opened == 0)
+ opened = new Date().getTime()
+ else {
+ var diff = (new Date().getTime()) - opened
+ assert_true(Math.abs(1 - diff / timeoutms) < 0.25) // allow 25% difference
+ this.close();
+ test.done()
+ }
+ }, this)
+ }
+ })
+
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.html b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.html
new file mode 100644
index 00000000000..3543c6b3083
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.html
@@ -0,0 +1,9 @@
+<!doctype html>
+<meta charset=utf-8>
+<title>EventSource: "retry" field</title>
+<script src="../resources/testharness.js"></script>
+<script src="../resources/testharnessreport.js"></script>
+<div id=log></div>
+<script>
+fetch_tests_from_worker(new Worker("../eventsource/format-field-retry.any.worker.js"));
+</script>
diff --git a/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.js b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.js
new file mode 100644
index 00000000000..accadde1fa1
--- /dev/null
+++ b/Tests/LibWeb/Text/input/wpt-import/eventsource/format-field-retry.any.worker.js
@@ -0,0 +1,10 @@
+
+self.GLOBAL = {
+ isWindow: function() { return false; },
+ isWorker: function() { return true; },
+ isShadowRealm: function() { return false; },
+};
+importScripts("/resources/testharness.js");
+self.META_TITLE = "EventSource: \"retry\" field";
+importScripts("/eventsource/format-field-retry.any.js");
+done();