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
6 changes: 4 additions & 2 deletions docs/architecture/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,10 @@ the system, and the technology choices.
registered here; helper logic lives in `services/` and `utils/`.
- **better-sqlite3** for synchronous, embedded SQL access.
- **Background jobs**:
- A nightly `node-cron` job at midnight (local `TZ`) prunes finished/orphaned
chores and generates recurring "sticky" chore instances.
- A nightly `node-cron` job at midnight (local `TZ`) prunes finished
one-time chores (and the definition of one it just finished, unless a
follow-up or a routine uses it) and generates recurring "sticky" chore
instances. A chore that simply has no schedule is kept.
- The **Calendar Sync Service** ([`services/calendarSync.js`](../../server/services/calendarSync.js))
periodically fetches ICS/CalDAV/Google calendars into a local cache table.
- **File handling**: uploads (user avatars, photos) are written to
Expand Down
26 changes: 17 additions & 9 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2674,17 +2674,25 @@ async function dailyBackgroundProcessing() {
prunedSchedules: schedulesToPrune,
}

// We should also delete chores that have no schedules to avoid clutter
const choresToPrune = db.prepare(`
// A finished one-time chore takes its definition with it, so the chore
// list doesn't fill with chores that were done once (#41). Only those:
// a chore whose last schedule was pruned just now, above. A chore with no
// schedules is otherwise ordinary (made and not scheduled yet, or its
// schedule deleted), and some are used without one: a follow-up
// target, handed out by its rule, and a routine's chore, whose schedules
// come and go with calendar events. Deleting a routine's chore deletes
// the routine (ON DELETE CASCADE), and a follow-up target its rule, so
// neither is pruned even after its one-time card was.
const prunedChoreIds = [...new Set(schedulesToPrune.map((schedule) => schedule.chore_id))];
const choresToPrune = prunedChoreIds.length === 0 ? [] : db.prepare(`
SELECT c.id, c.title
FROM chores c
WHERE NOT EXISTS (
SELECT 1
FROM chore_schedules cs
WHERE cs.chore_id = c.id
);
`).all();
console.log(`Found ${choresToPrune.length} orphaned chores to prune`);
WHERE c.id IN (${prunedChoreIds.map(() => '?').join(',')})
AND NOT EXISTS (SELECT 1 FROM chore_schedules cs WHERE cs.chore_id = c.id)
AND NOT EXISTS (SELECT 1 FROM chore_followups f WHERE f.followup_chore_id = c.id)
AND NOT EXISTS (SELECT 1 FROM routines r WHERE r.chore_id = c.id);
`).all(...prunedChoreIds);
console.log(`Found ${choresToPrune.length} finished one-time chores to prune`);

let prunedChoreCount = 0;
for (const chore of choresToPrune) {
Expand Down
126 changes: 126 additions & 0 deletions server/tests/nightlyChorePrune.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// The nightly job deletes a chore's definition only when it just finished
// the chore's last, one-time schedule (#41), never a chore that simply has
// no schedule. Before this, every chore without a schedule went overnight:
// one made and not yet scheduled, a follow-up target (and with it the rule
// that hands it out), and a calendar routine's chore, which deleted the
// routine too. A real server, the job run on demand.
const test = require('node:test');
const assert = require('node:assert/strict');
const { spawn } = require('node:child_process');
const fs = require('node:fs');
const path = require('node:path');
const { freePort } = require('./freePort');

const serverDir = path.resolve(__dirname, '..');
const tmpDir = path.resolve(__dirname, '.tmp');
const testDbPath = path.join(tmpDir, `nightly-chore-prune-${process.pid}-${Date.now()}.db`);
const keepTestArtifacts = process.env.HOMEGLOW_TEST_KEEP_ARTIFACTS === '1';
let baseUrl;
let serverProcess;
let serverLogs = '';
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function api(pathname, method = 'GET', body) {
const response = await fetch(`${baseUrl}${pathname}`, {
method,
headers: body ? { 'Content-Type': 'application/json' } : {},
body: body ? JSON.stringify(body) : undefined,
});
const text = await response.text();
let parsed;
try { parsed = text ? JSON.parse(text) : null; } catch { parsed = text; }
return { status: response.status, body: parsed };
}
const ok = (res, what) => { assert.ok(res.status < 300, `${what}: ${res.status} ${JSON.stringify(res.body)}`); return res.body; };
const scheduleId = (body) => body.id || body.ids?.[0];
const choreTitles = async () => (await api('/api/chores')).body.map((chore) => chore.title);
const runNightlyJob = async () => ok(await api('/api/system/backgroundTasks'), 'nightly job');
// The server's own date, as the nightly job sees it (TZ is UTC here).
const today = () => new Date().toISOString().slice(0, 10);

test.before(async () => {
fs.mkdirSync(tmpDir, { recursive: true });
const port = await freePort();
baseUrl = `http://127.0.0.1:${port}`;
serverProcess = spawn(process.execPath, ['index.js'], {
cwd: serverDir,
env: {
...process.env, PORT: String(port), DB_PATH: testDbPath, TZ: 'UTC', DEMO_MODE: 'false',
ENCRYPTION_KEY: Buffer.alloc(32, 9).toString('base64'),
HOMEGLOW_DISABLE_BACKGROUND_JOBS: '1', HOMEGLOW_DISABLE_CALENDAR_SYNC: '1', HOMEGLOW_DISABLE_UPDATE_CHECK: '1',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
serverProcess.stdout.on('data', (chunk) => { serverLogs += chunk; });
serverProcess.stderr.on('data', (chunk) => { serverLogs += chunk; });
const start = Date.now();
while (Date.now() - start < 30000) {
try { if ((await fetch(`${baseUrl}/api/test`)).ok) return; } catch { /* starting */ }
await delay(250);
}
throw new Error('server did not start');
});

test.after(async () => {
if (serverProcess && serverProcess.exitCode === null) {
await new Promise((resolve) => { serverProcess.once('close', resolve); serverProcess.kill(); setTimeout(resolve, 5000); });
}
if (process.exitCode && serverLogs) console.error(serverLogs.slice(-4000));
if (!keepTestArtifacts) {
for (const suffix of ['', '-wal', '-shm']) fs.rmSync(`${testDbPath}${suffix}`, { force: true });
}
});

test('chores without a schedule, follow-up targets and routines survive the night; a finished one-time chore does not', async () => {
const ava = ok(await api('/api/users', 'POST', { username: 'Ava', email: 'ava@example.com' }), 'user').id;

// Made in Admin, not scheduled yet.
ok(await api('/api/chores', 'POST', { title: 'Not scheduled yet', clam_value: 0 }), 'chore');
// A chore whose schedule was deleted: its definition stays.
const rake = ok(await api('/api/chores', 'POST', { title: 'Rake leaves', clam_value: 0 }), 'chore').id;
const rakeSchedule = scheduleId(ok(await api('/api/chore-schedules', 'POST', { chore_id: rake, user_id: ava, crontab: '0 0 * * 6', duration: 'day-of', visible: 1 }), 'schedule'));
ok(await api(`/api/chore-schedules/${rakeSchedule}`, 'DELETE'), 'delete schedule');

// Dishes hands Unload dishwasher to Ava when it's done.
const dishes = ok(await api('/api/chores', 'POST', { title: 'Dishes', clam_value: 0 }), 'chore').id;
const unload = ok(await api('/api/chores', 'POST', { title: 'Unload dishwasher', clam_value: 0 }), 'chore').id;
const dishesSchedule = scheduleId(ok(await api('/api/chore-schedules', 'POST', { chore_id: dishes, user_id: ava, crontab: '0 0 * * *', duration: 'day-of', visible: 1 }), 'schedule'));
ok(await api(`/api/chores/${dishes}/followups`, 'PUT', { followups: [{ followup_chore_id: unload, user_ids: [ava], delay_minutes: 0 }] }), 'follow-up');

// A calendar routine with no matching event coming up: no schedules.
ok(await api('/api/routines', 'POST', { name: 'Get ready for soccer', user_id: ava, trigger: 'calendar', match_text: 'soccer', steps: [] }), 'routine');

// A one-time chore, done: its definition is what the prune is for.
const car = ok(await api('/api/chores', 'POST', { title: 'Wash the car', clam_value: 2 }), 'chore').id;
const carSchedule = scheduleId(ok(await api('/api/chore-schedules', 'POST', { chore_id: car, user_id: ava, crontab: null, duration: 'day-of', visible: 1 }), 'schedule'));
ok(await api('/api/chores/complete', 'POST', { chore_schedule_id: carSchedule, user_id: ava, date: today() }), 'complete the car');

// Dishes done: Unload dishwasher arrives as a one-time card, and is done too.
ok(await api('/api/chores/complete', 'POST', { chore_schedule_id: dishesSchedule, user_id: ava, date: today() }), 'complete dishes');
const unloadCard = (await api('/api/chore-schedules')).body.find((s) => s.chore_id === unload && s.user_id === ava);
assert.ok(unloadCard, 'the follow-up handed out its card');
ok(await api('/api/chores/complete', 'POST', { chore_schedule_id: unloadCard.id, user_id: ava, date: today() }), 'complete the follow-up');

const night = await runNightlyJob();
assert.deepEqual(night.prunedChores.map((chore) => chore.title), ['Wash the car']);

const titles = await choreTitles();
for (const kept of ['Not scheduled yet', 'Rake leaves', 'Dishes', 'Unload dishwasher', 'Get ready for soccer']) {
assert.ok(titles.includes(kept), `"${kept}" survives the night (${titles.join(', ')})`);
}
assert.ok(!titles.includes('Wash the car'), 'the finished one-time chore is gone');

// The follow-up's card went, but its rule and target stay.
assert.ok(!(await api('/api/chore-schedules')).body.some((s) => s.id === unloadCard.id), "the follow-up's done card was pruned");
const dishesAfter = (await api('/api/chores')).body.find((chore) => chore.id === dishes);
assert.deepEqual(dishesAfter.followups.map((f) => f.title), ['Unload dishwasher']);

// And the routine is still there.
const routines = (await api('/api/routines')).body.routines.map((routine) => routine.name);
assert.deepEqual(routines, ['Get ready for soccer']);

// A second night changes nothing.
const again = await runNightlyJob();
assert.deepEqual(again.prunedChores, []);
assert.deepEqual((await choreTitles()).sort(), titles.slice().sort());
});