Skip to content
37 changes: 28 additions & 9 deletions capsules/browser/browser/browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,11 @@ let statusTimer = 0;
let canGoBack = false;
let canGoForward = false;
let pageStatusTimer = 0;
let pageStatusPollingRun = null;
let pageStatusRefreshTimers = [];
let pageStatusRefreshRun = null;
let pageHeartbeatTimer = 0;
let pageHeartbeatRun = null;
let lastPageStatus = null;
let unloadCleanupStarted = false;
let recoverableDisplayAttachStarted = false;
Expand Down Expand Up @@ -398,19 +401,22 @@ function setLoading(loading) {
}

function stopPageStatusPolling() {
pageStatusPollingRun = null;
window.clearTimeout(pageStatusTimer);
pageStatusTimer = 0;
stopPageStatusRefresh();
}

function stopPageStatusRefresh() {
pageStatusRefreshRun = null;
for (const timer of pageStatusRefreshTimers) {
window.clearTimeout(timer);
}
pageStatusRefreshTimers = [];
}

function stopPageHeartbeat() {
pageHeartbeatRun = null;
window.clearTimeout(pageHeartbeatTimer);
pageHeartbeatTimer = 0;
}
Expand Down Expand Up @@ -1249,8 +1255,9 @@ async function fetchPageStatus({
history = "replace",
forceAddress = false,
fast = false,
isCurrent = () => true,
} = {}) {
if (!currentPage?.page_id) {
if (!isCurrent() || !currentPage?.page_id) {
return null;
}
const owner = currentRuntimePageOwner();
Expand All @@ -1259,7 +1266,7 @@ async function fetchPageStatus({
`/api/apps/browser/pages/${encodeURIComponent(currentPage.page_id)}/status${query}`,
{ method: "GET" },
);
if (!runtimeViewerOwnerActive(owner)) return null;
if (!isCurrent() || !runtimeViewerOwnerActive(owner)) return null;
if (
status?.schema !== "elastos.browser.page-status/v1" ||
status.page_id !== currentPage.page_id
Expand Down Expand Up @@ -1414,12 +1421,16 @@ function schedulePageStatusRefresh({
),
];
stopPageStatusRefresh();
const run = {};
pageStatusRefreshRun = run;
const isCurrent = () => pageStatusRefreshRun === run;
pageStatusRefreshTimers = delays.map((nextDelay) => {
const timer = window.setTimeout(async () => {
pageStatusRefreshTimers = pageStatusRefreshTimers.filter(
(candidate) => candidate !== timer,
);
if (
!isCurrent() ||
unloadCleanupStarted ||
!currentPage ||
document.hidden ||
Expand All @@ -1429,9 +1440,9 @@ function schedulePageStatusRefresh({
}
const owner = currentRuntimePageOwner();
try {
await fetchPageStatus({ history, forceAddress });
await fetchPageStatus({ history, forceAddress, isCurrent });
} catch (error) {
await handlePageObservationFailure(error, owner);
if (isCurrent()) await handlePageObservationFailure(error, owner);
}
}, nextDelay);
return timer;
Expand All @@ -1440,8 +1451,11 @@ function schedulePageStatusRefresh({

function startPageStatusPolling() {
stopPageStatusPolling();
const run = {};
pageStatusPollingRun = run;
const isCurrent = () => pageStatusPollingRun === run;
const poll = async () => {
if (unloadCleanupStarted || !currentPage) {
if (!isCurrent() || unloadCleanupStarted || !currentPage) {
return;
}
if (document.hidden) {
Expand All @@ -1454,11 +1468,12 @@ function startPageStatusPolling() {
}
const owner = currentRuntimePageOwner();
try {
await fetchPageStatus({ fast: true });
await fetchPageStatus({ fast: true, isCurrent });
} catch (error) {
await handlePageObservationFailure(error, owner);
if (isCurrent()) await handlePageObservationFailure(error, owner);
} finally {
if (
isCurrent() &&
sameRuntimePageOwner(currentRuntimePageOwner(), owner) &&
!unloadCleanupStarted &&
!relaunchRequested &&
Expand All @@ -1473,8 +1488,11 @@ function startPageStatusPolling() {

function startPageHeartbeat() {
stopPageHeartbeat();
const run = {};
pageHeartbeatRun = run;
const isCurrent = () => pageHeartbeatRun === run;
const beat = async () => {
if (unloadCleanupStarted || !currentPage?.page_id) {
if (!isCurrent() || unloadCleanupStarted || !currentPage?.page_id) {
return;
}
const owner = currentRuntimePageOwner();
Expand All @@ -1485,9 +1503,10 @@ function startPageHeartbeat() {
{ method: "POST" },
);
} catch (error) {
if (await handlePageObservationFailure(error, owner)) nextDelay = PAGE_STATUS_INTERVAL_MS;
if (isCurrent() && await handlePageObservationFailure(error, owner)) nextDelay = PAGE_STATUS_INTERVAL_MS;
} finally {
if (
isCurrent() &&
sameRuntimePageOwner(currentRuntimePageOwner(), owner) &&
!unloadCleanupStarted &&
!relaunchRequested &&
Expand Down
58 changes: 55 additions & 3 deletions scripts/browser-observation-recovery.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ function deferred() {
}

const routes = {
status: { start: "startPageStatusPolling", timer: "pageStatusTimer" },
heartbeat: { start: "startPageHeartbeat", timer: "pageHeartbeatTimer" },
afterInput: { start: "schedulePageStatusRefresh", timer: "pageStatusRefreshTimers" },
status: { start: "startPageStatusPolling", stop: "stopPageStatusPolling", timer: "pageStatusTimer" },
heartbeat: { start: "startPageHeartbeat", stop: "stopPageHeartbeat", timer: "pageHeartbeatTimer" },
afterInput: { start: "schedulePageStatusRefresh", stop: "stopPageStatusRefresh", timer: "pageStatusRefreshTimers" },
};
function harness() {
const timers = new Map(), requests = [], failures = [], renewals = [], mutations = [], messages = [];
Expand All @@ -40,6 +40,7 @@ function harness() {
currentPage: { page_id: "page-current", actual_url: "https://fixture.invalid/nav", title: "Before",
runtime_cleanup: { schema: "elastos.browser.cleanup-handle/v1", id: "cleanup-current" } },
unloadCleanupStarted: false, currentPageGeneration: 1, pageStatusTimer: 0, pageHeartbeatTimer: 0, pageStatusRefreshTimers: [],
pageStatusPollingRun: null, pageStatusRefreshRun: null, pageHeartbeatRun: null,
relaunchRequested: false, lastPageStatus: null, homeWindowCloseInFlight: false,
homeWindowTerminalCloseConfirmed: false, pendingHomeWindowCloseDelivery: null,
document: { hidden: false }, isAddressEditing: () => false,
Expand Down Expand Up @@ -82,6 +83,7 @@ function harness() {
mediaOpen: () => mediaOpen,
setFetch: value => { fetch = value; },
start: route => state[routes[route].start](),
stop: route => state[routes[route].stop](),
async fire(route) {
const id = timerFor(route), timer = timers.get(id);
assert.ok(timer, `missing ${route} timer`);
Expand Down Expand Up @@ -236,6 +238,56 @@ for (const route of Object.keys(routes)) {
}
}

for (const route of Object.keys(routes)) {
for (const lifecycle of ["restart", "stop"]) {
for (const outcome of ["success", "transport", "authority", "terminal"]) {
test(`${route} ${lifecycle} retires a pending ${outcome} observation for the same page owner`, async () => {
const h = harness(), pending = deferred(), owner = h.state.currentRuntimePageOwner();
const previousStatus = { ...h.healthyStatus(), actual_url: "https://fixture.invalid/previous", title: "Previous" };
h.setFetch(() => pending.promise);
h.start(route);
const observation = h.fire(route);
assert.equal(h.requests.length, 1);
if (lifecycle === "restart") h.start(route);
else h.stop(route);
h.state.currentPage.actual_url = "https://fixture.invalid/current";
const remainingTimers = [...h.timers.keys()];
assert.equal(remainingTimers.length, lifecycle === "stop" ? 0 : route === "afterInput" ? 4 : 1);

if (outcome === "success") pending.resolve(response(previousStatus));
else if (outcome === "transport") pending.reject(new TypeError("retired observation failed"));
else pending.resolve(response({ error: "retired observation failed" }, outcome === "authority" ? 401 : 404));
await observation;

assertRetained(h, owner);
assert.equal(h.state.currentPage.actual_url, "https://fixture.invalid/current");
assert.equal(h.state.lastPageStatus, null);
assert.deepEqual(h.mutations, []);
assert.deepEqual(h.messages, []);
assert.deepEqual([...h.timers.keys()], remainingTimers,
"Retired work must leave the replacement timers unchanged");

if (lifecycle === "restart") {
if (outcome === "authority") {
h.setFetch(async () => response({ error: "auth session is not active" }, 401));
await h.fire(route);
assert.equal(h.renewals.length, 1, "The active run must still request fresh authority on HTTP 401");
assert.equal(h.timers.size, 0);
assert.deepEqual(h.failures, []);
assert.equal(h.mediaOpen(), true);
} else {
h.setFetch(async () => response(h.healthyStatus()));
await h.fire(route);
assertRetained(h, owner);
assert.equal(h.requests.length, 2, "The replacement run must continue observing");
if (route !== "heartbeat") assert.ok(h.mutations.length > 0);
}
}
});
}
}
}

for (const route of ["status", "afterInput"]) {
for (const invalid of ["schema", "page_id", "direct_network", "json"]) {
test(`${route} still handles malformed ${invalid} as a terminal observation error`, async () => {
Expand Down
4 changes: 4 additions & 0 deletions scripts/browser-window-close-handshake.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,8 @@ function createActiveAuthorityExpiryHarness(surface) {
unloadCleanupStarted: false,
pageHeartbeatTimer: 0,
pageStatusTimer: 0,
pageStatusPollingRun: null,
pageHeartbeatRun: null,
relaunchRequested: false,
browserAuthorityRenewal: null,
browserAuthorityRenewalRetryTimer: 0,
Expand Down Expand Up @@ -186,12 +188,14 @@ function createActiveAuthorityExpiryHarness(surface) {
friendlyOpenError,
showStatus() {},
stopPageStatusPolling() {
context.pageStatusPollingRun = null;
for (const [id, timer] of timers) {
if (timer.delay !== 60_000) timers.delete(id);
}
context.pageStatusTimer = 0;
},
stopPageHeartbeat() {
context.pageHeartbeatRun = null;
for (const [id, timer] of timers) {
if (timer.delay === 60_000) timers.delete(id);
}
Expand Down
Loading
Loading