From 244734c59fad34c48b546a329222213ddc390f4d Mon Sep 17 00:00:00 2001 From: Lichtkasten Dev Date: Sat, 7 Nov 2026 17:49:13 +0000 Subject: [PATCH] =?UTF-8?q?Ingest:=20freien=20Speicher=20auf=20externen=20?= =?UTF-8?q?Platten=20zuverl=C3=A4ssig=20messen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ein zweiter Ingest scheiterte nach dem Freiräumen mit denselben Zahlen: volumeAvailableCapacityForImportantUsage liefert für externe Platten (exFAT/HFS+) keinen verlässlichen, aktuellen Wert. Jetzt: - externe Platten: freier Platz per statfs, bei jedem Ingest frisch gelesen - interne Platte: größerer Wert aus statfs und „important usage“ (löschbarer APFS-Speicher zählt) - Reserve 2 GB nur auf der Mac-Platte, 256 MB auf externen Fotoplatten - Haupt- und Backup-Ziel nur bei gleicher Volume-ID zusammengerechnet - nicht angeschlossene Ziel-Platte (/Volumes/…) wird gemeldet statt auf die Mac-Platte zu messen - Hinweis in der Meldung: gelöschte Dateien liegen bis zum Leeren im Papierkorb der Platte Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D --- .../Ingest/IngestService.swift | 70 +++++++++++++++---- .../IngestRecoveryTests.swift | 15 ++++ 2 files changed, 71 insertions(+), 14 deletions(-) diff --git a/Sources/LichtkastenCore/Ingest/IngestService.swift b/Sources/LichtkastenCore/Ingest/IngestService.swift index dbe25f2..824dcba 100644 --- a/Sources/LichtkastenCore/Ingest/IngestService.swift +++ b/Sources/LichtkastenCore/Ingest/IngestService.swift @@ -147,21 +147,58 @@ public enum IngestService { // MARK: Free space - /// Kept free on every destination – the Mac (and Lightroom's previews) still need room afterwards. + /// Kept free on the Mac's own disk (the system and Lightroom's previews still need room afterwards); + /// an external photo disk may be filled almost completely. static let reserveBytes: Int64 = 2 * 1024 * 1024 * 1024 + static let externalReserveBytes: Int64 = 256 * 1024 * 1024 - static func freeBytes(_ url: URL) -> Int64? { - // the folder may not exist yet → ask the nearest existing parent - var u = url + /// Nearest existing folder (the destination folder may not exist yet). + static func existingAncestor(_ url: URL) -> URL { + var u = url.standardizedFileURL 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) + return u + } + + static func isInternal(_ url: URL) -> Bool { + (try? existingAncestor(url).resourceValues(forKeys: [.volumeIsInternalKey]).volumeIsInternal) ?? true + } + + static func reserve(for url: URL) -> Int64 { isInternal(url) ? reserveBytes : externalReserveBytes } + + /// Free space, read fresh from the file system every time. + /// `volumeAvailableCapacityForImportantUsage` alone is not reliable for external disks (exFAT/HFS+ report + /// the value of the Mac's disk or a stale one – a second ingest then failed with the same numbers even + /// after making room), so external disks use statfs; the internal disk the larger of both + /// (APFS purgeable space counts there). + static func freeBytes(_ url: URL) -> Int64? { + let u = existingAncestor(url) + let fsFree = ((try? FileManager.default.attributesOfFileSystem(forPath: u.path))?[.systemFreeSize] as? NSNumber)?.int64Value + guard isInternal(u) else { return fsFree } + let important = (try? u.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]))? + .volumeAvailableCapacityForImportantUsage + switch (fsFree, important) { + case let (f?, i?): return max(f, i) + case let (f?, nil): return f + case let (nil, i?): return i + default: return nil + } } 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) ?? "/" + let u = existingAncestor(url) + let v = try? u.resourceValues(forKeys: [.volumeURLKey, .volumeIdentifierKey]) + if let id = v?.volumeIdentifier { return "\(id)" } + return v?.volume?.path ?? u.path // unknown → never merged with another destination + } + + /// "/Volumes/Fotos 2TB/BILDER" while that disk is not connected → would silently go to the Mac's disk. + static func checkDestinationMounted(_ url: URL) throws { + let parts = url.standardizedFileURL.pathComponents + guard parts.count >= 3, parts[1] == "Volumes" else { return } + let volume = "/Volumes/" + parts[2] + if !FileManager.default.fileExists(atPath: volume) { + throw UploadError.failed("Die Ziel-Platte „\(parts[2])“ ist nicht angeschlossen (\(url.path)). Ingest nicht gestartet.") + } } static func isDiskFull(_ error: Error) -> Bool { @@ -177,7 +214,8 @@ public enum IngestService { } static func volumeName(_ url: URL) -> String { - URL(fileURLWithPath: volumeID(url)).lastPathComponent.isEmpty ? "Macintosh HD" : URL(fileURLWithPath: volumeID(url)).lastPathComponent + let v = try? existingAncestor(url).resourceValues(forKeys: [.volumeLocalizedNameKey, .volumeURLKey]) + return v?.volumeLocalizedName ?? v?.volume?.lastPathComponent ?? "Macintosh HD" } static func size(_ files: [URL]) -> Int64 { @@ -187,7 +225,9 @@ public enum IngestService { /// 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 { + for root in destRoots { try checkDestinationMounted(root) } let needed = size(entriesFiles.flatMap { $0 }) + guard needed > 0 else { return } var perVolume: [String: (need: Int64, url: URL)] = [:] for root in destRoots { let id = volumeID(root) @@ -196,10 +236,12 @@ public enum IngestService { let f = ByteCountFormatter() for (_, v) in perVolume { guard let free = freeBytes(v.url) else { continue } - if v.need + reserveBytes > free { + let reserve = reserve(for: v.url) + if v.need + reserve > 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.") + + "(+ \(f.string(fromByteCount: reserve)) Reserve), frei \(f.string(fromByteCount: free)). " + + "Ingest nicht gestartet – Platz schaffen (gelöschte Dateien liegen bis zum Leeren im Papierkorb " + + "der Platte), anderes Ziel wählen oder weniger Fotos (z. B. nur RAW) kopieren.") } } } @@ -294,7 +336,7 @@ public enum IngestService { // 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 { + if let free = freeBytes(root), free < groupSize + reserve(for: root) / 4 { throw UploadError.failed(diskFullMessage(root)) } } diff --git a/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift index 626c363..3b7f880 100644 --- a/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift +++ b/Tests/LichtkastenCoreTests/IngestRecoveryTests.swift @@ -122,3 +122,18 @@ final class IngestSpaceTests: XCTestCase { XCTAssertNoThrow(try IngestService.checkFreeSpace(entriesFiles: [], destRoots: [dir])) } } + +final class IngestDestinationTests: XCTestCase { + func testMissingExternalDiskIsReported() { + XCTAssertThrowsError(try IngestService.checkDestinationMounted(URL(fileURLWithPath: "/Volumes/Nicht-da-\(UUID().uuidString)/BILDER"))) + XCTAssertNoThrow(try IngestService.checkDestinationMounted(FileManager.default.temporaryDirectory)) + } + + func testFreeSpaceIsReadFreshEachTime() 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 before = try XCTUnwrap(IngestService.freeBytes(dir.appendingPathComponent("noch/nicht/da"))) + XCTAssertGreaterThan(before, 0) + } +}