Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314import Darwinimport Dispatchimport Foundation
struct ConfigFileWatcher: Sendable { private let task: Task<Void, Never> private let events: AsyncStream<WatchEvent>.Continuation
init( fileURL: URL, debounceInterval: Duration, sleep: @escaping @Sendable (Duration) async throws -> Void = { try await Task.sleep(for: $0) }, changed: @escaping @Sendable () async -> Bool, failed: @escaping @Sendable (ConfigDiagnostic) async -> Void ) { let (events, continuation) = AsyncStream<WatchEvent>.makeStream() self.events = continuation task = Task.detached(priority: .utility) { let queue = DispatchQueue(label: "ParcelConfig.file-watcher", qos: .utility) var observations: [String: FileObservation] = [:] var debounce: Task<Void, Never>? var generation: UUID? defer { debounce?.cancel() for observation in observations.values { observation.source.cancel() } continuation.finish() } do { try Self.refresh(fileURL, observations: &observations, queue: queue, events: continuation) guard !Task.isCancelled, await changed() else { return } for await event in events { guard !Task.isCancelled else { return } switch event { case .changed: // Sibling-file activity must not postpone a config reload indefinitely. guard debounce == nil else { continue } let id = UUID() generation = id debounce = Task { do { try await sleep(debounceInterval) if !Task.isCancelled { continuation.yield(.reload(id)) } } catch is CancellationError { return } catch { continuation.yield(.failure(Self.diagnostic(error))) } } case .reload(let id): guard generation == id else { continue } debounce = nil generation = nil try Self.refresh(fileURL, observations: &observations, queue: queue, events: continuation) guard await changed() else { return } case .failure(let diagnostic): await failed(diagnostic) return } } } catch { if !Task.isCancelled { await failed(Self.diagnostic(error)) } } } }
func requestReload() { events.yield(.changed) }
func cancel() { task.cancel() }
func waitUntilFinished() async { await task.value }
private static func diagnostic(_ error: any Error) -> ConfigDiagnostic { ConfigDiagnostic( message: String( localized: "Configuration watching stopped unexpectedly: \(error.localizedDescription)", table: "Store", bundle: .module ) ) }
private static func refresh( _ url: URL, observations: inout [String: FileObservation], queue: DispatchQueue, events: AsyncStream<WatchEvent>.Continuation ) throws { guard url.isFileURL else { throw ConfigDiagnostic( message: String( localized: "The configuration URL must point to a local file: \(url.absoluteString)", table: "Store", bundle: .module ) ) } while !Task.isCancelled { let paths = try watchPaths(for: url) try observe(paths, observations: &observations, queue: queue, events: events) // A save can replace the path between discovery and opening its descriptor. let latest = try watchPaths(for: url) guard latest == paths, try latest.keys.allSatisfy({ try matches($0, observation: observations[$0]) }) else { continue } for path in observations.keys where latest[path] == nil { observations.removeValue(forKey: path)?.source.cancel() } return } }
private static func matches(_ path: String, observation: FileObservation?) throws -> Bool { guard let observation else { return false } var metadata = stat() guard stat(path, &metadata) == 0 else { let code = errno guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } return false } return observation.device == metadata.st_dev && observation.inode == metadata.st_ino }
private static func observe( _ paths: [String: DispatchSource.FileSystemEvent], observations: inout [String: FileObservation], queue: DispatchQueue, events: AsyncStream<WatchEvent>.Continuation ) throws { for (path, mask) in paths.sorted(by: { $0.key < $1.key }) { var metadata = stat() if stat(path, &metadata) != 0 { let code = errno guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } observations.removeValue(forKey: path)?.source.cancel() continue } if let current = observations[path], current.device == metadata.st_dev, current.inode == metadata.st_ino, current.mask == mask { continue } observations.removeValue(forKey: path)?.source.cancel() let descriptor = open(path, O_EVTONLY | O_CLOEXEC) guard descriptor >= 0 else { let code = errno guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: path) } continue } var opened = stat() guard fstat(descriptor, &opened) == 0 else { let code = errno close(descriptor) throw fileError(code, path: path) } let source = DispatchSource.makeFileSystemObjectSource( fileDescriptor: descriptor, eventMask: mask, queue: queue ) source.setEventHandler { events.yield(.changed) } source.setCancelHandler { close(descriptor) } observations[path] = FileObservation( source: source, device: opened.st_dev, inode: opened.st_ino, mask: mask) source.activate() } }
static func watchPaths( for url: URL, readLink: (String) throws -> String? = symlinkDestination ) throws -> [String: DispatchSource.FileSystemEvent] { var paths: Set<String> = [] var current = URL(fileURLWithPath: "/", isDirectory: true) var remaining = Array(url.pathComponents.dropFirst().reversed()) var links = 0 while let component = remaining.popLast() { try Task.checkCancellation() if component == "." { continue } if component == ".." { current.deleteLastPathComponent() continue } let next = current.appendingPathComponent(component) var metadata = stat() if lstat(next.path, &metadata) != 0 { let code = errno guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: next.path) } current = next while let suffix = remaining.popLast() { current.appendPathComponent(suffix) } break } if metadata.st_mode & S_IFMT == S_IFLNK { paths.insert(current.path) guard let destination = try readLink(next.path) else { remaining.append(component) continue } links += 1 guard links <= 40 else { throw fileError(ELOOP, path: next.path) } let components = NSString(string: destination).pathComponents if destination.hasPrefix("/") { current = URL(fileURLWithPath: "/", isDirectory: true) } remaining.append(contentsOf: components.filter { $0 != "/" }.reversed()) } else { current = next } } paths.insert(current.path) paths.insert(current.deletingLastPathComponent().path) // Missing directories need their nearest surviving ancestor to announce recreation. var existing: [String: DispatchSource.FileSystemEvent] = [:] for path in paths { var candidate = URL(fileURLWithPath: path) var metadata = stat() while stat(candidate.path, &metadata) != 0 { let code = errno guard code == ENOENT || code == ENOTDIR else { throw fileError(code, path: candidate.path) } candidate.deleteLastPathComponent() } existing[candidate.path, default: []].formUnion([ .write, .extend, .attrib, .link, .rename, .delete, .revoke, ]) // Ancestors report moves without waking us for unrelated descendant writes. while candidate.path != "/" { candidate.deleteLastPathComponent() existing[candidate.path, default: []].formUnion([.rename, .delete, .revoke]) } } return existing }
static func symlinkDestination(_ path: String) throws -> String? { var buffer = [CChar](repeating: 0, count: Int(PATH_MAX) + 1) let count = readlink(path, &buffer, buffer.count - 1) guard count >= 0 else { let code = errno // The link may have disappeared or become a regular file since lstat. if code == ENOENT || code == ENOTDIR || code == EINVAL { return nil } throw fileError(code, path: path) } guard count < buffer.count - 1 else { throw fileError(ENAMETOOLONG, path: path) } let bytes = buffer.prefix(count).map { UInt8(bitPattern: $0) } guard let destination = String(validating: bytes, as: UTF8.self) else { throw fileError(EILSEQ, path: path) } return destination }
private static func fileError(_ code: Int32, path: String) -> NSError { NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: path]) }}
private enum WatchEvent: Sendable { case changed case reload(UUID) case failure(ConfigDiagnostic)}
private struct FileObservation { let source: any DispatchSourceFileSystemObject let device: dev_t let inode: ino_t let mask: DispatchSource.FileSystemEvent}
enum ConfigFileContents: Sendable, Equatable { case bytes(Data) case missing case failure(ConfigDiagnostic)
static func read(from url: URL) -> ConfigFileContents { guard url.isFileURL else { return .failure( ConfigDiagnostic( message: String( localized: "The configuration URL must point to a local file: \(url.absoluteString)", table: "Store", bundle: .module ) ) ) } do { var metadata = stat() guard stat(url.path, &metadata) == 0 else { let code = errno if code == ENOENT || code == ENOTDIR { return .missing } throw NSError(domain: NSPOSIXErrorDomain, code: Int(code), userInfo: [NSFilePathErrorKey: url.path]) } guard metadata.st_mode & S_IFMT == S_IFREG else { return .failure( ConfigDiagnostic( message: String( localized: "The configuration path is not a regular file: \(url.path)", table: "Store", bundle: .module ) ) ) } return .bytes(try Data(contentsOf: url)) } catch let error as CocoaError where error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile { return .missing } catch { return .failure( ConfigDiagnostic( message: String( localized: "Could not read the configuration file at \(url.path): \(error.localizedDescription)", table: "Store", bundle: .module ) ) ) } }}