Cotton code
359 lines · 16.7 KB · SwiftRaw
// The recorder's promise: **audio is never lost silently.**//// A recording is bytes that exist nowhere else. The meeting ROW is not written// until Stop — the crate mints it when it copies the file — so between the// first second of a meeting and a successful `meetings.create` there is a// window in which the only record of what happened is a file on this device// and nothing pointing at it. If the app is killed in that window (the OS// reclaiming memory, a crash, a force quit) the file survives and nobody ever// looks for it again.//// This is the thing that looks for it: a marker PER RECORDING, written when a// recording starts, rewritten at each transition, and cleared only when the// crate has answered with a meeting id. On the next launch the Meetings list// reads them, and every marker whose file is still on disk becomes an offer —// Keep, which creates the meeting, or Discard, which deletes the bytes because// the person said so.//// ── One slot was one recording too few ───────────────────────────────────────//// It was a single slot until 16 Sep 2026, and the walk found what that costs:// with a note on the Meetings list offering a killed recording, starting a NEW// recording overwrote the slot, the note vanished, and the killed capture stayed// in `recordings/<id>/` with no row and nothing pointing at it — lost without a// word. So the slot is a LIST, keyed by the act's id: a marker is upserted, and// only the recording that became a meeting is cleared.//// ── The marker is a convenience; the file on disk is the truth ───────────────//// A marker can go where the audio does not: a defaults suite that did not// survive, a corrupt slot, a slot cleared by hand. So a launch also SWEEPS `recordings/` for any capture no marker names// (``MeetingRecovery/offers(markers:onDisk:exists:probe:)``) and offers that// too, with what the file itself can say — when it was made, and how long it// runs. Nothing on this device holds bytes nobody is offered.//// ── Why a defaults slot and not a file beside the audio ──────────────────────//// The spec said "a small JSON marker beside the file", and the repo says a// whole-body read is banned outright (`WholeBodySweepTests`, allow-list EMPTY,// after a 464 MB first launch read as a white screen). A marker is small and// would be a safe read — but "it is only small" is exactly the sentence that// ban exists to refuse, and there is already a channel in this app for a// device-local scrap that has to survive a launch: the App Group's// `UserDefaults`, which is where the share mailbox lives. So the marker is a// defaults slot holding the same JSON, keyed the same way, and the FILE it// names is the audio. Nothing is read whole.//// ── What the offer can and cannot promise ────────────────────────────────────//// The capture is linear PCM in a CAF, which a killed process leaves READABLE// and with its true length (`MeetingAudioFormats.capturedExtension`). So a// marker still at ``MeetingRecoveryStage/recording`` names bytes that open —// what is missing is only whatever the writer was still holding, a fraction of// a second. It is offered, and the offer says which case it is: a recording// nothing closed is not a whole recording, and saying so is not the same as// refusing to keep it.//import Foundation/// How far a recording had got when the marker was last written.public enum MeetingRecoveryStage: String, Codable, Sendable, Equatable, CaseIterable {    /// Capture was running. The file on disk is unfinalised.    case recording    /// The person had paused. Same file state as `recording` — a pause does    /// not close the file — recorded separately because it is what the offer    /// says happened.    case paused    /// Capture stopped and the file was closed, so the bytes are playable —    /// but `meetings.create` had not answered. This is the case a marker most    /// often survives in, and the one where Keep certainly works.    case closed}/// One recording that has not become a meeting yet.public struct MeetingRecoveryMarker: Codable, Equatable, Sendable {    /// The recorder's own id for this act — also the directory the audio sits    /// in, so a marker and its bytes can always be matched up.    public var id: String    /// Where the audio is, on this device.    public var path: String    /// When the recording started, RFC3339 (`CottonDate.format`).    public var startedAt: String    /// What the person had called it, if they had typed anything.    public var title: String?    /// How long had been captured when the marker was last written.    public var durationMs: Int    public var stage: String    /// The meeting the crate answered with, written just BEFORE the marker is    /// cleared. A marker carrying one is a marker whose row exists — the crash    /// landed in the gap between the answer and the clear — so recovery drops    /// it instead of offering a second copy of a meeting that is already there.    public var meetingId: String?    public init(        id: String,        path: String,        startedAt: String,        title: String? = nil,        durationMs: Int = 0,        stage: MeetingRecoveryStage = .recording,        meetingId: String? = nil    ) {        self.id = id        self.path = path        self.startedAt = startedAt        self.title = title        self.durationMs = durationMs        self.stage = stage.rawValue        self.meetingId = meetingId    }    private enum CodingKeys: String, CodingKey {        case id, path, startedAt, title, durationMs, stage, meetingId    }    /// The stage this build understands, or `nil` for a word a later one wrote.    /// An unknown stage reads as "something was captured", which is what the    /// offer needs and all it needs.    public var recoveryStage: MeetingRecoveryStage? { MeetingRecoveryStage(rawValue: stage) }    /// True once the file has been closed and is certainly playable.    public var isClosed: Bool { recoveryStage == .closed }}/// What the Meetings list is about to offer, or nothing.public struct MeetingRecoveryOffer: Equatable, Sendable {    public let marker: MeetingRecoveryMarker    /// False when the bytes were never finalised — the offer still stands, and    /// says so.    public let isPlayable: Bool    /// **How long the recording actually ran**, in milliseconds, or `nil` when    /// nothing on this device can say.    ///    /// The AUDIO's own answer where there is one, the marker's banked figure    /// where there is not — see ``MeetingRecovery/length(of:probing:)``. It is    /// what the slip says and what is sent to `meetings.create`, so the row the    /// person keeps and the sentence they were shown are the same number.    public let durationMs: Int?    /// **`durationMs` has no default**, so nothing constructs an offer without    /// saying how long the recording ran — a silent `nil` there is the slip    /// going back to "Some of it was captured" over audio the file could have    /// answered for.    public init(marker: MeetingRecoveryMarker, isPlayable: Bool, durationMs: Int?) {        self.marker = marker        self.isPlayable = isPlayable        self.durationMs = durationMs    }}/// The markers' home — one per recording, never one slot for all of them.////// It takes ``ShareMailboxStorage`` rather than declaring a second protocol/// with the same two members: there is ONE App Group defaults suite in this/// app, and two seams over it would be two things to fake in a test and two/// places for a key to be spelled.public struct MeetingRecoveryStore: Sendable {    /// The defaults key. Wire protocol between one launch and the next: change    /// it and a marker the previous build wrote is a recording nobody looks    /// for. It holds a JSON ARRAY — the single-object key it replaced is dead,    /// and a capture that key still named is found by the disk sweep, which is    /// what makes the marker a convenience rather than the record.    public static let key = "cotton.meetings.recordings.v1"    private let storage: any ShareMailboxStorage    public init(storage: any ShareMailboxStorage = DefaultsShareMailboxStorage()) {        self.storage = storage    }    /// Every recording that has not become a meeting yet, in the order they    /// were written.    ///    /// **One unreadable entry never costs the others.** Each element is decoded    /// on its own and a failure is dropped, because a whole array refused on    /// one corrupt element is every other recording lost with it — and the    /// disk sweep still offers the audio a dropped marker named. A slot that is    /// not a list at all is nothing, and it is not cleared either.    public func markers() -> [MeetingRecoveryMarker] {        guard let raw = storage.text(Self.key) else { return [] }        guard let slots = try? JSONDecoder().decode([Slot].self, from: Data(raw.utf8)) else {            return []        }        return slots.compactMap(\.marker).filter { !$0.path.isEmpty }    }    /// Write the marker for ONE recording. Called on every transition — start,    /// pause, resume, stop — because the transition that is not written down is    /// the one the crash happens after.    ///    /// **Upsert by id.** A second recording adds a row; the same recording    /// moving on replaces its own, in place, so the order on the list is the    /// order they started in.    public func write(_ marker: MeetingRecoveryMarker) {        var held = markers()        if let at = held.firstIndex(where: { $0.id == marker.id }) {            held[at] = marker        } else {            held.append(marker)        }        save(held)    }    /// That recording became a meeting, or the person discarded it. **Only that    /// one goes** — a clear that took the list with it is the bug this whole    /// shape answers.    public func clear(id: String) {        let kept = markers().filter { $0.id != id }        save(kept)    }    private func save(_ markers: [MeetingRecoveryMarker]) {        guard !markers.isEmpty else { return storage.set(Self.key, nil) }        guard            let data = try? JSONEncoder().encode(markers),            let text = String(data: data, encoding: .utf8)        else { return }        storage.set(Self.key, text)    }    /// One element of the list, decoded tolerantly. See ``markers()``.    private struct Slot: Decodable {        let marker: MeetingRecoveryMarker?        init(from decoder: Decoder) throws {            marker = try? MeetingRecoveryMarker(from: decoder)        }    }}/// A capture file this app is still holding, found by looking rather than by/// being told.////// The marker is a convenience and this is the evidence: `recordings/<act>/`/// with audio in it and no meeting made of it is a recording nobody has been/// offered, whatever the defaults suite says.public struct MeetingCaptureOnDisk: Equatable, Sendable {    /// The act's id — the directory's own name, which is what a marker is tied    /// to and what Discard acts on.    public let act: String    /// Where the audio is.    public let path: String    /// When the file was made, RFC3339 (`CottonDate.format`), or `""` when the    /// filesystem could not say. It stands in for the marker's `startedAt`,    /// which is the only thing a sweep cannot read off the bytes.    public let startedAt: String    public init(act: String, path: String, startedAt: String) {        self.act = act        self.path = path        self.startedAt = startedAt    }}/// What to do with a marker found at launch — pure, so the rule is testable/// without a container, a defaults suite or a file.public enum MeetingRecovery {    /// The offer a marker earns, or nothing.    ///    /// Three ways to earn nothing, and each is a different fact:    ///    ///  * **no marker** — no recording was interrupted;    ///  * **a marker naming a meeting** — the row exists and the crash landed    ///    in the gap before the clear; offering it would make a second copy;    ///  * **a marker whose file is gone** — iOS evicted it, or the person    ///    cleared storage. The claim is the marker's; the disk is the evidence,    ///    and a claim the disk contradicts is not one.    ///    /// `exists` and `probe` are injected rather than read here so every rule    /// above is a test with no filesystem and no audio framework in it.    public static func offer(        _ marker: MeetingRecoveryMarker?,        exists: (String) -> Bool,        probe: (String) -> Int? = { _ in nil }    ) -> MeetingRecoveryOffer? {        guard let marker, !marker.path.isEmpty else { return nil }        guard marker.meetingId == nil else { return nil }        guard exists(marker.path) else { return nil }        return MeetingRecoveryOffer(            marker: marker,            isPlayable: marker.isClosed,            durationMs: length(of: marker, probing: probe)        )    }    /// **Every recording this device is still holding, as offers** — one note    /// per unsaved recording, newest first.    ///    /// Two sources, and the order between them is the whole rule:    ///    ///  * the MARKERS, each earning an offer by ``offer(_:exists:probe:)``;    ///  * then the captures found on DISK that no marker names at all. A marker    ///    that named one and earned no offer — the row exists, the file is gone    ///    — has already answered for that act, and a sweep that offered it    ///    anyway would be a second copy of a meeting already made.    ///    /// A swept capture gets a marker synthesised from what the file itself can    /// say: its id is the directory's, its start is the file's own date, and it    /// carries no banked length, so the length on the slip is whatever the probe    /// reads off the audio.    ///    /// Newest first, because the note a person is looking for is the one that    /// just went.    public static func offers(        markers: [MeetingRecoveryMarker],        onDisk captures: [MeetingCaptureOnDisk] = [],        exists: (String) -> Bool,        probe: (String) -> Int? = { _ in nil }    ) -> [MeetingRecoveryOffer] {        var found = markers.compactMap { offer($0, exists: exists, probe: probe) }        let spokenFor = Set(markers.map(\.id))        for capture in captures where !spokenFor.contains(capture.act) {            let made = MeetingRecoveryMarker(                id: capture.act,                path: capture.path,                startedAt: capture.startedAt,                durationMs: 0,                stage: .recording            )            if let earned = offer(made, exists: exists, probe: probe) { found.append(earned) }        }        // Stable: two recordings with the same stamp — or two with none — keep        // the order they were found in rather than swapping about between draws.        return found.enumerated()            .sorted { left, right in                let a = left.element.marker.startedAt                let b = right.element.marker.startedAt                if a == b { return left.offset < right.offset }                if a.isEmpty { return false }                if b.isEmpty { return true }                return a > b            }            .map(\.element)    }    /// How long the recovered audio ran, in milliseconds — or `nil`.    ///    /// **The FILE first, the marker second.** The marker's elapsed figure is    /// banked at TRANSITIONS — start, pause, resume, stop — so a recording the    /// OS killed while it was running carries whatever was true a moment after    /// capture opened, which is nearly nothing. The walk of 15 Sep 2026 watched    /// a recording run to 0:13, killed the app, and was offered "About 1 second    /// of it was captured" over thirteen seconds of audio; the row it then kept    /// carried that same second.    ///    /// The bytes on disk cannot be stale, so they are asked first. What asks    /// them is injected: the real one is `MeetingAudioLength` over    /// `AVAudioPlayer`, which **refuses a file whose moov atom was never    /// written** rather than answering zero — the unfinalised case this whole    /// file exists for. So the marker stays as the fallback, and `nil` — no    /// length claimed at all — stays a real answer. None of the three is a    /// guess.    public static func length(        of marker: MeetingRecoveryMarker,        probing probe: (String) -> Int?    ) -> Int? {        if let read = probe(marker.path), read > 0 { return read }        return marker.durationMs > 0 ? marker.durationMs : nil    }}