Merge pull request 'Redline: past submissions list + start-new-session with 10-session retention (MMDB-2925)' (#29) from feat/redline-sessions-history-20261011 into main

This commit was merged in pull request #29.
This commit is contained in:
2026-10-11 10:01:23 +00:00
11 changed files with 1049 additions and 44 deletions
@@ -2,7 +2,7 @@ import Foundation
public enum SessionState: String, Codable, Sendable {
case open // accepting captures
case archived // its PDF has been built and sent; kept forever, never deleted
case archived // closed and kept as a past session (sent or not); pruned by retention
}
/// The manifest persisted as session.json alongside the PNGs.
@@ -11,7 +11,9 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
public let createdAt: Date
public private(set) var state: SessionState
public private(set) var captures: [Capture]
/// Set when the PDF is built, so a re-send reuses the same file.
/// Set when the PDF is built, so a re-send reuses the same file. nil on a
/// session that was closed without ever sending — the Past submissions list
/// shows that as "Not sent".
public private(set) var pdfFileName: String?
public init(
@@ -61,7 +63,8 @@ public struct CaptureSession: Codable, Sendable, Identifiable, Equatable {
}
/// Value-semantic: returns a new session; does not mutate `self`.
public func markArchived(pdfFileName: String) -> CaptureSession {
/// `pdfFileName` is nil when the session is closed without ever sending.
public func markArchived(pdfFileName: String?) -> CaptureSession {
CaptureSession(
id: id,
createdAt: createdAt,
+159 -27
View File
@@ -4,6 +4,13 @@ import CoreGraphics
import Darwin
public actor SpoolStore {
/// How many archived sessions (past submissions) are kept on disk. Ben's
/// retention rule (2026-10-11): "by default, retain the past 10 sessions" —
/// older session folders are removed from `archive/` once this is exceeded.
/// Any PDF a pruned session produced is not touched: it lives in the outbox
/// (or the OneDrive folder) it was sent to.
public static let defaultRetainedSessionCount = 10
private let paths: AppSupportPaths
private var openSession: CaptureSession
@@ -28,9 +35,28 @@ public actor SpoolStore {
}
/// The session currently accepting captures. Cheap accessor — all reconciliation already
/// happened once, inside init.
/// happened once, inside init. A truth guard: if the stored session is no longer really
/// open on disk (its directory was archived away and the replacement session could not
/// be created — e.g. disk full), a fresh session is minted, or the call fails loudly.
/// It never returns an already-archived session as the open one.
public func currentSession() throws -> CaptureSession {
openSession
try ensureOpenSession()
}
/// Mint-or-verify the open session: returns the session that is REALLY open on disk,
/// creating a fresh one when the stored one is stale (archived away mid-run). Throws
/// loudly when no new session can be created either — never substitutes a lie.
private func ensureOpenSession() throws -> CaptureSession {
let dir = paths.sessionDirectory(openSession.id)
if openSession.state == .open && FileManager.default.fileExists(atPath: dir.path) {
return openSession
}
let staleID = openSession.id.uuidString
Log.spool.error(
"The stored open session \(staleID, privacy: .public) is not really open on disk; starting a fresh one.")
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
return fresh
}
/// Writes `pngData` to disk and fsyncs it BEFORE the manifest is touched, then updates and
@@ -40,32 +66,38 @@ public actor SpoolStore {
pngData: Data, pixelWidth: Int, pixelHeight: Int,
scale: CGFloat, capturedAt: Date
) throws -> Capture {
let open = try ensureOpenSession()
let captureID = UUID()
let sequence = openSession.nextSequence
let sequence = open.nextSequence
let fileName = "\(String(format: "%03d", sequence))-\(Self.hexSuffix(captureID)).png"
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let fileURL = sessionDir.appendingPathComponent(fileName)
try AtomicFile.write(pngData, to: fileURL)
let capture = Capture(
id: captureID, sequence: sequence, fileName: fileName,
pixelWidth: pixelWidth, pixelHeight: pixelHeight,
scale: scale, capturedAt: capturedAt)
let updated = openSession.appending(capture)
let updated = open.appending(capture)
try AtomicFile.writeJSON(updated, to: sessionDir.appendingPathComponent("session.json"))
openSession = updated
return capture
}
/// D-11: moves the capture's PNG into `<sessionDir>/removed/` (created lazily) and drops
/// its manifest entry. NEVER unlinks/deletes a user PNG. Throws (no filesystem change) if
/// `captureID` is not present in the open session.
/// its manifest entry. NEVER unlinks/deletes a user PNG on this path. Throws (no
/// filesystem change) if `captureID` is not present in the open session.
/// (Session retention is the one place that removes files: when a session falls
/// outside the newest `defaultRetainedSessionCount`, its WHOLE folder — including
/// `removed/` — is pruned. That is the requested retention policy (Ben, 2026-10-11),
/// not this remove path.)
public func remove(captureID: UUID) throws -> CaptureSession {
guard let capture = openSession.captures.first(where: { $0.id == captureID }) else {
let open = try ensureOpenSession()
guard let capture = open.captures.first(where: { $0.id == captureID }) else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "capture \(captureID) is not in the open session")
}
let sessionDir = paths.sessionDirectory(openSession.id)
let sessionDir = paths.sessionDirectory(open.id)
let removedDir = sessionDir.appendingPathComponent("removed", isDirectory: true)
do {
try FileManager.default.createDirectory(at: removedDir, withIntermediateDirectories: true)
@@ -87,35 +119,110 @@ public actor SpoolStore {
}
/// Closes the open session (must be non-empty), moves its directory under archive/, records
/// pdfFileName, and starts a fresh empty open session. Returns the archived one.
/// pdfFileName, starts a fresh empty open session, and applies session retention.
/// Returns the archived one.
public func archiveCurrent(pdfFileName: String) throws -> CaptureSession {
guard !openSession.isEmpty else {
let open = try ensureOpenSession()
guard !open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
path: paths.sessionDirectory(open.id).path,
underlying: "cannot archive an empty session")
}
let archived = openSession.markArchived(pdfFileName: pdfFileName)
let sessionDir = paths.sessionDirectory(openSession.id)
let archived = try moveOpenSessionToArchive(open.markArchived(pdfFileName: pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
applyRetention()
return archived
}
/// Closes the open session — sent or not — and keeps its captures as a past
/// session under archive/, then starts a fresh empty open session. Unlike
/// `archiveCurrent(pdfFileName:)` this never requires a PDF: the archived session
/// keeps whatever pdfFileName it already has (nil when it was never sent, which
/// the Past submissions list shows as "Not sent"). An empty open session is
/// simply replaced — there is nothing to keep. Returns the archived session, or
/// nil when the open session was empty.
public func closeCurrentSession() throws -> CaptureSession? {
let open = try ensureOpenSession()
guard !open.isEmpty else {
openSession = try Self.createFreshSession(paths: paths)
return nil
}
let archived = try moveOpenSessionToArchive(
open.markArchived(pdfFileName: open.pdfFileName))
openSession = try Self.createFreshSession(paths: paths)
applyRetention()
return archived
}
/// Keeps the newest `limit` archived sessions and removes the rest of the session
/// folders from archive/ (the single folder all sessions live in). Returns the
/// removed ids. Only UUID session folders directly under archive/ are ever
/// touched — never spool/, never anything else. This is the requested retention
/// policy (Ben, 2026-10-11: "retain the past 10 sessions"): a session folder
/// dropped here is gone for good, while any PDF it produced stays in the
/// outbox/OneDrive folder it was sent to.
public func pruneArchivedSessions(keeping limit: Int) throws -> [UUID] {
let sessions = try archivedSessions()
guard sessions.count > limit else { return [] }
var removed: [UUID] = []
for session in sessions.dropFirst(limit) {
let dir = paths.archiveDirectory(session.id)
do {
try FileManager.default.removeItem(at: dir)
} catch {
throw ShotdeckError.spoolWriteFailed(
path: dir.path,
underlying: "could not remove an expired session: \(error.localizedDescription)")
}
removed.append(session.id)
}
try AtomicFile.fsyncDirectory(at: paths.archive)
return removed
}
/// The retention policy every archive path funnels through, so it can never be
/// forgotten: sessions over the default count are pruned. A retention failure is
/// logged loudly (with the exact path) and never thrown — the archive it follows
/// already succeeded, and converting a completed send into a reported failure
/// would be a lie (the safe direction of a failed prune is keeping too much, never
/// losing data). The visible symptom of a failed prune is simply more than 10
/// sessions in the Past submissions list.
private func applyRetention() {
do {
let removed = try pruneArchivedSessions(keeping: Self.defaultRetainedSessionCount)
if !removed.isEmpty {
Log.spool.warning(
"Session retention: removed \(removed.count, privacy: .public) archived session(s) beyond the newest \(Self.defaultRetainedSessionCount, privacy: .public).")
}
} catch {
Log.spool.error(
"Session retention failed — past sessions were kept beyond \(Self.defaultRetainedSessionCount, privacy: .public): \((error as? ShotdeckError)?.errorDescription ?? error.localizedDescription, privacy: .public)")
}
}
/// Writes the archived manifest, then renames the whole session directory from
/// spool/ into archive/ in one atomic operation.
private func moveOpenSessionToArchive(_ archived: CaptureSession) throws -> CaptureSession {
let sessionDir = paths.sessionDirectory(archived.id)
try AtomicFile.writeJSON(archived, to: sessionDir.appendingPathComponent("session.json"))
let archiveDir = paths.archiveDirectory(openSession.id)
let archiveDir = paths.archiveDirectory(archived.id)
guard rename(sessionDir.path, archiveDir.path) == 0 else {
throw ShotdeckError.spoolWriteFailed(
path: sessionDir.path,
underlying: "could not move the session into archive/: \(String(cString: strerror(errno)))")
}
try AtomicFile.fsyncDirectory(at: paths.archive)
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
return archived
}
/// Abandons the open session only if it is empty (mints a new id/dir/manifest); throws,
/// with no filesystem change, if the open session has captures.
public func startNewSession() throws -> CaptureSession {
guard openSession.isEmpty else {
let open = try ensureOpenSession()
guard open.isEmpty else {
throw ShotdeckError.spoolWriteFailed(
path: paths.sessionDirectory(openSession.id).path,
underlying: "cannot start a new session: \(openSession.captures.count) capture(s) present in the open session")
path: paths.sessionDirectory(open.id).path,
underlying: "cannot start a new session: \(open.captures.count) capture(s) present in the open session")
}
let fresh = try Self.createFreshSession(paths: paths)
openSession = fresh
@@ -129,19 +236,44 @@ public actor SpoolStore {
return dir.appendingPathComponent(capture.fileName)
}
/// Archived sessions, newest createdAt first. Lazily reconciles each archive/ directory
/// Archived sessions, newest first. Lazily reconciles each archive/ directory
/// the same way init reconciles spool/ candidates (orphan recovery, missing-drop, corrupt
/// rebuild) — an archived session's manifest can degrade too and must self-heal without
/// ever losing a PNG.
///
/// Order: manifest `createdAt` first (whole-second ISO8601 — the manifest format is
/// pinned in AtomicFileTests), then the session folder's creation date and content
/// modification date to break ties at real resolution (two sessions closed in the
/// same second would otherwise order, and therefore prune, arbitrarily by UUID —
/// and on a volume that reports no creation date the modification date still keeps
/// retention on real order), then the id as the final deterministic tie-break.
/// The folder dates are tie-break refinements only — the manifest `createdAt` stays
/// the authoritative timestamp; if a volume reports neither date the tie-break
/// degrades to the id.
public func archivedSessions() throws -> [CaptureSession] {
let ids = try Self.listUUIDDirectories(in: paths.archive, fileManager: .default)
var sessions: [CaptureSession] = []
var keyed: [(session: CaptureSession, folderCreatedAt: Date, folderModifiedAt: Date)] = []
for id in ids {
sessions.append(
try Self.reconcileSessionDirectory(
at: paths.archiveDirectory(id), id: id, assumedStateIfRebuilt: .archived, fileManager: .default))
let dir = paths.archiveDirectory(id)
// Read the folder dates BEFORE reconciling: reconciliation can rewrite
// session.json and bump the folder's modification date to "now", which
// would let a healed older session outrank a genuinely newer same-second
// peer in the tie-break below.
let values = try? dir.resourceValues(forKeys: [.creationDateKey, .contentModificationDateKey])
let session = try Self.reconcileSessionDirectory(
at: dir, id: id, assumedStateIfRebuilt: .archived, fileManager: .default)
// The manifest `createdAt` is the authoritative timestamp; the folder dates
// only refine ties between same-second sessions.
let folderCreatedAt = values?.creationDate ?? session.createdAt
let folderModifiedAt = values?.contentModificationDate ?? folderCreatedAt
keyed.append((session, folderCreatedAt, folderModifiedAt))
}
return sessions.sorted { ($0.createdAt, $0.id.uuidString) > ($1.createdAt, $1.id.uuidString) }
return keyed
.sorted { lhs, rhs in
(lhs.session.createdAt, lhs.folderCreatedAt, lhs.folderModifiedAt, lhs.session.id.uuidString)
> (rhs.session.createdAt, rhs.folderCreatedAt, rhs.folderModifiedAt, rhs.session.id.uuidString)
}
.map(\.session)
}
// MARK: - Reconciliation (static so they can run inside init)