@h1r-ai/croche-react-native 0.0.0-stage → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +475 -2
- package/THIRD-PARTY-NOTICES +5824 -0
- package/android/build.gradle +47 -0
- package/android/src/main/AndroidManifest.xml +8 -0
- package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
- package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
- package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
- package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
- package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
- package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
- package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
- package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
- package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
- package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
- package/croche-react-native.podspec +28 -0
- package/ios/CrocheRuntimeBridge.swift +986 -0
- package/ios/RNCrocheRuntime.mm +221 -0
- package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
- package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
- package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
- package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
- package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
- package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
- package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
- package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
- package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
- package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
- package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
- package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
- package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
- package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
- package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
- package/package.json +40 -4
- package/scripts/vendor-native.sh +56 -0
- package/src/NativeCrocheRuntime.ts +162 -0
- package/src/index.ts +660 -0
- package/src/project-types.ts +35 -0
- package/src/project.ts +426 -0
- package/src/protocol.ts +28 -0
- package/src/types.ts +9 -0
|
@@ -0,0 +1,345 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(Glibc)
|
|
3
|
+
import Glibc
|
|
4
|
+
#else
|
|
5
|
+
import Darwin
|
|
6
|
+
#endif
|
|
7
|
+
|
|
8
|
+
/// acquire must provide exclusive ownership until release. save must atomically replace
|
|
9
|
+
/// the whole JSON snapshot or throw; it must never be interrupted by cancellation.
|
|
10
|
+
public protocol RuntimeStorage: Sendable {
|
|
11
|
+
func acquire() throws
|
|
12
|
+
func load() throws -> JSON
|
|
13
|
+
func save(_ state: JSON) throws
|
|
14
|
+
func release()
|
|
15
|
+
/// Deletes the snapshot for real; absence succeeds. Required, with no tombstone default.
|
|
16
|
+
func remove() throws
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// A RuntimeStorage that also keeps named entries beside the snapshot, such as `held`: the sends
|
|
20
|
+
/// waiting behind a running turn (F19). Each entry is replaced atomically and independently of the
|
|
21
|
+
/// snapshot, under the same ownership. `load(entry:)` returns `.null` for an entry never saved.
|
|
22
|
+
/// A storage without entries still works; the Runtime then cannot keep sends that arrive while a
|
|
23
|
+
/// turn runs, and refuses them (`storage_error`) rather than overwrite the snapshot.
|
|
24
|
+
public protocol KeyedRuntimeStorage: RuntimeStorage {
|
|
25
|
+
func load(entry: String) throws -> JSON
|
|
26
|
+
func save(entry: String, _ value: JSON) throws
|
|
27
|
+
/// Deletes an entry for real; absence succeeds.
|
|
28
|
+
func remove(entry: String) throws
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/// A RuntimeStorage that also keeps the turn archive (F20.6): every finished turn in full, as
|
|
32
|
+
/// JSON lines in entries named `archive<NNNN>` (100 turns each) beside the snapshot. Opt-in and
|
|
33
|
+
/// separate from KeyedRuntimeStorage: a storage without it keeps no archive, typed
|
|
34
|
+
/// (`archive_unavailable`), and everything else works. The Runtime keeps the rules (segments,
|
|
35
|
+
/// the byte bound, the last record per turn); the storage keeps lines:
|
|
36
|
+
/// - `appendLine` writes a newline first when the entry does not end with one, and is durable
|
|
37
|
+
/// when it returns;
|
|
38
|
+
/// - `readLines` returns complete lines only: a torn last line (a crash mid-append) is not one;
|
|
39
|
+
/// - `replaceLines` is atomic: after a crash the entry holds every old line or every new one,
|
|
40
|
+
/// never a mix and never none; `[]` deletes the entry;
|
|
41
|
+
/// - `remove` deletes for real; an absent entry is not an error;
|
|
42
|
+
/// - `entries` lists the entries whose names start with `prefix`, with their sizes in bytes.
|
|
43
|
+
public protocol ArchiveRuntimeStorage: RuntimeStorage {
|
|
44
|
+
func appendLine(entry: String, _ line: String) throws
|
|
45
|
+
func readLines(entry: String) throws -> [String]
|
|
46
|
+
func replaceLines(entry: String, _ lines: [String]) throws
|
|
47
|
+
func remove(entry: String) throws
|
|
48
|
+
func entries(prefix: String) throws -> [String: Int]
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// Private local file storage with a process-safe advisory lock and atomic replacement.
|
|
52
|
+
/// Use an application-private directory; snapshots include runtime credentials. Entries are
|
|
53
|
+
/// sidecar files beside the snapshot (`<file>.held`), each replaced atomically. The turn archive
|
|
54
|
+
/// is sidecars too (`<file>.archive0001`, JSON lines), under the same lock; a segment is rewritten
|
|
55
|
+
/// to `<file>.archive0001.tmp-<nonce>` and renamed over it, and stale temporaries are deleted when
|
|
56
|
+
/// the storage is acquired.
|
|
57
|
+
public final class FileRuntimeStorage: KeyedRuntimeStorage, ArchiveRuntimeStorage, @unchecked Sendable {
|
|
58
|
+
private let url: URL
|
|
59
|
+
private let mutex = NSLock()
|
|
60
|
+
private var descriptor: Int32 = -1
|
|
61
|
+
/// Runs after a segment's temporary is complete and before the rename (tests inject a crash).
|
|
62
|
+
var beforeCommit: ((URL) throws -> Void)?
|
|
63
|
+
public init(url: URL) { self.url = url }
|
|
64
|
+
public func acquire() throws {
|
|
65
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
66
|
+
guard descriptor == -1 else { throw CrocheError("store_busy", "Storage is already owned") }
|
|
67
|
+
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
68
|
+
let fd = open(url.path + ".lock", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
|
|
69
|
+
guard fd >= 0 else { throw CrocheError("storage_error", "Could not open storage lock") }
|
|
70
|
+
guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
|
|
71
|
+
_ = close(fd); throw CrocheError("store_busy", "Storage is already owned")
|
|
72
|
+
}
|
|
73
|
+
descriptor = fd
|
|
74
|
+
removeStaleTemporaries()
|
|
75
|
+
}
|
|
76
|
+
public func load() throws -> JSON {
|
|
77
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
78
|
+
guard descriptor >= 0 else { throw CrocheError("storage_error", "Storage is not owned") }
|
|
79
|
+
if !FileManager.default.fileExists(atPath: url.path) { return .null }
|
|
80
|
+
let saved = try JSON(data: Data(contentsOf: url))
|
|
81
|
+
guard saved.object != nil else { throw CrocheError("storage_error", "Existing Runtime snapshot must be an object") }
|
|
82
|
+
return saved
|
|
83
|
+
}
|
|
84
|
+
public func save(_ state: JSON) throws {
|
|
85
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
86
|
+
guard descriptor >= 0 else { throw CrocheError("storage_error", "Storage is not owned") }
|
|
87
|
+
try state.encoded().write(to: url, options: .atomic)
|
|
88
|
+
_ = chmod(url.path, S_IRUSR | S_IWUSR)
|
|
89
|
+
}
|
|
90
|
+
public func load(entry: String) throws -> JSON {
|
|
91
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
92
|
+
let file = try sidecar(entry)
|
|
93
|
+
if !FileManager.default.fileExists(atPath: file.path) { return .null }
|
|
94
|
+
return try JSON(data: Data(contentsOf: file))
|
|
95
|
+
}
|
|
96
|
+
public func save(entry: String, _ value: JSON) throws {
|
|
97
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
98
|
+
let file = try sidecar(entry)
|
|
99
|
+
try value.encoded().write(to: file, options: .atomic)
|
|
100
|
+
_ = chmod(file.path, S_IRUSR | S_IWUSR)
|
|
101
|
+
}
|
|
102
|
+
private func sidecar(_ entry: String) throws -> URL {
|
|
103
|
+
guard descriptor >= 0 else { throw CrocheError("storage_error", "Storage is not owned") }
|
|
104
|
+
guard !entry.isEmpty, entry.allSatisfy({ $0.isASCII && ($0.isLowercase || $0.isNumber) }) else { throw CrocheError("storage_error", "Invalid storage entry") }
|
|
105
|
+
return URL(fileURLWithPath: url.path + "." + entry)
|
|
106
|
+
}
|
|
107
|
+
// MARK: The turn archive (F20.6)
|
|
108
|
+
public func appendLine(entry: String, _ line: String) throws {
|
|
109
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
110
|
+
let file = try segment(entry)
|
|
111
|
+
guard !line.contains("\n") else { throw CrocheError("storage_error", "An archive line holds no newline") }
|
|
112
|
+
let fd = open(file.path, O_RDWR | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR)
|
|
113
|
+
guard fd >= 0 else { throw CrocheError("storage_error", "Could not open the archive") }
|
|
114
|
+
defer { _ = close(fd) }
|
|
115
|
+
var info = stat()
|
|
116
|
+
guard fstat(fd, &info) == 0 else { throw CrocheError("storage_error", "Could not read the archive") }
|
|
117
|
+
var bytes = [UInt8]()
|
|
118
|
+
if info.st_size > 0 {
|
|
119
|
+
var last: UInt8 = 0
|
|
120
|
+
guard pread(fd, &last, 1, off_t(info.st_size - 1)) == 1 else { throw CrocheError("storage_error", "Could not read the archive") }
|
|
121
|
+
if last != 0x0a { bytes.append(0x0a) } // a torn line never swallows this record
|
|
122
|
+
}
|
|
123
|
+
bytes += Array(line.utf8); bytes.append(0x0a)
|
|
124
|
+
try Self.writeAll(fd, bytes)
|
|
125
|
+
guard fsync(fd) == 0 else { throw CrocheError("storage_error", "Could not sync the archive") }
|
|
126
|
+
}
|
|
127
|
+
public func readLines(entry: String) throws -> [String] {
|
|
128
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
129
|
+
let file = try segment(entry)
|
|
130
|
+
guard FileManager.default.fileExists(atPath: file.path) else { return [] }
|
|
131
|
+
var lines = String(decoding: try Data(contentsOf: file), as: UTF8.self)
|
|
132
|
+
.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)
|
|
133
|
+
lines.removeLast() // the piece after the last newline: a torn line, or "" when whole
|
|
134
|
+
return lines.filter { !$0.isEmpty }
|
|
135
|
+
}
|
|
136
|
+
public func replaceLines(entry: String, _ lines: [String]) throws {
|
|
137
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
138
|
+
let file = try segment(entry)
|
|
139
|
+
guard !lines.isEmpty else { return try unlinkIfPresent(file) }
|
|
140
|
+
guard !lines.contains(where: { $0.contains("\n") }) else { throw CrocheError("storage_error", "An archive line holds no newline") }
|
|
141
|
+
// '.' and '-' are outside the entry rule: a temporary is never an entry, `held` or `lock`.
|
|
142
|
+
let nonce = UUID().uuidString.lowercased()
|
|
143
|
+
let temporary = URL(fileURLWithPath: file.path + ".tmp-" + nonce)
|
|
144
|
+
let fd = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)
|
|
145
|
+
guard fd >= 0 else { throw CrocheError("storage_error", "Could not write the archive") }
|
|
146
|
+
do {
|
|
147
|
+
defer { _ = close(fd) }
|
|
148
|
+
try Self.writeAll(fd, Array(lines.map { $0 + "\n" }.joined().utf8))
|
|
149
|
+
guard fsync(fd) == 0 else { throw CrocheError("storage_error", "Could not sync the archive") }
|
|
150
|
+
} catch { _ = unlink(temporary.path); throw error }
|
|
151
|
+
do {
|
|
152
|
+
try beforeCommit?(temporary)
|
|
153
|
+
guard rename(temporary.path, file.path) == 0 else { throw CrocheError("storage_error", "Could not replace the archive") }
|
|
154
|
+
} catch { _ = unlink(temporary.path); throw error }
|
|
155
|
+
}
|
|
156
|
+
public func remove(entry: String) throws {
|
|
157
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
158
|
+
try unlinkIfPresent(try sidecar(entry))
|
|
159
|
+
}
|
|
160
|
+
public func entries(prefix: String) throws -> [String: Int] {
|
|
161
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
162
|
+
guard descriptor >= 0 else { throw CrocheError("storage_error", "Storage is not owned") }
|
|
163
|
+
var found: [String: Int] = [:]
|
|
164
|
+
for (name, path) in try siblings() {
|
|
165
|
+
guard Self.isEntry(name), name.hasPrefix(prefix) else { continue }
|
|
166
|
+
if let size = try? FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber { found[name] = size.intValue }
|
|
167
|
+
}
|
|
168
|
+
return found
|
|
169
|
+
}
|
|
170
|
+
/// Line entries are segments only: the archive's (`archive` and four digits) and the message
|
|
171
|
+
/// log's (`log` and six digits, S1). Never the snapshot's own sidecars (`held`) or its lock
|
|
172
|
+
/// file (`lock`).
|
|
173
|
+
private func segment(_ entry: String) throws -> URL {
|
|
174
|
+
guard Self.isSegment(entry) else { throw CrocheError("storage_error", "Invalid archive entry") }
|
|
175
|
+
return try sidecar(entry)
|
|
176
|
+
}
|
|
177
|
+
private static func isSegment(_ entry: Substring) -> Bool {
|
|
178
|
+
let digits = { (n: Int) in entry.dropFirst(n).allSatisfy { $0.isASCII && $0.isNumber } }
|
|
179
|
+
return (entry.count == 11 && entry.hasPrefix("archive") && digits(7))
|
|
180
|
+
|| (entry.count == 9 && entry.hasPrefix("log") && digits(3))
|
|
181
|
+
}
|
|
182
|
+
private static func isSegment(_ entry: String) -> Bool { isSegment(Substring(entry)) }
|
|
183
|
+
private static func isEntry(_ name: String) -> Bool {
|
|
184
|
+
!name.isEmpty && name.allSatisfy { $0.isASCII && ($0.isLowercase || $0.isNumber) }
|
|
185
|
+
}
|
|
186
|
+
/// The files beside the snapshot: `<file>.<suffix>`, as (suffix, path).
|
|
187
|
+
private func siblings() throws -> [(String, String)] {
|
|
188
|
+
let directory = url.deletingLastPathComponent().path, base = url.lastPathComponent + "."
|
|
189
|
+
guard let names = try? FileManager.default.contentsOfDirectory(atPath: directory) else { return [] }
|
|
190
|
+
return names.filter { $0.hasPrefix(base) }.map { (String($0.dropFirst(base.count)), directory + "/" + $0) }
|
|
191
|
+
}
|
|
192
|
+
/// Segment rewrites a crash interrupted (`archive<NNNN>.tmp-<nonce>`, `log<NNNNNN>.tmp-<nonce>`):
|
|
193
|
+
/// deleted by the owner.
|
|
194
|
+
private func removeStaleTemporaries() {
|
|
195
|
+
for (suffix, path) in (try? siblings()) ?? [] {
|
|
196
|
+
let parts = suffix.split(separator: ".", maxSplits: 1).map(String.init)
|
|
197
|
+
guard parts.count == 2, Self.isSegment(parts[0]), parts[1].hasPrefix("tmp-") else { continue }
|
|
198
|
+
_ = unlink(path)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
private func unlinkIfPresent(_ file: URL) throws {
|
|
202
|
+
if unlink(file.path) != 0 && errno != ENOENT { throw CrocheError("storage_error", "Could not delete the archive") }
|
|
203
|
+
}
|
|
204
|
+
private static func writeAll(_ fd: Int32, _ bytes: [UInt8]) throws {
|
|
205
|
+
var offset = 0
|
|
206
|
+
while offset < bytes.count {
|
|
207
|
+
let written = bytes[offset...].withUnsafeBytes { write(fd, $0.baseAddress, $0.count) }
|
|
208
|
+
guard written > 0 else { throw CrocheError("storage_error", "Could not write the archive") }
|
|
209
|
+
offset += written
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
public func remove() throws {
|
|
214
|
+
try mutex.withLock {
|
|
215
|
+
guard descriptor >= 0 else { throw CrocheError("storage_error", "Storage is not owned") }
|
|
216
|
+
try unlinkIfPresent(url)
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
public func release() {
|
|
221
|
+
mutex.lock(); defer { mutex.unlock() }
|
|
222
|
+
if descriptor >= 0 { _ = flock(descriptor, LOCK_UN); _ = close(descriptor); descriptor = -1 }
|
|
223
|
+
}
|
|
224
|
+
deinit { release() }
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// Project namespace, independent of every app-supplied RuntimeStorage. Core mints and
|
|
228
|
+
// validates the record; this host only owns its file, atomic replacement and flock.
|
|
229
|
+
final class ProjectRecordFiles: @unchecked Sendable {
|
|
230
|
+
private let directory: @Sendable () -> URL?
|
|
231
|
+
private let mutex = NSLock()
|
|
232
|
+
private var descriptors: [String: Int32] = [:]
|
|
233
|
+
// Internal host-test fences; configured before the host is handed to Core.
|
|
234
|
+
var afterRead: (@Sendable (String, String?) -> Void)?
|
|
235
|
+
var beforeLock: (@Sendable (String) -> Void)?
|
|
236
|
+
var afterWrite: (@Sendable (String) -> Void)?
|
|
237
|
+
init(directory: @escaping @Sendable () -> URL? = ProjectRecordFiles.defaultDirectory) { self.directory = directory }
|
|
238
|
+
static var hasPrivateStorage: Bool {
|
|
239
|
+
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(visionOS)
|
|
240
|
+
true
|
|
241
|
+
#else
|
|
242
|
+
false
|
|
243
|
+
#endif
|
|
244
|
+
}
|
|
245
|
+
// Policy seam lets host tests exercise a platform without a default on Apple too.
|
|
246
|
+
static func forOpen(projectDirectory: URL?, hasPrivateStorage: Bool = ProjectRecordFiles.hasPrivateStorage) throws -> ProjectRecordFiles {
|
|
247
|
+
if hasPrivateStorage {
|
|
248
|
+
guard projectDirectory == nil else {
|
|
249
|
+
throw CrocheError("invalid_configuration", "this platform keeps the project record in the app's private storage")
|
|
250
|
+
}
|
|
251
|
+
return ProjectRecordFiles()
|
|
252
|
+
}
|
|
253
|
+
guard let projectDirectory else {
|
|
254
|
+
throw CrocheError("storage_error", "This platform requires projectDirectory for the project record")
|
|
255
|
+
}
|
|
256
|
+
return ProjectRecordFiles(directory: { projectDirectory })
|
|
257
|
+
}
|
|
258
|
+
static func defaultDirectory() -> URL? {
|
|
259
|
+
#if os(iOS) || os(macOS) || os(tvOS) || os(watchOS) || os(visionOS)
|
|
260
|
+
return FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
|
261
|
+
#else
|
|
262
|
+
return nil
|
|
263
|
+
#endif
|
|
264
|
+
}
|
|
265
|
+
static func owns(_ key: String) -> Bool { key.hasPrefix("croche.project.") }
|
|
266
|
+
func file(_ key: String) throws -> URL {
|
|
267
|
+
let prefix = "croche.project.v1."
|
|
268
|
+
let hash = key.dropFirst(prefix.count)
|
|
269
|
+
guard key.hasPrefix(prefix), hash.count == 64, hash.allSatisfy({ $0.isASCII && ($0.isNumber || ("a"..."f").contains(String($0))) }) else {
|
|
270
|
+
throw CrocheError("storage_error", "Unsupported project record key")
|
|
271
|
+
}
|
|
272
|
+
guard let directory = directory() else {
|
|
273
|
+
throw CrocheError("storage_error", "Project record needs app-private storage or an explicit projectDirectory")
|
|
274
|
+
}
|
|
275
|
+
return directory.appendingPathComponent("croche.project.v1.\(hash).json")
|
|
276
|
+
}
|
|
277
|
+
private func io<T>(_ body: () throws -> T) throws -> T {
|
|
278
|
+
do { return try body() }
|
|
279
|
+
catch let error as CrocheError { throw error }
|
|
280
|
+
catch { throw CrocheError("storage_error", "Could not access the project record directory") }
|
|
281
|
+
}
|
|
282
|
+
func acquire(_ key: String) throws {
|
|
283
|
+
beforeLock?(key)
|
|
284
|
+
try io { try mutex.withLock {
|
|
285
|
+
guard descriptors[key] == nil else { throw CrocheError("store_busy", "Project record is already owned") }
|
|
286
|
+
let url = try file(key)
|
|
287
|
+
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
288
|
+
let fd = open(url.path + ".lock", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)
|
|
289
|
+
guard fd >= 0 else { throw CrocheError("storage_error", "Could not open project record lock") }
|
|
290
|
+
guard flock(fd, LOCK_EX | LOCK_NB) == 0 else {
|
|
291
|
+
_ = close(fd); throw CrocheError("store_busy", "Project record is already owned")
|
|
292
|
+
}
|
|
293
|
+
descriptors[key] = fd
|
|
294
|
+
} }
|
|
295
|
+
}
|
|
296
|
+
private func ownedFile(_ key: String) throws -> URL {
|
|
297
|
+
guard descriptors[key] != nil else { throw CrocheError("storage_error", "Project record is not owned") }
|
|
298
|
+
return try file(key)
|
|
299
|
+
}
|
|
300
|
+
func read(_ key: String) throws -> String? {
|
|
301
|
+
let value = try io { try mutex.withLock {
|
|
302
|
+
let url = try ownedFile(key)
|
|
303
|
+
guard FileManager.default.fileExists(atPath: url.path) else { return nil as String? }
|
|
304
|
+
return try String(contentsOf: url, encoding: .utf8)
|
|
305
|
+
} }
|
|
306
|
+
afterRead?(key, value)
|
|
307
|
+
return value
|
|
308
|
+
}
|
|
309
|
+
func write(_ key: String, _ value: String) throws {
|
|
310
|
+
try io { try mutex.withLock {
|
|
311
|
+
let url = try ownedFile(key)
|
|
312
|
+
let temporary = URL(fileURLWithPath: url.path + ".tmp-" + UUID().uuidString)
|
|
313
|
+
let fd = open(temporary.path, O_CREAT | O_EXCL | O_WRONLY, S_IRUSR | S_IWUSR)
|
|
314
|
+
guard fd >= 0 else { throw CrocheError("storage_error", "Could not write project record") }
|
|
315
|
+
defer { _ = close(fd); _ = unlink(temporary.path) }
|
|
316
|
+
let bytes = Array(value.utf8)
|
|
317
|
+
var offset = 0
|
|
318
|
+
while offset < bytes.count {
|
|
319
|
+
let count = bytes[offset...].withUnsafeBytes {
|
|
320
|
+
#if canImport(Glibc)
|
|
321
|
+
return Glibc.write(fd, $0.baseAddress, $0.count)
|
|
322
|
+
#else
|
|
323
|
+
return Darwin.write(fd, $0.baseAddress, $0.count)
|
|
324
|
+
#endif
|
|
325
|
+
}
|
|
326
|
+
if count < 0 && errno == EINTR { continue }
|
|
327
|
+
guard count > 0 else { throw CrocheError("storage_error", "Could not write project record") }
|
|
328
|
+
offset += count
|
|
329
|
+
}
|
|
330
|
+
guard fsync(fd) == 0, rename(temporary.path, url.path) == 0 else {
|
|
331
|
+
throw CrocheError("storage_error", "Could not commit project record")
|
|
332
|
+
}
|
|
333
|
+
} }
|
|
334
|
+
afterWrite?(key)
|
|
335
|
+
}
|
|
336
|
+
func release(_ key: String) {
|
|
337
|
+
mutex.withLock {
|
|
338
|
+
if let fd = descriptors.removeValue(forKey: key) { _ = flock(fd, LOCK_UN); _ = close(fd) }
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
var held: Bool { mutex.withLock { !descriptors.isEmpty } }
|
|
342
|
+
deinit {
|
|
343
|
+
for fd in descriptors.values { _ = flock(fd, LOCK_UN); _ = close(fd) }
|
|
344
|
+
}
|
|
345
|
+
}
|