Ingest: bei zu wenig Speicherplatz abbrechen

- vor dem Kopieren: Platzbedarf pro Ziel-Volume (Haupt + Backup auf derselben Platte doppelt)
  plus 2 GB Reserve geprüft – reicht es nicht, startet der Ingest gar nicht erst
- während des Ingests: vor jedem Foto erneut geprüft (Platte kann sich auch anders füllen)
- volle Platte beim Kopieren: halbe Datei wird entfernt, klare Meldung, Karte wird nicht ausgeworfen,
  bis dahin kopierte Fotos sind vollständig und stehen im Verlauf

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
Lichtkasten DevandClaude Opus 5.5 committed 2026-11-06 23:55:04 +00:00
1 parent b2210757dd
commit b9d7ea3146
3 files changed
+92

No files matched your search

@@ -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)
}
}
}
@@ -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
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)
@@ -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]))
}
}