Repository Public
1// SP Lecture Studio — LectureStorage2// File: Packages/LectureStorage/Sources/EventLog.swift3// Description: Append-only, crash tolerant writer for events.jsonl (each event is one line, flushed to disk on a short interval).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import LectureCore910/// Thread-safe appender. Events are written immediately with `write(2)` and forced to stable storage (`fsync`)11/// at most every `syncInterval` seconds and on every `flush()`; a crash can lose at most that interval of events.12public final class EventLogWriter: @unchecked Sendable {13 private let lock = NSLock()14 private let handle: FileHandle15 private var nextSeq: Int6416 private var lastSync = Date.distantPast17 private var dirty = false18 public let syncInterval: TimeInterval19 public let url: URL2021 public init(url: URL, syncInterval: TimeInterval = 1.0) throws {22 self.url = url; self.syncInterval = syncInterval23 let fm = FileManager.default24 if !fm.fileExists(atPath: url.path) { fm.createFile(atPath: url.path, contents: nil) }25 ProjectPackage.protect(url)26 // Continue numbering after the existing events; repair a truncated tail by starting on a fresh line.27 let existing = (try? Data(contentsOf: url)) ?? Data()28 let parsed = EventCoding.parse(existing)29 nextSeq = (parsed.events.map(\.seq).max() ?? 0) + 130 handle = try FileHandle(forWritingTo: url)31 try handle.seekToEnd()32 if let last = existing.last, last != 0x0A { try handle.write(contentsOf: Data([0x0A])) }33 }3435 deinit { try? handle.synchronize(); try? handle.close() }3637 @discardableResult38 public func append(_ payload: EventPayload, at t: MediaTime, wall: Date = Date()) -> TimelineEvent {39 lock.lock(); defer { lock.unlock() }40 let event = TimelineEvent(seq: nextSeq, t: t, wall: wall, e: payload)41 nextSeq += 142 if let line = try? EventCoding.line(for: event) {43 try? handle.write(contentsOf: line); dirty = true44 if Date().timeIntervalSince(lastSync) >= syncInterval { syncLocked() }45 }46 return event47 }4849 /// Forces everything written so far to stable storage (pause, stop, app going to the background, checkpoints).50 public func flush() { lock.lock(); syncLocked(); lock.unlock() }5152 private func syncLocked() {53 guard dirty else { return }54 try? handle.synchronize(); dirty = false; lastSync = Date()55 }56}57