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
5 changes: 5 additions & 0 deletions .changeset/save-failures.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'lyra': patch
---

When Lyra can't write a session's changes to disk (the disk is full, the folder isn't writable, or another app holds the file), it now says so in Activity with the reason and a Retry button, keeps the changes in memory and keeps trying until they're saved, instead of logging it and losing them when you switch away. And if your settings file can't be read, or holds a "Keep audio" value Lyra can't use, Lyra no longer falls back to 30 days and deletes older recordings at startup: it keeps every recording until you choose again, and tells you.
30 changes: 28 additions & 2 deletions apps/lyra/src/main/audioRetention.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { readdir, stat, unlink } from 'node:fs/promises'
import { join } from 'node:path'
import { basename, join } from 'node:path'
import type { AudioTrack, RetentionPreview } from '../shared/types'
import { audioExpired, retentionCutoff } from '../shared/retention'
import { clear, end } from './activity'
import { log } from './log'
import { notesDir } from './pages'
import { deleteSessionAudio, recordingPageId, trackPath } from './recorder'
import { peekManifest, sessionIds } from './sessionStore'
import { getSettings, onSettingsChanged } from './settings'
import { audioRetentionUnread, getSettings, onSettingsChanged, type RetentionUnread } from './settings'

/**
* Deletes recorded audio older than the "Keep recordings" setting. Transcripts, raw passes and
Expand Down Expand Up @@ -66,6 +67,11 @@ export async function previewAudioSweep(days: number | null, now = Date.now()):

/** Deletes expired audio; returns how many sessions (or legacy files) lost theirs. */
export async function sweepAudio(now = Date.now()): Promise<number> {
// A choice that couldn't be read never deletes anything: it may not be the person's.
if (audioRetentionUnread()) {
log('retention', 'skipped the sweep: the keep audio setting was unreadable')
return 0
}
const days = getSettings().audioRetentionDays
// Forever keeps everything; 0 is handled as soon as a session is transcribed.
const cutoff = retentionCutoff(days, now)
Expand Down Expand Up @@ -93,16 +99,36 @@ export async function sweepAudio(now = Date.now()): Promise<number> {

let timer: ReturnType<typeof setInterval> | null = null

const UNREAD_ACTIVITY_ID = 'settings:retention'

/** Says, until "Keep audio" is chosen again, that recordings are being kept and why. */
function reportUnread(unread: RetentionUnread): void {
const aside = unread.aside ? ` A copy of the old file is in ${basename(unread.aside)}.` : ''
end(
{
id: UNREAD_ACTIVITY_ID,
kind: 'settings',
origin: 'settings',
title: unread.why === 'file' ? 'Couldn’t read your settings' : 'Couldn’t read how long to keep audio',
detail: `No recordings are deleted until you choose again in Settings → Keep audio.${aside}`
},
'failed'
)
}

/** Sweeps now, once a day after, and whenever the setting or the notes folder changes. */
export function startAudioRetention(): void {
const run = (): void => {
sweepAudio().catch((error: unknown) => {
log('retention', 'sweep failed', String(error))
})
}
const unread = audioRetentionUnread()
if (unread) reportUnread(unread)
run()
timer ??= setInterval(run, SWEEP_EVERY_MS)
onSettingsChanged((next, prev) => {
if (unread && !audioRetentionUnread()) clear(UNREAD_ACTIVITY_ID)
if (next.audioRetentionDays !== prev.audioRetentionDays || next.notesDir !== prev.notesDir) run()
})
}
153 changes: 153 additions & 0 deletions apps/lyra/src/main/docSave.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
flushSave,
hasUnsaved,
markUnsaved,
newSaveState,
retryDelay,
writeFailureReason,
type SaveIo
} from './docSave'

const diskFull = (): Error => Object.assign(new Error('ENOSPC: no space left on device'), { code: 'ENOSPC' })

/** A document whose next `failNext` writes fail; `disk` is what landed last. */
function harness() {
let doc = 'v0'
const calls: { failed: number[]; recovered: number; writes: string[] } = { failed: [], recovered: 0, writes: [] }
const io: SaveIo & { failNext: number; disk: string | null } = {
failNext: 0,
disk: null,
snapshot: () => doc,
write: (text: string): Promise<void> => {
calls.writes.push(text)
if (io.failNext > 0) {
io.failNext--
return Promise.reject(diskFull())
}
io.disk = text
return Promise.resolve()
},
failed: (_error: unknown, failures: number) => {
calls.failed.push(failures)
},
recovered: () => {
calls.recovered++
}
}
const state = newSaveState()
const edit = (next: string): void => {
doc = next
markUnsaved(state, Date.now())
}
return { io, state, calls, edit }
}

beforeEach(() => {
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
})

describe('flushSave', () => {
it('saves a change and leaves nothing unsaved', async () => {
const { io, state, edit } = harness()
edit('v1')
await flushSave(state, io)
expect(io.disk).toBe('v1')
expect(hasUnsaved(state)).toBe(false)
})

it('keeps a change unsaved when its write fails, and says so', async () => {
const { io, state, calls, edit } = harness()
io.failNext = Infinity
edit('v1')
await flushSave(state, io)
expect(io.disk).toBeNull()
expect(hasUnsaved(state)).toBe(true)
expect(calls.failed).toEqual([1])
})

it('writes the change on the next flush once the disk takes it', async () => {
const { io, state, calls, edit } = harness()
io.failNext = Infinity
edit('v1')
await flushSave(state, io)
io.failNext = 0
// What a quit or an unload does: before the fix this was a no-op and v1 was lost.
await flushSave(state, io)
expect(io.disk).toBe('v1')
expect(hasUnsaved(state)).toBe(false)
expect(calls.recovered).toBe(1)
})

it('tries again on its own, backing off, until a write lands', async () => {
const { io, state, calls, edit } = harness()
io.failNext = Infinity
edit('v1')
await flushSave(state, io)
await vi.advanceTimersByTimeAsync(retryDelay(1))
expect(calls.failed).toEqual([1, 2])
await vi.advanceTimersByTimeAsync(retryDelay(2))
expect(calls.failed).toEqual([1, 2, 3])
io.failNext = 0
await vi.advanceTimersByTimeAsync(retryDelay(3))
expect(io.disk).toBe('v1')
expect(hasUnsaved(state)).toBe(false)
expect(calls.recovered).toBe(1)
// Nothing left to retry.
const writes = calls.writes.length
await vi.advanceTimersByTimeAsync(10 * 60_000)
expect(calls.writes.length).toBe(writes)
})

it('a retry writes the latest document, with changes made while it was failing', async () => {
const { io, state, edit } = harness()
io.failNext = Infinity
edit('v1')
await flushSave(state, io)
edit('v2')
io.failNext = 0
await vi.advanceTimersByTimeAsync(retryDelay(1))
expect(io.disk).toBe('v2')
expect(hasUnsaved(state)).toBe(false)
})

it('a later write that holds every change covers an earlier failure', async () => {
const { io, state, calls, edit } = harness()
io.failNext = 1
edit('v1')
const first = flushSave(state, io)
edit('v2')
// The first write fails, the second (queued behind it, with v2) lands.
const second = flushSave(state, io)
await Promise.all([first, second])
expect(io.disk).toBe('v2')
expect(hasUnsaved(state)).toBe(false)
expect(calls.recovered).toBe(1)
})

it('does nothing when there is nothing to save', async () => {
const { io, state, calls } = harness()
await flushSave(state, io)
expect(calls.writes).toEqual([])
})
})

describe('retryDelay', () => {
it('backs off, then repeats the longest wait', () => {
expect([1, 2, 3, 4, 5, 50].map(retryDelay)).toEqual([1000, 5000, 15_000, 60_000, 60_000, 60_000])
})
})

describe('writeFailureReason', () => {
it('says why in plain words', () => {
expect(writeFailureReason(diskFull())).toBe('the disk is full')
expect(writeFailureReason(Object.assign(new Error('x'), { code: 'EACCES' }))).toBe(
'Lyra isn’t allowed to write to the notes folder'
)
expect(writeFailureReason(new Error('odd'))).toBe('the disk refused the write')
expect(writeFailureReason('not an error')).toBe('the disk refused the write')
})
})
111 changes: 111 additions & 0 deletions apps/lyra/src/main/docSave.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/**
* Saving one session's document (`doc.json`). Pure (no Electron), so the rules can be
* unit-tested: a change stays unsaved until a write that holds it lands, a failed write is tried
* again with backoff (a local write is free, so it keeps trying), and the store hears when saving
* starts failing and when it works again, to tell the person (docs/STATES.md).
*/

/** Waits between tries after a failed write; the last one repeats until a write lands. */
export const SAVE_RETRY_MS: readonly number[] = [1000, 5000, 15_000, 60_000]

export type SaveState = {
/** When the oldest change not yet saved was made; null when everything is saved. */
unsavedSince: number | null
/** Counts changes, so a write can tell whether it holds the latest one. */
changes: number
/** The save being written; saves run one after another, so the newest lands last. */
saving: Promise<void>
/** Writes that failed in a row; 0 once one lands. */
failures: number
retryTimer: ReturnType<typeof setTimeout> | null
}

export type SaveIo = {
/** The document as it is now, as the file's text. */
snapshot: () => string
write: (text: string) => Promise<void>
/** A write failed; `failures` counts them since the last one that landed. */
failed: (error: unknown, failures: number) => void
/** A write landed after one or more failed. */
recovered: () => void
}

export function newSaveState(): SaveState {
return { unsavedSince: null, changes: 0, saving: Promise.resolve(), failures: 0, retryTimer: null }
}

/** A change was made and needs saving. */
export function markUnsaved(state: SaveState, now: number): void {
state.unsavedSince ??= now
state.changes++
}

/** Whether the document has changes that aren't on disk, written or failed. */
export const hasUnsaved = (state: SaveState): boolean => state.unsavedSince !== null || state.failures > 0

export function retryDelay(failures: number): number {
const index = Math.min(Math.max(failures, 1), SAVE_RETRY_MS.length) - 1
return SAVE_RETRY_MS[index] ?? 1000
}

/**
* Writes the document as it is now, if it has changes not saved yet, and resolves once every
* save so far has been tried. Never rejects: a failed write leaves the document unsaved, tells
* `io.failed` and tries again later; `hasUnsaved` says whether it's on disk.
*/
export function flushSave(state: SaveState, io: SaveIo): Promise<void> {
if (state.retryTimer) clearTimeout(state.retryTimer)
state.retryTimer = null
const since = state.unsavedSince
if (since === null) return state.saving
state.unsavedSince = null
const upTo = state.changes
const text = io.snapshot()
state.saving = state.saving.then(() =>
io.write(text).then(
() => {
// This write holds every change so far: an earlier failure is covered by it.
if (state.changes === upTo) {
state.unsavedSince = null
if (state.retryTimer) clearTimeout(state.retryTimer)
state.retryTimer = null
}
if (state.failures === 0) return
state.failures = 0
io.recovered()
},
(error: unknown) => {
// Still unsaved: the next write takes this change along with any made since.
state.unsavedSince = Math.min(since, state.unsavedSince ?? since)
state.failures++
io.failed(error, state.failures)
if (state.retryTimer) clearTimeout(state.retryTimer)
state.retryTimer = setTimeout(() => void flushSave(state, io), retryDelay(state.failures))
}
)
)
return state.saving
}

/** Why a write failed, in plain words for the person, from the file system's error code. */
export function writeFailureReason(error: unknown): string {
const code = error instanceof Error && 'code' in error ? error.code : null
switch (code) {
case 'ENOSPC':
case 'EDQUOT':
return 'the disk is full'
case 'EACCES':
case 'EPERM':
return 'Lyra isn’t allowed to write to the notes folder'
case 'EBUSY':
return 'another app has the file open'
case 'EROFS':
return 'the drive is read-only'
case 'ENOENT':
case 'ENODEV':
case 'ENXIO':
return 'the notes folder can’t be found (was a drive removed?)'
default:
return 'the disk refused the write'
}
}
Loading