diff --git a/Sources/Lichtkasten/Services/AppState.swift b/Sources/Lichtkasten/Services/AppState.swift index 4b59f0b..0446b9d 100644 --- a/Sources/Lichtkasten/Services/AppState.swift +++ b/Sources/Lichtkasten/Services/AppState.swift @@ -629,6 +629,8 @@ final class AppState: ObservableObject { self.tasks.cancel(taskID) } catch { self.tasks.finish(taskID, error: error.localizedDescription) + // e.g. disk full: say it loudly – the card stays in (no eject), what was copied is complete + self.alert = AppAlert(title: "Ingest abgebrochen", message: error.localizedDescription) } } } diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift index cc85756..dbe25f2 100644 --- a/Sources/LichtkastenCore/Ingest/IngestService.swift +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -135,10 +135,75 @@ public enum IngestService { /// Copy + make the copy writable again (otherwise locked files stay locked and metadata can't be written). static func copy(_ src: URL, to dest: URL) throws { let fm = FileManager.default - try fm.copyItem(at: src, to: dest) + do { + try fm.copyItem(at: src, to: dest) + } catch { + try? fm.removeItem(at: dest) // no half file (e.g. disk full in the middle of a RAW) + if isDiskFull(error) { throw UploadError.failed(diskFullMessage(dest)) } + throw error + } try? fm.setAttributes([.immutable: false, .posixPermissions: 0o644], ofItemAtPath: dest.path) } + // MARK: Free space + + /// Kept free on every destination – the Mac (and Lightroom's previews) still need room afterwards. + static let reserveBytes: Int64 = 2 * 1024 * 1024 * 1024 + + static func freeBytes(_ url: URL) -> Int64? { + // the folder may not exist yet → ask the nearest existing parent + var u = url + while !FileManager.default.fileExists(atPath: u.path), u.pathComponents.count > 1 { u.deleteLastPathComponent() } + let v = try? u.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey]) + return v?.volumeAvailableCapacityForImportantUsage ?? v?.volumeAvailableCapacity.map(Int64.init) + } + + static func volumeID(_ url: URL) -> String { + var u = url + while !FileManager.default.fileExists(atPath: u.path), u.pathComponents.count > 1 { u.deleteLastPathComponent() } + return (try? u.resourceValues(forKeys: [.volumeURLKey]).volume?.path) ?? "/" + } + + static func isDiskFull(_ error: Error) -> Bool { + let ns = error as NSError + if ns.domain == NSCocoaErrorDomain && ns.code == NSFileWriteOutOfSpaceError { return true } + if ns.domain == NSPOSIXErrorDomain && ns.code == Int(ENOSPC) { return true } + if let u = ns.userInfo[NSUnderlyingErrorKey] as? Error { return isDiskFull(u) } + return false + } + + static func diskFullMessage(_ url: URL) -> String { + "Speicherplatz voll auf „\(volumeName(url))“ – Ingest abgebrochen. Die bis dahin kopierten Fotos sind vollständig." + } + + static func volumeName(_ url: URL) -> String { + URL(fileURLWithPath: volumeID(url)).lastPathComponent.isEmpty ? "Macintosh HD" : URL(fileURLWithPath: volumeID(url)).lastPathComponent + } + + static func size(_ files: [URL]) -> Int64 { + files.reduce(0) { $0 + (((try? FileManager.default.attributesOfItem(atPath: $1.path)[.size]) as? NSNumber)?.int64Value ?? 0) } + } + + /// Before the first copy: enough room for everything on every destination (primary and backup on the same + /// disk count twice)? Otherwise stop right away instead of filling the disk halfway. + static func checkFreeSpace(entriesFiles: [[URL]], destRoots: [URL]) throws { + let needed = size(entriesFiles.flatMap { $0 }) + var perVolume: [String: (need: Int64, url: URL)] = [:] + for root in destRoots { + let id = volumeID(root) + perVolume[id, default: (0, root)].need += needed + } + let f = ByteCountFormatter() + for (_, v) in perVolume { + guard let free = freeBytes(v.url) else { continue } + if v.need + reserveBytes > free { + throw UploadError.failed("Nicht genug Speicherplatz auf „\(volumeName(v.url))“: benötigt \(f.string(fromByteCount: v.need)) " + + "(+ \(f.string(fromByteCount: reserveBytes)) Reserve), frei \(f.string(fromByteCount: free)). " + + "Ingest nicht gestartet – Platz schaffen, anderes Ziel wählen oder weniger Fotos (z. B. nur RAW) kopieren.") + } + } + } + // MARK: Run /// Copies the photos (and their XMP sidecars) from `sources` like PM's Ingest. @@ -218,6 +283,7 @@ public enum IngestService { let total = entries.reduce(0) { $0 + $1.files.filter { $0.pathExtension.lowercased() != "xmp" }.count } var done = 0 + try checkFreeSpace(entriesFiles: entries.map(\.files), destRoots: destRoots) progress(IngestProgress(done: 0, total: total, currentFile: "Starte …")) defer { if historyChanged, let historyFile { try? saveHistory(history, at: historyFile) } @@ -225,6 +291,13 @@ public enum IngestService { } for entry in entries { try Task.checkCancellation() + // the disk may also fill up from elsewhere during the ingest (LR previews, other copies) + let groupSize = size(entry.files) + for root in destRoots { + if let free = freeBytes(root), free < groupSize + reserveBytes / 4 { + throw UploadError.failed(diskFullMessage(root)) + } + } let item = entry.item let ctx = VariableContext.make(fileURL: item.primary, exif: item.exif, sequence: settings.sequenceEnabled ? seq : nil, iptc: item.iptc) diff --git a/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift index db9790e..626c363 100644 --- a/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift +++ b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift @@ -105,3 +105,20 @@ final class IngestRecoveryTests: XCTestCase { exiftool: ExifTool(executable: exe), historyFile: history) { _ in } } } + +final class IngestSpaceTests: XCTestCase { + func testRefusesWhenDestinationIsTooSmall() throws { + let dir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: dir) } + let free = try XCTUnwrap(IngestService.freeBytes(dir)) + // a sparse "card file" larger than the free space of the destination + let big = dir.appendingPathComponent("big.NEF") + FileManager.default.createFile(atPath: big.path, contents: nil) + let h = try FileHandle(forWritingTo: big) + try h.truncate(atOffset: UInt64(free) + 1) + try h.close() + XCTAssertThrowsError(try IngestService.checkFreeSpace(entriesFiles: [[big]], destRoots: [dir.appendingPathComponent("INPUT")])) + XCTAssertNoThrow(try IngestService.checkFreeSpace(entriesFiles: [], destRoots: [dir])) + } +}