Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / apple / Shared / BlobStore.swift

BlobStore.swift115 lines · 4.7 KiBRaw
1// EverySync Apple shells — blob sidecar store.
2//
3// Note image bytes keyed by `fileName` (see IPC_CONTRACT.md + `NoteKind`):
4// envelopes carry only the name + `widthFraction`; bytes ride the blob
5// channel `notes-blobs:<vaultId>` and land here. Zero sync logic — pure file
6// I/O under the same App-Group container + `NSFileCoordinator` as
7// `EnvelopeIPC.swift`.
8
9import Foundation
10
11public enum BlobStoreError: Error {
12 case containerUnavailable
13 case invalidFileName
14 case io(Error)
15}
16
17/// Content-addressed-ish file store: `<group>/vault/<vaultId>/blobs/<fileName>`.
18/// `fileName` values come from the XCFramework (`NoteKind.imageNames`); they
19/// are `"<sha256>.jpg"`-shaped. This store REJECTS any name containing a path
20/// separator or `..` so a hostile envelope can never escape the vault dir.
21public final class BlobStore {
22 private let fileManager = FileManager.default
23 private let coordinator = NSFileCoordinator()
24 private let queue = DispatchQueue(label: "com.vayunmathur.everysync.blob-store")
25
26 public init() {}
27
28 // MARK: - Ops (called only with XCFramework-derived names/hashes)
29
30 /// Reads blob bytes; nil when absent (a missing blob is NOT an error —
31 /// the hub prefetches via `NoteKind.imageNames(blocksJson)`; the note
32 /// renders with a placeholder until the blob arrives).
33 public func read(vaultId: String, fileName: String) throws -> Data? {
34 let safe = try checkedFileName(fileName)
35 return try queue.sync {
36 let url = try blobURL(vaultId: vaultId, fileName: safe)
37 var result: Data?
38 var caught: Error?
39 var coordError: NSError?
40 coordinator.coordinate(readingItemAt: url, options: [], error: &coordError) { readURL in
41 do {
42 result = try Data(contentsOf: readURL)
43 } catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSFileReadNoSuchFileError {
44 result = nil
45 } catch {
46 caught = error
47 }
48 }
49 if let caught { throw BlobStoreError.io(caught) }
50 return result
51 }
52 }
53
54 /// Idempotent write keyed on `fileName`. Overwrites are safe: file names
55 /// embed the content hash, so same-name bytes are same-content bytes.
56 public func write(vaultId: String, fileName: String, data: Data) throws {
57 let safe = try checkedFileName(fileName)
58 try queue.sync {
59 let url = try blobURL(vaultId: vaultId, fileName: safe)
60 var caught: Error?
61 var coordError: NSError?
62 coordinator.coordinate(writingItemAt: url, options: [], error: &coordError) { writeURL in
63 do {
64 try data.write(to: writeURL, options: .atomic)
65 } catch {
66 caught = error
67 }
68 }
69 if let caught { throw BlobStoreError.io(caught) }
70 }
71 }
72
73 /// Lists blob file names present for a vault (for orphan GC on the hub).
74 public func list(vaultId: String) throws -> [String] {
75 try queue.sync {
76 let dir = try blobsDirectory(vaultId: vaultId)
77 var coordError: NSError?
78 var names: [String] = []
79 coordinator.coordinate(readingItemAt: dir, options: [], error: &coordError) { readDir in
80 names = (try? fileManager.contentsOfDirectory(atPath: readDir.path)) ?? []
81 }
82 return names
83 }
84 }
85
86 // MARK: - Paths
87
88 func blobsDirectory(vaultId: String) throws -> URL {
89 precondition(!vaultId.isEmpty && !vaultId.contains("/"), "vaultId must be a bare id")
90 guard let container = fileManager.containerURL(forSecurityApplicationGroupIdentifier: EverysyncGroup.identifier) else {
91 throw BlobStoreError.containerUnavailable
92 }
93 return container.appendingPathComponent("vault/\(vaultId)/blobs", isDirectory: true)
94 }
95
96 func blobURL(vaultId: String, fileName: String) throws -> URL {
97 let dir = try blobsDirectory(vaultId: vaultId)
98 try fileManager.createDirectory(at: dir, withIntermediateDirectories: true)
99 return dir.appendingPathComponent(fileName)
100 }
101
102 /// Rejects traversal + separators. Blob names are XCFramework-derived
103 /// (`NoteKind.imageNames`), but the envelope is relay data — never trust it.
104 func checkedFileName(_ raw: String) throws -> String {
105 guard !raw.isEmpty,
106 !raw.contains("/"),
107 !raw.contains("\\"),
108 raw != ".",
109 raw != "..",
110 !raw.contains("..") else {
111 throw BlobStoreError.invalidFileName
112 }
113 return raw
114 }
115}