mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 05:37:43 +01:00
* fix(calendar): read linked calendars in a worker with a time limit, and turn them back on ical.js has inner loops with no guard; a stuck parse held the app's only thread four times on 14 Nov (each stop needed a SIGKILL). The reader now runs in workers/calendar-reader.cjs, started per read and terminated after 4 s (and capped at 128 MB), so it can never hold the request thread. The standalone build carries the worker (outputFileTracingIncludes) and ical.js (serverExternalPackages). Ends the pause from #1769. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmwF5V6xdaNTSbg9ouh * fix(calendar): start the reader worker from an opaque bootstrap so Turbopack does not bundle the project Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmwF5V6xdaNTSbg9ouh * fix(calendar): the reader worker finds ical.js in the standalone build Built SELF_HOST=1 locally and ran the worker from a copy of the standalone tree outside the repo: a bare require('ical.js') fails there (Next ships it as .next/node_modules/ical.js-<hash> and in the pnpm store, with no plain node_modules/ical.js). The worker now looks in those places, and unwraps the ES module default when loaded by directory. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmwF5V6xdaNTSbg9ouh * test(calendar): the stuck-reader fixture lives in a private temp folder (CodeQL) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmwF5V6xdaNTSbg9ouh --------- Co-authored-by: Claude <noreply@anthropic.com>
247 lines
8.1 KiB
JavaScript
247 lines
8.1 KiB
JavaScript
/**
|
|
* Reads a calendar file (iCalendar, RFC 5545) into agenda items between two
|
|
* instants, in its OWN thread.
|
|
*
|
|
* Why a worker: ical.js has inner loops with no guard, and a malformed or
|
|
* unusual file can spin inside one call. On 14 Nov 2026, after linked
|
|
* calendars went live, orangecat-app hung four times (each stop needed a
|
|
* SIGKILL) and the site answered nothing. Run here, a stuck read is
|
|
* terminated by the app after a time limit and the app's own thread never
|
|
* waits on it (src/services/planner/ics-read.ts).
|
|
*
|
|
* Plain CommonJS on purpose: it is started by path, outside the bundle, and
|
|
* the self-hosted build carries it (next.config outputFileTracingIncludes).
|
|
*
|
|
* Exports `readFile` for tests; as a worker it reads `workerData` and posts
|
|
* `{ ok: true, read }` or `{ ok: false, error, notCalendar }`.
|
|
*/
|
|
'use strict';
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { isMainThread, parentPort, workerData } = require('node:worker_threads');
|
|
|
|
/**
|
|
* ical.js, wherever this tree keeps it. In the repo it is a plain
|
|
* node_modules package. In the self-hosted standalone build Next ships it as
|
|
* an external under a hashed link (.next/node_modules/ical.js-<hash>) and in
|
|
* the pnpm store, with no plain node_modules/ical.js, so a bare require fails
|
|
* there. Looked for in that order; the first that loads wins.
|
|
*/
|
|
/** Loaded by directory, ical.js can come back as its ES module, with `default`. */
|
|
const usable = mod => (mod && typeof mod.parse === 'function' ? mod : mod && mod.default);
|
|
|
|
function loadIcal() {
|
|
try {
|
|
return usable(require('ical.js'));
|
|
} catch {
|
|
// Not a plain package here; look where the standalone build puts it.
|
|
}
|
|
const root = path.resolve(__dirname, '..');
|
|
const candidates = [];
|
|
const hashed = path.join(root, '.next', 'node_modules');
|
|
if (fs.existsSync(hashed)) {
|
|
for (const name of fs.readdirSync(hashed)) {
|
|
if (name === 'ical.js' || name.startsWith('ical.js-')) {
|
|
candidates.push(path.join(hashed, name));
|
|
}
|
|
}
|
|
}
|
|
const store = path.join(root, 'node_modules', '.pnpm');
|
|
if (fs.existsSync(store)) {
|
|
for (const name of fs.readdirSync(store)) {
|
|
if (name.startsWith('ical.js@')) {
|
|
candidates.push(path.join(store, name, 'node_modules', 'ical.js'));
|
|
}
|
|
}
|
|
}
|
|
for (const dir of candidates) {
|
|
try {
|
|
const ical = usable(require(dir));
|
|
if (ical && typeof ical.parse === 'function') {
|
|
return ical;
|
|
}
|
|
} catch {
|
|
// Try the next one.
|
|
}
|
|
}
|
|
throw new Error('ical.js was not found beside the calendar reader.');
|
|
}
|
|
|
|
const ICAL = loadIcal();
|
|
|
|
/** Occurrences one repeating event may contribute, so a "daily forever" cannot run away. */
|
|
const OCCURRENCES_MAX = 400;
|
|
/** Items one calendar file may contribute to one span. */
|
|
const ITEMS_MAX = 500;
|
|
/** Recurrence steps one file may take in all. */
|
|
const STEPS_MAX = 150000;
|
|
|
|
function startOf(time) {
|
|
return time.isDate ? time.toString().slice(0, 10) : time.toJSDate().toISOString();
|
|
}
|
|
|
|
function itemOf(event, start, end, calendarName) {
|
|
return {
|
|
source: 'linked',
|
|
title: String(event.summary || '(no title)').slice(0, 200),
|
|
start: startOf(start),
|
|
end: end && !end.isDate ? end.toJSDate().toISOString() : null,
|
|
allDay: start.isDate,
|
|
location: event.location ? String(event.location).slice(0, 300) : null,
|
|
calendarName,
|
|
};
|
|
}
|
|
|
|
/** Does an occurrence touch the span? All-day ones are compared by their day. */
|
|
function touches(start, end, fromMs, untilMs) {
|
|
const s = start.isDate
|
|
? Date.parse(`${start.toString().slice(0, 10)}T00:00:00Z`)
|
|
: start.toJSDate().getTime();
|
|
const e = end
|
|
? end.isDate
|
|
? Date.parse(`${end.toString().slice(0, 10)}T00:00:00Z`)
|
|
: end.toJSDate().getTime()
|
|
: s;
|
|
return s < untilMs && Math.max(e, s) >= fromMs;
|
|
}
|
|
|
|
/** A repeating rule that ended (UNTIL) before the span, with no extra dates: nothing to walk. */
|
|
function endedBefore(event, fromMs) {
|
|
const comp = event.component;
|
|
if (comp.hasProperty('rdate')) {
|
|
return false;
|
|
}
|
|
const rules = comp.getAllProperties('rrule').map(p => p.getFirstValue());
|
|
return rules.length > 0 && rules.every(r => r.until && r.until.toJSDate().getTime() < fromMs);
|
|
}
|
|
|
|
/** An occurrence of a series with exceptions: does it (as moved) end on or after `fromMs`? */
|
|
function mayReach(event, next, fromMs) {
|
|
const d = event.getOccurrenceDetails(next);
|
|
return !d.endDate || d.endDate.toJSDate().getTime() >= fromMs;
|
|
}
|
|
|
|
class NotACalendar extends Error {}
|
|
|
|
/**
|
|
* Read one file for one span. Returns `{ items, complete }`; `complete` is
|
|
* false when the step budget ran out first. Throws NotACalendar.
|
|
*/
|
|
function readFile(text, fromMs, untilMs, calendarName, stepsMax = STEPS_MAX) {
|
|
let root;
|
|
try {
|
|
root = new ICAL.Component(ICAL.parse(text));
|
|
} catch {
|
|
throw new NotACalendar('This is not a calendar file.');
|
|
}
|
|
if (root.name !== 'vcalendar') {
|
|
throw new NotACalendar('This is not a calendar file.');
|
|
}
|
|
for (const tz of root.getAllSubcomponents('vtimezone')) {
|
|
try {
|
|
ICAL.TimezoneService.register(tz);
|
|
} catch {
|
|
// A broken zone block leaves those times floating; the rest still reads.
|
|
}
|
|
}
|
|
const masters = new Map();
|
|
const exceptions = [];
|
|
for (const vevent of root.getAllSubcomponents('vevent')) {
|
|
const event = new ICAL.Event(vevent);
|
|
if (event.isRecurrenceException()) {
|
|
exceptions.push(event);
|
|
} else if (event.uid) {
|
|
masters.set(event.uid, event);
|
|
} else {
|
|
masters.set(`no-uid-${masters.size}`, event);
|
|
}
|
|
}
|
|
for (const ex of exceptions) {
|
|
const master = masters.get(ex.uid);
|
|
if (master) {
|
|
master.relateException(ex);
|
|
}
|
|
}
|
|
|
|
const out = [];
|
|
let steps = 0;
|
|
let complete = true;
|
|
walk: for (const event of masters.values()) {
|
|
if (out.length >= ITEMS_MAX) {
|
|
break;
|
|
}
|
|
const status = String(event.component.getFirstPropertyValue('status') || '').toUpperCase();
|
|
if (status === 'CANCELLED' || !event.startDate) {
|
|
continue;
|
|
}
|
|
if (!event.isRecurring()) {
|
|
if (touches(event.startDate, event.endDate, fromMs, untilMs)) {
|
|
out.push(itemOf(event, event.startDate, event.endDate, calendarName));
|
|
}
|
|
continue;
|
|
}
|
|
if (endedBefore(event, fromMs)) {
|
|
continue;
|
|
}
|
|
// How long an occurrence can run, plus two days for all-day and
|
|
// zone-shifted ones, so one that started before the span is only looked
|
|
// at closely when it could still reach into it. A series with moved or
|
|
// changed occurrences (exceptions) is always looked at closely.
|
|
const reachMs =
|
|
(Math.max(event.duration ? event.duration.toSeconds() : 0, 0) + 2 * 86400) * 1000;
|
|
const plain = Object.keys(event.exceptions).length === 0;
|
|
const it = event.iterator();
|
|
for (let n = 0; n < OCCURRENCES_MAX * 20; n++) {
|
|
if (steps >= stepsMax) {
|
|
complete = false;
|
|
break walk;
|
|
}
|
|
steps++;
|
|
const next = it.next();
|
|
if (!next) {
|
|
break;
|
|
}
|
|
const nextMs = next.toJSDate().getTime();
|
|
if (nextMs >= untilMs) {
|
|
break;
|
|
}
|
|
if (plain && nextMs + reachMs < fromMs) {
|
|
continue;
|
|
}
|
|
if (!plain && nextMs < fromMs && !mayReach(event, next, fromMs)) {
|
|
continue;
|
|
}
|
|
const d = event.getOccurrenceDetails(next);
|
|
const cancelled =
|
|
String(d.item.component.getFirstPropertyValue('status') || '').toUpperCase() ===
|
|
'CANCELLED';
|
|
if (!cancelled && touches(d.startDate, d.endDate, fromMs, untilMs)) {
|
|
out.push(itemOf(d.item, d.startDate, d.endDate, calendarName));
|
|
if (out.length >= ITEMS_MAX) {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return { items: out, complete };
|
|
}
|
|
|
|
module.exports = { readFile, NotACalendar, STEPS_MAX };
|
|
|
|
if (!isMainThread && parentPort && workerData && workerData.job === 'calendar-read') {
|
|
const { text, fromMs, untilMs, calendarName, stepsMax } = workerData;
|
|
try {
|
|
parentPort.postMessage({
|
|
ok: true,
|
|
read: readFile(text, fromMs, untilMs, calendarName, stepsMax),
|
|
});
|
|
} catch (error) {
|
|
parentPort.postMessage({
|
|
ok: false,
|
|
notCalendar: error instanceof NotACalendar,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
});
|
|
}
|
|
}
|