Ignore navigation-cancelled requests and recover on restore

This commit is contained in:
raucao committed 2026-10-29 23:50:10 +04:00
1 parent c94fc9070b
commit 14b43ebfa6
10 files changed
+552 -1

No files matched your search

+22
View File
@@ -1,5 +1,6 @@
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { isCancellation } from './http';
export const BITCOIN_DEFAULT_INTERVAL = 30000;
@@ -54,6 +55,9 @@ function providerFor(id) {
export default class BitcoinService extends Service {
@service storage;
@service http;
@service pageLifecycle;
removeRestoreHandler = null;
@tracked enabled = false;
@tracked interval = BITCOIN_DEFAULT_INTERVAL;
@@ -70,6 +74,17 @@ export default class BitcoinService extends Service {
constructor() {
super(...arguments);
this.ready = this.load();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
// A bfcache restore may have cancelled the last price fetch, leaving a stale
// error behind. Fetch again immediately instead of waiting for the interval.
handleRestore() {
if (this.enabled) {
this.fetchPrice();
}
}
async load() {
@@ -163,6 +178,12 @@ export default class BitcoinService extends Service {
this.changePercent = changePercent;
this.error = null;
} catch (err) {
// A navigation or bfcache freeze cancels the request; keep the last
// known price and do not report a failure.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error('Error fetching bitcoin price:', err);
this.error = 'Unable to load the bitcoin price';
} finally {
@@ -187,6 +208,7 @@ export default class BitcoinService extends Service {
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
+46
View File
@@ -17,6 +17,7 @@ import {
queryMessage,
} from '../config/caldav';
import { ICS_TYPE, feedName, icsInstanceKey, readMessage } from '../config/ics';
import { isCancellation } from './http';
const CALENDAR_CONSUMER = 'calendar';
const CALENDAR_TYPES = [CALDAV_TYPE, ICS_TYPE];
@@ -39,6 +40,7 @@ export default class CalendarService extends Service {
@service storage;
@service sockethub;
@service calendarCache;
@service pageLifecycle;
@tracked instances = [];
@tracked error = null;
@@ -46,10 +48,33 @@ export default class CalendarService extends Service {
intervalId = null;
refreshPromise = null;
ready = null;
loadFailed = false;
removeRestoreHandler = null;
constructor() {
super(...arguments);
this.ready = this.load();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
// A bfcache restore leaves the Sockethub socket dropped and the last refresh
// may have stored an error. Reconnect, clear the stale message, and refresh
// immediately rather than waiting for the next interval. If the initial load
// itself was interrupted, retry it first so the instances are populated.
async handleRestore() {
if (this.loadFailed) {
await this.load();
return;
}
if (!this.enabled) {
return;
}
await this.syncConnection();
await this.refreshAll();
}
async load() {
@@ -69,10 +94,19 @@ export default class CalendarService extends Service {
)
.map(({ key, data }) => this.buildInstance(key, data));
this.loadFailed = false;
await this.syncConnection();
this.startPolling();
} catch (err) {
// An interrupted storage read (navigation or bfcache freeze) must not be
// reported as a calendar failure; `handleRestore` retries the load.
if (isCancellation(err) || this.pageLifecycle.leaving) {
this.loadFailed = true;
return;
}
console.error('Error loading calendar integrations:', err);
this.loadFailed = true;
this.error = 'Unable to load calendars';
}
}
@@ -114,6 +148,11 @@ export default class CalendarService extends Service {
await this.sockethub.acquire(CALENDAR_CONSUMER);
this.error = null;
} catch (err) {
// A navigation that tears down the socket is not a connection failure.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error('Error connecting to Sockethub for calendars:', err);
this.error = classifyCalendarError(err);
}
@@ -247,6 +286,12 @@ export default class CalendarService extends Service {
await this.refreshIcs(instance, context, window);
}
} catch (err) {
// The Sockethub socket drops when the tab is navigated away from or
// frozen; that cancellation should not surface as a calendar error.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error(`Error refreshing calendar ${instance.id}:`, err);
this.error = classifyCalendarError(err);
}
@@ -387,6 +432,7 @@ export default class CalendarService extends Service {
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
this.sockethub.release(CALENDAR_CONSUMER);
super.willDestroy();
+22
View File
@@ -22,6 +22,23 @@ export class NetworkError extends Error {
}
}
// The request was cancelled because the document was navigated away from (or
// frozen/restored), not because a target was actually unreachable. Callers
// should treat this as a no-op rather than a user-facing failure.
export class RequestAbortedError extends Error {
constructor(cause) {
super('Request was cancelled');
this.name = 'RequestAbortedError';
this.cause = cause;
}
}
// True for both the browser's own `AbortError` and the wrapper above, so
// consumers can ignore cancellations without knowing which layer raised them.
export function isCancellation(err) {
return err?.name === 'AbortError' || err?.name === 'RequestAbortedError';
}
// Rewrites an absolute http(s) URL to go through the local development CORS
// proxy. Relative URLs and URLs already pointing at the proxy are untouched.
export function proxiedUrl(url, base) {
@@ -52,6 +69,11 @@ export default class HttpService extends Service {
try {
response = await fetch(target, { ...options, headers });
} catch (err) {
// A navigation (or bfcache entry) cancels in-flight requests; that is not
// a real network failure and must not surface as an error state.
if (err?.name === 'AbortError') {
throw new RequestAbortedError(err);
}
throw new NetworkError(err);
}
+37 -1
View File
@@ -1,6 +1,6 @@
import Service, { service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { HttpError } from './http';
import { HttpError, isCancellation } from './http';
import { authorizationHeader, unreadCountUrl } from '../config/feedbin';
import {
GITHUB_ACCEPT,
@@ -177,16 +177,21 @@ export default class NotificationsService extends Service {
@service sites;
@service http;
@service homeAssistant;
@service pageLifecycle;
@tracked states = {};
intervalId = null;
fetching = false;
ready = null;
removeRestoreHandler = null;
constructor() {
super(...arguments);
this.ready = this.setup();
this.removeRestoreHandler = this.pageLifecycle.onRestore(() =>
this.handleRestore()
);
}
async setup() {
@@ -196,6 +201,30 @@ export default class NotificationsService extends Service {
}
}
// After a bfcache restore the pollers are stale and any request that was in
// flight when the tab was navigated away from can have left a site stuck in
// its error state. Clear those and fetch immediately instead of waiting for
// the next interval.
async handleRestore() {
const pollable = this.sites.all.filter((site) => this.isPollable(site));
if (pollable.length === 0) {
return;
}
for (const site of pollable) {
if (this.states[site.id]?.status === 'error') {
this.setState(site.id, {
status: 'loading',
error: null,
errorType: null,
});
}
}
await this.fetchAll();
}
isPollable(site) {
return Boolean(ADAPTERS[site.type]);
}
@@ -251,6 +280,12 @@ export default class NotificationsService extends Service {
items: result.notifications,
});
} catch (err) {
// A navigation or bfcache freeze cancels the request; that is not a
// failure and must not paint the tile as errored.
if (isCancellation(err) || this.pageLifecycle.leaving) {
return;
}
console.error(`Error fetching ${site.type} notifications:`, err);
this.setState(site.id, {
status: 'error',
@@ -323,6 +358,7 @@ export default class NotificationsService extends Service {
}
willDestroy() {
this.removeRestoreHandler?.();
this.stopPolling();
super.willDestroy();
}
+61
View File
@@ -0,0 +1,61 @@
import Service from '@ember/service';
// Tracks the page transitions that pause or discard the dashboard. Dashtab is a
// new-tab page, so it is frequently navigated away from while its integrations
// are still loading; the resulting cancelled requests and dropped sockets must
// not be mistaken for failures, and the dashboard has to recover when it is
// restored from the back/forward cache.
export default class PageLifecycleService extends Service {
// True while the document is being unloaded (a real navigation, not a
// bfcache freeze), so pollers can ignore errors raised during teardown.
leaving = false;
handlers = new Set();
constructor() {
super(...arguments);
this.onPageHide = (event) => {
this.leaving = !event.persisted;
};
this.onPageShow = (event) => {
this.leaving = false;
if (event.persisted) {
this.notifyRestore();
}
};
// The Page Lifecycle API freezes a backgrounded tab without unloading it;
// `resume` is the counterpart to `freeze` and lets us refresh a stale view.
this.onResume = () => {
this.notifyRestore();
};
window.addEventListener('pagehide', this.onPageHide);
window.addEventListener('pageshow', this.onPageShow);
window.addEventListener('resume', this.onResume);
}
// Registers a callback to run when the page is restored after being frozen or
// discarded. Returns an unsubscribe function.
onRestore(handler) {
this.handlers.add(handler);
return () => this.handlers.delete(handler);
}
notifyRestore() {
for (const handler of [...this.handlers]) {
handler();
}
}
willDestroy() {
window.removeEventListener('pagehide', this.onPageHide);
window.removeEventListener('pageshow', this.onPageShow);
window.removeEventListener('resume', this.onResume);
this.handlers.clear();
super.willDestroy();
}
}
+63
View File
@@ -205,6 +205,69 @@ module('Unit | Service | bitcoin', function (hooks) {
assert.false(service.loading);
});
test('fetchPrice keeps the last price when the request is cancelled', async function (assert) {
globalThis.fetch = async () => {
const err = new Error('The operation was aborted');
err.name = 'AbortError';
throw err;
};
const service = this.owner.lookup('service:bitcoin');
await service.ready;
service.price = 100;
await service.fetchPrice();
assert.strictEqual(service.error, null);
assert.strictEqual(service.price, 100);
assert.false(service.loading);
});
test('fetchPrice ignores failures while the page is leaving', async function (assert) {
globalThis.fetch = async () => {
throw new TypeError('Failed to fetch');
};
const service = this.owner.lookup('service:bitcoin');
await service.ready;
service.pageLifecycle.leaving = true;
await service.fetchPrice();
assert.strictEqual(service.error, null);
service.pageLifecycle.leaving = false;
});
test('handleRestore refetches when enabled', async function (assert) {
const service = this.owner.lookup('service:bitcoin');
await service.ready;
let calls = 0;
service.fetchPrice = async () => {
calls++;
};
service.enabled = true;
service.handleRestore();
assert.strictEqual(calls, 1);
});
test('handleRestore does nothing when disabled', async function (assert) {
const service = this.owner.lookup('service:bitcoin');
await service.ready;
let calls = 0;
service.fetchPrice = async () => {
calls++;
};
service.handleRestore();
assert.strictEqual(calls, 0);
});
test('fetchPrice sets an error for an unknown provider', async function (assert) {
let calls = 0;
globalThis.fetch = async () => {
+106
View File
@@ -248,6 +248,112 @@ module('Unit | Service | calendar', function (hooks) {
service.stopPolling();
});
test('a refresh cancelled by navigation does not surface an error', async function (assert) {
const { service } = await setup(this, {
handler: () => {
throw Object.assign(new Error('caldav:connection-failed'), {
name: 'SockethubPlatformError',
});
},
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
await service.refreshAll();
assert.strictEqual(service.error, 'Unable to reach the calendar server');
service.error = null;
service.pageLifecycle.leaving = true;
await service.refreshAll();
assert.strictEqual(service.error, null);
service.pageLifecycle.leaving = false;
service.stopPolling();
});
test('a refresh aborted mid-flight does not surface an error', async function (assert) {
const { service } = await setup(this, {
handler: () => {
throw Object.assign(new Error('The operation was aborted'), {
name: 'AbortError',
});
},
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
await service.refreshAll();
assert.strictEqual(service.error, null);
service.stopPolling();
});
test('handleRestore reconnects and clears a stale error', async function (assert) {
const { service, sockethub } = await setup(this, {
handler: (message) =>
message.type === 'query' ? { items: [EVENT] } : { items: [] },
});
await service.configureCaldav({
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
});
// Simulate the socket being dropped and an error left behind when the tab
// was navigated away from.
sockethub.connected = false;
service.error = 'Unable to load calendar events';
await service.handleRestore();
assert.true(sockethub.connected);
assert.strictEqual(service.error, null);
service.stopPolling();
});
test('handleRestore retries an interrupted initial load', async function (assert) {
const { service, storage } = await setup(this);
await storage.set('integrations', 'caldav-key', {
type: 'calendar-caldav',
status: 'active',
url: 'https://cal.example/dav/',
username: 'alice',
password: 'secret',
calendars: [CALENDAR],
selectedCalendarIds: ['c1'],
createdAt: Date.now(),
});
service.loadFailed = true;
service.error = 'Unable to load calendars';
service.instances = [];
await service.handleRestore();
assert.true(service.enabled);
assert.strictEqual(service.error, null);
service.stopPolling();
});
test('deselecting a calendar prunes its cached events', async function (assert) {
const { service, cache } = await setup(this, {
handler: (message) =>
+30
View File
@@ -4,6 +4,8 @@ import {
CORS_PROXY_HEADER,
HttpError,
NetworkError,
RequestAbortedError,
isCancellation,
proxiedUrl,
} from 'dashtab/services/http';
@@ -120,6 +122,34 @@ module('Unit | Service | http', function (hooks) {
);
});
test('it throws RequestAbortedError when the request is cancelled', async function (assert) {
globalThis.fetch = async () => {
const err = new Error('The operation was aborted');
err.name = 'AbortError';
throw err;
};
const http = this.owner.lookup('service:http');
await assert.rejects(
http.requestJson('https://example.com/data.json'),
(err) => {
assert.true(err instanceof RequestAbortedError);
assert.false(err instanceof NetworkError);
assert.true(isCancellation(err));
return true;
}
);
});
test('isCancellation matches AbortError and RequestAbortedError only', function (assert) {
assert.true(isCancellation({ name: 'AbortError' }));
assert.true(isCancellation(new RequestAbortedError()));
assert.false(isCancellation(new NetworkError()));
assert.false(isCancellation(new HttpError(500)));
assert.false(isCancellation(null));
});
test('proxiedUrl prefixes absolute URLs with the proxy base', function (assert) {
const base = 'http://localhost:8081/';
+90
View File
@@ -611,6 +611,96 @@ module('Unit | Service | notifications', function (hooks) {
service.stopPolling();
});
test('fetchSite ignores a request cancelled by navigation', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => {
const err = new Error('The operation was aborted');
err.name = 'AbortError';
throw err;
};
const [site] = service.sites.all;
await service.fetchSite(site);
const state = service.stateFor(site);
assert.strictEqual(state.status, 'loading');
assert.strictEqual(state.error, undefined);
service.stopPolling();
});
test('fetchSite ignores failures while the page is leaving', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
service.pageLifecycle.leaving = true;
globalThis.fetch = async () => {
throw new TypeError('Failed to fetch');
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(service.stateFor(site).status, 'loading');
service.pageLifecycle.leaving = false;
service.stopPolling();
});
test('handleRestore clears an error state and refetches', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
type: 'discourse',
status: 'active',
url: 'https://forum.example.com',
apiKey: 'key',
});
const service = this.owner.lookup('service:notifications');
service.fetchAll = async () => {};
await service.ready;
globalThis.fetch = async () => {
throw new TypeError('Failed to fetch');
};
const [site] = service.sites.all;
await service.fetchSite(site);
assert.strictEqual(service.stateFor(site).status, 'error');
let calls = 0;
service.fetchAll = async () => {
calls++;
};
await service.handleRestore();
assert.strictEqual(service.stateFor(site).status, 'loading');
assert.strictEqual(calls, 1);
service.stopPolling();
});
test('fetchSite flags an unauthorized response', async function (assert) {
const storage = this.owner.lookup('service:storage');
await storage.set('integrations', 'discourse-abc', {
@@ -0,0 +1,75 @@
import { module, test } from 'qunit';
import { setupTest } from 'dashtab/tests/helpers';
module('Unit | Service | page-lifecycle', function (hooks) {
setupTest(hooks);
test('it exists', function (assert) {
assert.ok(this.owner.lookup('service:page-lifecycle'));
});
test('it marks the page as leaving on a real unload', function (assert) {
const service = this.owner.lookup('service:page-lifecycle');
window.dispatchEvent(
new PageTransitionEvent('pagehide', { persisted: false })
);
assert.true(service.leaving);
});
test('a bfcache freeze is not treated as leaving', function (assert) {
const service = this.owner.lookup('service:page-lifecycle');
window.dispatchEvent(
new PageTransitionEvent('pagehide', { persisted: true })
);
assert.false(service.leaving);
});
test('it notifies restore handlers on a persisted pageshow', function (assert) {
const service = this.owner.lookup('service:page-lifecycle');
let calls = 0;
service.onRestore(() => calls++);
window.dispatchEvent(
new PageTransitionEvent('pageshow', { persisted: true })
);
assert.strictEqual(calls, 1);
// A fresh load is not a restore.
window.dispatchEvent(
new PageTransitionEvent('pageshow', { persisted: false })
);
assert.strictEqual(calls, 1);
});
test('onRestore returns an unsubscribe function', function (assert) {
const service = this.owner.lookup('service:page-lifecycle');
let calls = 0;
const unsubscribe = service.onRestore(() => calls++);
unsubscribe();
window.dispatchEvent(
new PageTransitionEvent('pageshow', { persisted: true })
);
assert.strictEqual(calls, 0);
});
test('it clears the leaving flag after a pageshow', function (assert) {
const service = this.owner.lookup('service:page-lifecycle');
window.dispatchEvent(
new PageTransitionEvent('pagehide', { persisted: false })
);
assert.true(service.leaving);
window.dispatchEvent(
new PageTransitionEvent('pageshow', { persisted: false })
);
assert.false(service.leaving);
});
});