Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions defaultmodules/calendar/calendar.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,16 @@
padding-left: 20px;
text-align: right;
}

/* events of a calendar whose last fetch failed */
.calendar .stale > td {
opacity: 0.6;
}

.calendar .stale-icon {
margin-right: 4px;
}

.calendar .stale-note td {
text-align: right;
}
93 changes: 86 additions & 7 deletions defaultmodules/calendar/calendar.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,9 @@ Module.register("calendar", {
// indicate no data available yet
this.loaded = false;

// current fetch errors, keyed by calendar url
this.errors = {};

// data holder of calendar url. Avoid fade out/in on updateDom (one for each calendar update)
this.calendarDisplayer = {};

Expand Down Expand Up @@ -189,21 +192,24 @@ Module.register("calendar", {
// save the event list
this.calendarData[payload.url].events = payload.events;

this.error = null;
// a successful fetch clears the error of this calendar; the UI must then be redrawn
// even if the events did not change, otherwise the error stays visible
const recovered = payload.url in this.errors;
delete this.errors[payload.url];
this.loaded = true;

if (this.config.broadcastEvents) {
this.broadcastEvents();
}
// if the checksum is the same
if (this.calendarData[payload.url].checksum === payload.checksum) {
if (!recovered && this.calendarData[payload.url].checksum === payload.checksum) {
// then don't update the UI
return;
}
// haven't seen or the checksum is different
this.calendarData[payload.url].checksum = payload.checksum;

if (!this.config.updateOnFetch) {
if (!this.config.updateOnFetch && !recovered) {
if (this.calendarDisplayer[payload.url] === undefined) {
// calendar will never displayed, so display it
this.updateDom(this.config.animationSpeed);
Expand All @@ -215,22 +221,80 @@ Module.register("calendar", {
return;
}
} else if (notification === "CALENDAR_ERROR") {
const error_message = this.translate(payload.error_type);
this.error = this.translate("MODULE_CONFIG_ERROR", { MODULE_NAME: this.name, ERROR: error_message });
// errors without url (e.g. malformed url) cannot be attributed to a calendar
this.errors[payload.url ?? ""] = this.translate(payload.error_type);
this.loaded = true;
}

this.updateDom(this.config.animationSpeed);
},

/**
* Whether a fetch error should replace the whole calendar.
* Errors of single calendars are shown next to their events instead,
* unless there are no events to show or the error belongs to no calendar.
* @param {object[]} events the events that would be displayed
* @returns {boolean} true if the error should replace the calendar
*/
shouldShowError (events) {
if ("" in this.errors) return true;
return Object.keys(this.errors).length > 0 && events.length === 0;
},

/**
* Name used for a calendar in the stale note: its configured name, or else its hostname.
* @param {string} url The calendar url
* @returns {string} the label
*/
staleLabelForUrl (url) {
const name = this.calendarNameForUrl(url);
if (name) return name;
try {
return new URL(url).hostname;
} catch {
return url;
}
},

/**
* Text of the note shown for a calendar whose last fetch failed.
* @param {string} url The calendar url
* @returns {string} e.g. "Work: No internet connection."
*/
staleNoteText (url) {
return `${this.staleLabelForUrl(url)}: ${this.errors[url]}`;
},

/**
* Notes for all calendars whose last fetch failed, without duplicates
* (e.g. several unnamed calendars on the same host failing the same way).
* @returns {string[]} note texts
*/
staleNotes () {
return [...new Set(Object.keys(this.errors).map((url) => this.staleNoteText(url)))];
},

/**
* Marks an event row as coming from a calendar whose last fetch failed.
* @param {HTMLElement} eventWrapper the event row
* @param {HTMLElement} symbolWrapper the symbol cell
* @param {HTMLElement} titleWrapper the title cell
*/
markStale (eventWrapper, symbolWrapper, titleWrapper) {
eventWrapper.className += " stale";
const icon = document.createElement("span");
icon.className = "stale-icon fa-solid fa-triangle-exclamation";
(this.config.displaySymbol ? symbolWrapper : titleWrapper).prepend(icon);
},

// Override dom generator.
getDom () {
const events = this.createEventList(true);
const wrapper = document.createElement("table");
wrapper.className = this.config.tableClass;

if (this.error) {
wrapper.innerHTML = this.error;
if (this.shouldShowError(events)) {
wrapper.innerHTML = this.translate("MODULE_CONFIG_ERROR", { MODULE_NAME: this.name, ERROR: Object.values(this.errors)[0] });
wrapper.className = `${this.config.tableClass} dimmed`;
return wrapper;
}
Expand Down Expand Up @@ -383,6 +447,10 @@ Module.register("calendar", {
titleWrapper.className = `title ${titleClass}`;
}

if (event.url in this.errors) {
this.markStale(eventWrapper, symbolWrapper, titleWrapper);
}

if (this.config.timeFormat === "dateheaders") {
this.renderDateHeadersEventTime(eventWrapper, titleWrapper, event, eventStartDateMoment, eventEndDateMoment);
} else {
Expand Down Expand Up @@ -453,6 +521,17 @@ Module.register("calendar", {
}
});

// one note per calendar whose last fetch failed
for (const text of this.staleNotes()) {
const noteRow = document.createElement("tr");
noteRow.className = "stale-note dimmed xsmall";
const noteCell = document.createElement("td");
noteCell.colSpan = "3";
noteCell.textContent = text;
noteRow.appendChild(noteCell);
wrapper.appendChild(noteRow);
}

return wrapper;
},

Expand Down
12 changes: 12 additions & 0 deletions defaultmodules/calendar/calendarfetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,18 @@ class CalendarFetcher {
return timeSinceLastFetch >= this.httpFetcher.reloadInterval;
}

/**
* Whether a fetch error is likely to resolve on its own while retries remain.
* Network and server errors are retried with backoff; anything else (auth,
* rate limiting, client or parse errors) needs attention right away.
* @param {object} errorInfo error info emitted by the fetcher
* @returns {boolean} true if the error should not be surfaced yet
*/
isTransientError (errorInfo) {
const retryable = errorInfo.errorType === "NETWORK_ERROR" || errorInfo.errorType === "SERVER_ERROR";
return retryable && errorInfo.retryCount < this.httpFetcher.maxRetries;
}

/**
* Broadcasts the current events to listeners
*/
Expand Down
7 changes: 5 additions & 2 deletions defaultmodules/calendar/node_helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default NodeHelper.create({
const key = payload.id + payload.url;
if (typeof this.fetchers[key] === "undefined") {
Log.error("No fetcher exists with key: ", key);
this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_UNSPECIFIED" });
this.sendSocketNotification("CALENDAR_ERROR", { id: payload.id, url: payload.url, error_type: "MODULE_ERROR_UNSPECIFIED" });
return;
}
this.fetchers[key].fetchCalendar();
Expand All @@ -43,7 +43,7 @@ export default NodeHelper.create({
new URL(url);
} catch (error) {
Log.error("Malformed calendar url: ", url, error);
this.sendSocketNotification("CALENDAR_ERROR", { error_type: "MODULE_ERROR_MALFORMED_URL" });
this.sendSocketNotification("CALENDAR_ERROR", { id: identifier, error_type: "MODULE_ERROR_MALFORMED_URL" });
return;
}

Expand All @@ -63,8 +63,11 @@ export default NodeHelper.create({

fetcher.onError((fetcher, errorInfo) => {
Log.error("Calendar Error. Could not fetch calendar: ", fetcher.url, errorInfo.message || errorInfo);
// keep showing the last known events while the fetcher is still retrying
if (fetcher.isTransientError(errorInfo)) return;
this.sendSocketNotification("CALENDAR_ERROR", {
id: identifier,
url: fetcher.url,
error_type: errorInfo.translationKey
});
});
Expand Down
149 changes: 149 additions & 0 deletions tests/unit/modules/default/calendar/calendar_errors_spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");

const URL_A = "https://a.example/cal.ics";
const URL_B = "https://b.example/cal.ics";

/**
* Loads the calendar front end module with stubbed globals.
* @returns {object} module instance with updateDom spy
*/
const loadModule = function () {
let definition;
const code = fs.readFileSync(path.join(__dirname, "../../../../../defaultmodules/calendar/calendar.js"), "utf8");
vm.runInNewContext(code, {
URL,
Module: { register: (name, def) => { definition = def; } },
document: { createElement: () => ({ innerHTML: "", className: "", children: [], appendChild (c) { this.children.push(c); } }) },
Log: { debug () {}, warn () {}, error () {}, log () {} }
});
const instance = Object.create(definition);
instance.config = { ...definition.defaults };
instance.identifier = "calendar_1";
instance.name = "calendar";
instance.calendarData = {};
instance.calendarDisplayer = {};
instance.errors = {};
instance.loaded = false;
instance.translate = (key, vars) => (vars ? `${key}(${vars.ERROR})` : key);
instance.updateDom = vi.fn();
instance.broadcastEvents = vi.fn();
instance.createEventList = vi.fn(() => instance.events || []);
return instance;
};

const ok = (url, checksum = "x") => ({ id: "calendar_1", url, events: [], checksum });
const fail = (url) => ({ id: "calendar_1", url, error_type: "MODULE_ERROR_NO_CONNECTION" });

describe("Calendar error handling", () => {
it("redraws after recovery even if the events checksum is unchanged", () => {
const m = loadModule();
m.socketNotificationReceived("CALENDAR_EVENTS", ok(URL_A));
m.updateDom.mockClear();

m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
expect(m.getDom().innerHTML).toContain("MODULE_CONFIG_ERROR");
m.updateDom.mockClear();

m.socketNotificationReceived("CALENDAR_EVENTS", ok(URL_A));
expect(m.updateDom).toHaveBeenCalled();
expect(m.getDom().innerHTML).not.toContain("MODULE_CONFIG_ERROR");
});

it("keeps showing the error until every failing calendar has recovered", () => {
const m = loadModule();
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_B));
m.socketNotificationReceived("CALENDAR_EVENTS", ok(URL_A));
expect(m.getDom().innerHTML).toContain("MODULE_CONFIG_ERROR");
m.socketNotificationReceived("CALENDAR_EVENTS", ok(URL_B));
expect(m.getDom().innerHTML).not.toContain("MODULE_CONFIG_ERROR");
});

it("shows the full error when there are no events to display", () => {
const m = loadModule();
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
expect(m.shouldShowError([])).toBe(true);
});

it("keeps other calendars' events visible when one calendar fails", () => {
const m = loadModule();
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
expect(m.shouldShowError([{ url: URL_B }])).toBe(false);
});

it("shows the full error for errors that belong to no calendar", () => {
const m = loadModule();
// node_helper sends no url for a malformed calendar url
m.socketNotificationReceived("CALENDAR_ERROR", { id: "calendar_1", error_type: "MODULE_ERROR_MALFORMED_URL" });
expect(m.shouldShowError([{ url: URL_B }])).toBe(true);
});

describe("staleLabelForUrl", () => {
it("uses the calendar name when configured", () => {
const m = loadModule();
m.config.calendars = [{ url: URL_A, name: "Work" }];
expect(m.staleLabelForUrl(URL_A)).toBe("Work");
});

it("falls back to the hostname", () => {
const m = loadModule();
m.config.calendars = [{ url: URL_A }];
expect(m.staleLabelForUrl(URL_A)).toBe("a.example");
});

it("falls back to the raw url when it cannot be parsed", () => {
const m = loadModule();
m.config.calendars = [];
expect(m.staleLabelForUrl("not a url")).toBe("not a url");
});
});

it("wraps the message in the module error when replacing the calendar", () => {
const m = loadModule();
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
expect(m.getDom().innerHTML).toBe("MODULE_CONFIG_ERROR(MODULE_ERROR_NO_CONNECTION)");
});

it("names the calendar and the short error in the stale note", () => {
const m = loadModule();
m.config.calendars = [{ url: URL_A }];
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
expect(m.staleNoteText(URL_A)).toBe("a.example: MODULE_ERROR_NO_CONNECTION");
});

it("shows one note for calendars that would produce the same note", () => {
const m = loadModule();
m.config.calendars = [{ url: URL_A }, { url: `${URL_A}?other` }];
m.socketNotificationReceived("CALENDAR_ERROR", fail(URL_A));
m.socketNotificationReceived("CALENDAR_ERROR", fail(`${URL_A}?other`));
expect(m.staleNotes()).toEqual(["a.example: MODULE_ERROR_NO_CONNECTION"]);
});

describe("markStale", () => {
const cell = () => ({ className: "", children: [], prepend (el) { this.children.unshift(el); } });

it("adds the stale class and puts the icon in the symbol cell", () => {
const m = loadModule();
const row = cell(),
symbol = cell(),
title = cell();
m.markStale(row, symbol, title);
expect(row.className).toContain("stale");
expect(symbol.children[0].className).toBe("stale-icon fa-solid fa-triangle-exclamation");
expect(title.children).toHaveLength(0);
});

it("puts the icon in the title cell when symbols are not displayed", () => {
const m = loadModule();
m.config.displaySymbol = false;
const row = cell(),
symbol = cell(),
title = cell();
m.markStale(row, symbol, title);
expect(title.children[0].className).toBe("stale-icon fa-solid fa-triangle-exclamation");
expect(symbol.children).toHaveLength(0);
});
});
});
18 changes: 18 additions & 0 deletions tests/unit/modules/default/calendar/calendar_fetcher_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,22 @@ describe("CalendarFetcher", () => {
});
});
});
describe("isTransientError", () => {
it("treats network errors with retries left as transient", () => {
expect(makeFetcher().isTransientError({ errorType: "NETWORK_ERROR", retryCount: 1 })).toBe(true);
});

it("treats network errors as persistent once retries are used up", () => {
expect(makeFetcher().isTransientError({ errorType: "NETWORK_ERROR", retryCount: 3 })).toBe(false);
});

it("treats server errors with retries left as transient", () => {
expect(makeFetcher().isTransientError({ errorType: "SERVER_ERROR", retryCount: 2 })).toBe(true);
});

it("never treats auth or parse errors as transient", () => {
expect(makeFetcher().isTransientError({ errorType: "AUTH_FAILURE", retryCount: 0 })).toBe(false);
expect(makeFetcher().isTransientError({ errorType: "PARSE_ERROR" })).toBe(false);
});
});
});
Loading