Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XUtils / TemporaryDirectory.swift

TemporaryDirectory.swift196 lines · 7.3 KiBRaw
1import Foundation
2#if os(Linux)
3import Glibc
4#endif
5
6package struct TemporaryDirectory: ~Copyable {
7 private static let debugTmp = ProcessInfo.processInfo.environment["XTL_DEBUG_TMP"] != nil
8
9 private var shouldDelete: Bool
10 private let base: URL
11 package let url: URL
12
13 /// Prepares a fresh tmpdir root.
14 ///
15 /// Optional, but try calling this at launch to clean up old resources.
16 package static func prepare() {
17 _ = TemporaryDirectoryRoot.shared
18 }
19
20 /// Creates a temporary directory where `lastPathComponent` is exactly `name`.
21 ///
22 /// The directory is deleted on deinit or (if the object never deinits) on next launch.
23 /// To save the contents, move them elsewhere with ``persist(at:)``.
24 package init(name: String) throws {
25 do {
26 let basename = name
27 .replacingOccurrences(of: ".", with: "_")
28 .replacingOccurrences(of: "/", with: "_")
29 .prefix(32)
30 self.base = try TemporaryDirectoryRoot.shared.url
31 // ensures uniqueness
32 .appendingPathComponent("dir-\(basename)-\(UUID().uuidString)")
33 self.url = base.appendingPathComponent(name, isDirectory: true)
34 self.shouldDelete = true
35 } catch {
36 // non-copyable types can't be partially initialized so we need a stub value
37 self.base = URL(fileURLWithPath: "")
38 self.url = base
39 self.shouldDelete = false
40 throw error
41 }
42 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
43
44 if Self.debugTmp {
45 stderrPrint("Created TemporaryDirectory: \(url.path)")
46 }
47 }
48
49 private func _delete() {
50 guard !Self.debugTmp else { return }
51 try? FileManager.default.removeItem(at: base)
52 }
53
54 package consuming func persist(at location: URL) throws {
55 try FileManager.default.moveItem(at: url, to: location)
56 _delete()
57 // we do this after moving, so that if the move fails we clean up
58 shouldDelete = false
59 }
60
61 deinit {
62 if shouldDelete { _delete() }
63 }
64}
65
66private struct TemporaryDirectoryRoot {
67 static let shared = TemporaryDirectoryRoot()
68
69 private let _url: Result<URL, Errors>
70 var url: URL {
71 get throws(Errors) {
72 try _url.get()
73 }
74 }
75
76 private init() {
77 let url = XToolCache.directory
78
79 Self.pruneOrphans(in: url)
80
81 self._url = Result {
82 let childDir = try Self.claimDirectory(in: url)
83 try FileManager.default.createDirectory(at: childDir, withIntermediateDirectories: true)
84 return childDir
85 }
86 .mapError { $0 as? Errors ?? .tmpdirCreationFailed(url, $0) }
87 }
88
89 private static func claimDirectory(in url: URL) throws -> URL {
90 // create a lockfile + tmpdir. while we hold the lock, other instaces of
91 // xtool will not delete the directory during their prune step.
92
93 try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
94
95 let pid = ProcessInfo.processInfo.processIdentifier
96
97 for i in 0..<10 {
98 let random = "pid-\(pid)-\(i == 0 ? "0" : UUID().uuidString)"
99 let lockFile = url.appending(path: "\(random).lock")
100 #if os(macOS)
101 let fd = try FileDescriptor.open(
102 FilePath(lockFile.path),
103 .writeOnly,
104 options: [.create, .exclusiveLock],
105 permissions: [.ownerReadWrite, .groupRead, .otherRead],
106 )
107 #elseif os(Linux)
108 // POSIX directly: swift-system's FileDescriptor.open crashes in
109 // this binary on Linux (Result<_, Errno>.map traps in
110 // swift_getEnumCaseMultiPayload), so avoid it on the startup path.
111 let fd = Glibc.open(lockFile.path, O_WRONLY | O_CREAT, 0o644)
112 guard fd >= 0 else { throw Errors.tmpdirClaimFailed(url) }
113 guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
114 Glibc.close(fd)
115 continue
116 }
117 #else
118 let fd = try FileDescriptor.open(
119 FilePath(lockFile.path),
120 .writeOnly,
121 options: [.create],
122 permissions: [.ownerReadWrite, .groupRead, .otherRead],
123 )
124 guard try fd.tryLock(mode: .exclusive) else {
125 // someone else raced us and claimed the right to prune between when we created the file and
126 // when we tried to lock it
127 continue
128 }
129 #endif
130 // leak the file descriptor so that the lock is held until the process exits
131 return url.appending(path: random)
132 }
133 throw Errors.tmpdirClaimFailed(url)
134 }
135
136 /// Opens `path` and takes an exclusive non-blocking flock.
137 /// Returns true (leaving the fd open/closed by the caller path) only
138 /// when the lock was acquired. On Linux this uses POSIX directly:
139 /// swift-system's FileDescriptor.open crashes in this binary
140 /// (Result<_, Errno>.map traps in swift_getEnumCaseMultiPayload).
141 private static func tryLockOrphan(at path: String) throws -> Bool {
142 #if os(Linux)
143 let fd = Glibc.open(path, O_RDWR)
144 guard fd >= 0 else { return false }
145 defer { Glibc.close(fd) }
146 return flock(fd, LOCK_EX | LOCK_NB) == 0
147 #else
148 let lockFD = try FileDescriptor.open(FilePath(path), .readWrite)
149 defer { try? lockFD.close() }
150 return try lockFD.tryLock(mode: .exclusive)
151 #endif
152 }
153
154 private static func pruneOrphans(in url: URL) {
155 guard let children = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
156 else { return }
157 for lock in children {
158 do {
159 let basename = lock.lastPathComponent
160 if basename.hasPrefix("tmp-") {
161 // legacy tmpdir, remove it
162 try? FileManager.default.removeItem(at: lock)
163 continue
164 }
165 guard basename.hasPrefix("pid-") && basename.hasSuffix(".lock") else { continue }
166 if try Self.tryLockOrphan(at: lock.path) {
167 // we must remove the directory first. if we instead removed the lock first,
168 // we could be killed after the lock was removed but before the dir was
169 // removed and therefore leave it hanging around.
170 do {
171 try FileManager.default.removeItem(at: lock.deletingPathExtension())
172 } catch CocoaError.fileNoSuchFile {
173 // pass
174 }
175 try FileManager.default.removeItem(at: lock)
176 }
177 } catch {
178 // continue
179 }
180 }
181 }
182
183 enum Errors: Error, CustomStringConvertible {
184 case tmpdirCreationFailed(URL, Error)
185 case tmpdirClaimFailed(URL)
186
187 var description: String {
188 switch self {
189 case let .tmpdirCreationFailed(url, error):
190 "Could not create temporary directory in '\(url.path)': \(error)"
191 case let .tmpdirClaimFailed(url):
192 "Could not claim temporary directory in '\(url.path)'"
193 }
194 }
195 }
196}