instant_record 0.1.0 → 0.3.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +58 -0
- data/README.md +267 -61
- data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
- data/app/controllers/instant_record/events_controller.rb +58 -6
- data/app/controllers/instant_record/files_controller.rb +116 -0
- data/app/controllers/instant_record/mutations_controller.rb +84 -5
- data/app/controllers/instant_record/native_screens_controller.rb +60 -0
- data/app/controllers/instant_record/records_controller.rb +86 -8
- data/app/controllers/instant_record/shells_controller.rb +64 -0
- data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
- data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
- data/app/jobs/instant_record/shell_build_job.rb +16 -0
- data/app/models/instant_record/change.rb +36 -3
- data/app/models/instant_record/mutation_applier.rb +633 -50
- data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
- data/compiled/README.md +272 -0
- data/compiled/pipeline/browser_migrations.rb +18 -0
- data/compiled/pipeline/build.rb +13 -0
- data/compiled/pipeline/build_native.rb +14 -0
- data/compiled/pipeline/native/host.c +78 -0
- data/compiled/pipeline/native/instant_record_native.h +57 -0
- data/compiled/pipeline/native_shim.c +149 -0
- data/compiled/pipeline/reactor_shim.c +66 -0
- data/compiled/pipeline/sqlite/rh_shim.c +5 -0
- data/compiled/pipeline/sqlite_release.rb +43 -0
- data/compiled/toolchain.env.example +22 -0
- data/compiled/web/index.html +20 -0
- data/compiled/web/package-lock.json +884 -0
- data/compiled/web/package.json +17 -0
- data/compiled/web/src/app-host-core.js +556 -0
- data/compiled/web/src/app-host.js +16 -0
- data/compiled/web/src/branch-manager.js +140 -0
- data/compiled/web/src/branch-preview.js +397 -0
- data/compiled/web/src/changes.js +191 -0
- data/compiled/web/src/faults.js +172 -0
- data/compiled/web/src/flight-recorder.js +347 -0
- data/compiled/web/src/history-fill.js +68 -0
- data/compiled/web/src/http-headers.js +100 -0
- data/compiled/web/src/leader-election.js +705 -0
- data/compiled/web/src/main.js +608 -0
- data/compiled/web/src/manifest.js +112 -0
- data/compiled/web/src/opfs-wasi-core.js +109 -0
- data/compiled/web/src/opfs-wasi-file.js +8 -0
- data/compiled/web/src/reactor-runtime.js +1692 -0
- data/compiled/web/src/redactor.js +518 -0
- data/compiled/web/src/release-updates.js +48 -0
- data/compiled/web/src/replay.js +338 -0
- data/compiled/web/src/schema-recovery.js +204 -0
- data/compiled/web/src/server-request.js +68 -0
- data/compiled/web/src/sha256.js +98 -0
- data/compiled/web/src/shell.js +52 -0
- data/compiled/web/src/snapshot-store.js +38 -0
- data/compiled/web/src/sqlite-redactor.js +111 -0
- data/compiled/web/src/storage-backend.js +159 -0
- data/compiled/web/src/stream-leader.js +675 -0
- data/compiled/web/src/sync-context.js +91 -0
- data/compiled/web/src/sync-drain.js +104 -0
- data/compiled/web/src/sync-schedule.js +9 -0
- data/compiled/web/src/wasi-minimal.js +275 -0
- data/compiled/web/src/worker.js +39 -0
- data/compiled/web/vite.config.js +27 -0
- data/config/routes.rb +25 -0
- data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
- data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
- data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
- data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
- data/exe/instant_record_mcp +6 -0
- data/frontend/LiveList.js +67 -0
- data/frontend/chord.js +79 -0
- data/frontend/file.js +65 -0
- data/frontend/files.js +738 -0
- data/frontend/focus.js +10 -0
- data/frontend/held.js +192 -0
- data/frontend/http.js +76 -0
- data/frontend/index.js +53 -0
- data/frontend/keyboard.js +56 -0
- data/frontend/live.js +298 -0
- data/frontend/notices.js +118 -0
- data/frontend/package.json +15 -0
- data/frontend/range.js +10 -0
- data/frontend/selection.js +47 -0
- data/frontend/shortcuts.js +25 -0
- data/frontend/sync-notices.js +130 -0
- data/frontend/undo.js +48 -0
- data/frontend/window.js +181 -0
- data/lib/generators/instant_record/install/install_generator.rb +18 -30
- data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
- data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
- data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
- data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
- data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
- data/lib/instant_record/branch/sqlite_store.rb +142 -0
- data/lib/instant_record/branch.rb +388 -0
- data/lib/instant_record/client/notifier.rb +8 -12
- data/lib/instant_record/client/rebaser.rb +565 -0
- data/lib/instant_record/client/transport.rb +64 -42
- data/lib/instant_record/client.rb +1600 -169
- data/lib/instant_record/compiled_site.rb +85 -0
- data/lib/instant_record/compiler/app_stage.rb +212 -0
- data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
- data/lib/instant_record/compiler/browser_migrations.rb +161 -0
- data/lib/instant_record/compiler/entry_builder.rb +832 -0
- data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
- data/lib/instant_record/compiler/gem_vendor.rb +194 -0
- data/lib/instant_record/compiler/host_adapters.rb +506 -0
- data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
- data/lib/instant_record/compiler/manifest.rb +178 -0
- data/lib/instant_record/compiler/native_build.rb +586 -0
- data/lib/instant_record/compiler/native_contracts.rb +338 -0
- data/lib/instant_record/compiler/path_scrubber.rb +31 -0
- data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
- data/lib/instant_record/compiler/route_analyzer.rb +623 -0
- data/lib/instant_record/compiler/runner.rb +42 -0
- data/lib/instant_record/compiler/schema_lock.rb +606 -0
- data/lib/instant_record/compiler/source_pages.rb +77 -0
- data/lib/instant_record/compiler/static_linter.rb +770 -0
- data/lib/instant_record/compiler/swift_codegen.rb +341 -0
- data/lib/instant_record/compiler/toolchain.rb +219 -0
- data/lib/instant_record/compiler/wasm_build.rb +704 -0
- data/lib/instant_record/compiler/wasm_tree.rb +518 -0
- data/lib/instant_record/compiler.rb +277 -0
- data/lib/instant_record/configuration.rb +104 -0
- data/lib/instant_record/engine.rb +68 -18
- data/lib/instant_record/file_store.rb +162 -0
- data/lib/instant_record/files.rb +92 -0
- data/lib/instant_record/hlc.rb +387 -0
- data/lib/instant_record/host.rb +66 -0
- data/lib/instant_record/inertia/renderer.rb +52 -0
- data/lib/instant_record/inertia.rb +222 -0
- data/lib/instant_record/mcp/cli.rb +319 -0
- data/lib/instant_record/mcp/host_process.rb +229 -0
- data/lib/instant_record/mcp/http_exchange.rb +233 -0
- data/lib/instant_record/mcp/replica.rb +556 -0
- data/lib/instant_record/mcp/runtime.rb +406 -0
- data/lib/instant_record/mcp/server.rb +429 -0
- data/lib/instant_record/mcp.rb +47 -0
- data/lib/instant_record/native/contract.rb +367 -0
- data/lib/instant_record/native/node.rb +125 -0
- data/lib/instant_record/native/screen.rb +366 -0
- data/lib/instant_record/native/xcode_project.rb +344 -0
- data/lib/instant_record/native.rb +41 -0
- data/lib/instant_record/outbox_mutation.rb +81 -9
- data/lib/instant_record/outbox_upcaster.rb +161 -0
- data/lib/instant_record/read_tracker.rb +610 -0
- data/lib/instant_record/routing.rb +33 -0
- data/lib/instant_record/runtime_scoped.rb +4 -0
- data/lib/instant_record/shell.rb +486 -0
- data/lib/instant_record/sync_actions.rb +800 -0
- data/lib/instant_record/sync_metadata.rb +17 -2
- data/lib/instant_record/sync_notice.rb +234 -0
- data/lib/instant_record/sync_partition.rb +63 -0
- data/lib/instant_record/sync_scope.rb +300 -0
- data/lib/instant_record/sync_shape.rb +102 -0
- data/lib/instant_record/sync_window.rb +92 -15
- data/lib/instant_record/syncable.rb +313 -17
- data/lib/instant_record/testing/authoritative_server.rb +547 -0
- data/lib/instant_record/testing/chaos_simulator.rb +429 -0
- data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
- data/lib/instant_record/testing/fault_network.rb +140 -0
- data/lib/instant_record/testing/parity_suite.rb +435 -0
- data/lib/instant_record/testing/runtimes/base.rb +184 -0
- data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
- data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
- data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
- data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
- data/lib/instant_record/testing.rb +333 -0
- data/lib/instant_record/trace/redactor.rb +278 -0
- data/lib/instant_record/trace/replayer.rb +126 -0
- data/lib/instant_record/trace/schema_extractor.rb +37 -0
- data/lib/instant_record/trace.rb +22 -0
- data/lib/instant_record/version.rb +1 -1
- data/lib/instant_record.rb +107 -37
- data/lib/tasks/instant_record.rake +299 -47
- data/native/ios/InstantRecordNative/Package.swift +12 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
- data/native/ios/README.md +341 -0
- data/sig/instant_record/inertia.rbs +47 -0
- data/sig/instant_record/native.rbs +38 -0
- metadata +194 -18
- data/lib/generators/instant_record/install/templates/database.js +0 -32
- data/lib/generators/instant_record/install/templates/index.html +0 -69
- data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
- data/lib/instant_record/local_schema.rb +0 -75
- data/lib/instant_record/pglite_compat.rb +0 -40
|
@@ -0,0 +1,1048 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// Errors thrown by `FileStore` when attaching, reading, downloading, or syncing
|
|
4
|
+
/// a `sync_file` record's bytes.
|
|
5
|
+
public enum FileStoreError: Error, Equatable, LocalizedError {
|
|
6
|
+
case emptyFile
|
|
7
|
+
case alreadyAttached(type: String, id: String)
|
|
8
|
+
case invalidChunkSize(Int)
|
|
9
|
+
case fileMissing(type: String, id: String)
|
|
10
|
+
case noRoom(needed: Int64)
|
|
11
|
+
case httpError(status: Int, message: String?)
|
|
12
|
+
case unexpectedPieceSize(expected: Int, actual: Int)
|
|
13
|
+
case uploadStalled
|
|
14
|
+
case invalidURL
|
|
15
|
+
|
|
16
|
+
public var errorDescription: String? {
|
|
17
|
+
switch self {
|
|
18
|
+
case .emptyFile:
|
|
19
|
+
return "A file needs bytes"
|
|
20
|
+
case let .alreadyAttached(type, id):
|
|
21
|
+
return "\(type) \(id) already has a file. A new file is a new record."
|
|
22
|
+
case let .invalidChunkSize(size):
|
|
23
|
+
return "chunkSize must be a positive integer, got \(size)"
|
|
24
|
+
case let .fileMissing(type, id):
|
|
25
|
+
return "\(type) \(id) has no file on the server"
|
|
26
|
+
case let .noRoom(needed):
|
|
27
|
+
return "No room to keep \(needed) bytes"
|
|
28
|
+
case let .httpError(status, message):
|
|
29
|
+
return message ?? "The server answered \(status)"
|
|
30
|
+
case let .unexpectedPieceSize(expected, actual):
|
|
31
|
+
return "A piece arrived the wrong size (expected \(expected), got \(actual))"
|
|
32
|
+
case .uploadStalled:
|
|
33
|
+
return "The upload is not moving"
|
|
34
|
+
case .invalidURL:
|
|
35
|
+
return "Could not build the file endpoint URL"
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/// Summary of what is known locally about a record's file.
|
|
41
|
+
public struct FileMetadata: Equatable, Sendable {
|
|
42
|
+
public let type: String
|
|
43
|
+
public let id: String
|
|
44
|
+
public let name: String
|
|
45
|
+
public let contentType: String
|
|
46
|
+
public let size: Int64
|
|
47
|
+
public let local: Bool
|
|
48
|
+
public let uploaded: Bool
|
|
49
|
+
public let pinned: Bool
|
|
50
|
+
public let failed: String?
|
|
51
|
+
public let addedAt: Date
|
|
52
|
+
public let usedAt: Date
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/// Metadata returned when a file is attached locally, matching Active Storage's
|
|
56
|
+
/// blob attribute names for the form/mutation that creates the record.
|
|
57
|
+
public struct AttachedFile: Equatable, Sendable {
|
|
58
|
+
public let filename: String
|
|
59
|
+
public let contentType: String
|
|
60
|
+
public let byteSize: Int64
|
|
61
|
+
public let localURL: URL
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/// Local storage accounting for `FileStore`.
|
|
65
|
+
public struct StorageUsage: Equatable, Sendable {
|
|
66
|
+
public let files: Int
|
|
67
|
+
public let bytes: Int64
|
|
68
|
+
public let waiting: Int
|
|
69
|
+
public let waitingBytes: Int64
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/// Outcome of one upload sync pass.
|
|
73
|
+
public struct FileSyncResult: Equatable, Sendable {
|
|
74
|
+
public let sent: Int
|
|
75
|
+
public let waiting: Int
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// Byte progress during a chunked upload or download.
|
|
79
|
+
public struct TransferProgress: Equatable, Sendable {
|
|
80
|
+
public let transferred: Int64
|
|
81
|
+
public let size: Int64
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// Lifecycle events emitted by `FileStore`.
|
|
85
|
+
public enum FileEvent: Equatable, Sendable {
|
|
86
|
+
case added(type: String, id: String)
|
|
87
|
+
case progress(type: String, id: String, transferred: Int64, size: Int64)
|
|
88
|
+
case uploaded(type: String, id: String)
|
|
89
|
+
case failed(type: String, id: String, reason: String)
|
|
90
|
+
case fetched(type: String, id: String)
|
|
91
|
+
case evicted(type: String, id: String)
|
|
92
|
+
case removed(type: String, id: String)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/// Minimal async HTTP interface used by `FileStore`, allowing tests to stub the
|
|
96
|
+
/// server without opening real sockets.
|
|
97
|
+
public protocol FileHTTPClient: Sendable {
|
|
98
|
+
func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/// Default `FileHTTPClient` backed by `URLSession` and an InstantRecord
|
|
102
|
+
/// `Transport` so authentication headers and request preparation apply to file
|
|
103
|
+
/// transfers too.
|
|
104
|
+
public final class TransportFileHTTPClient: FileHTTPClient, @unchecked Sendable {
|
|
105
|
+
private let session: URLSession
|
|
106
|
+
private let transport: Transport
|
|
107
|
+
|
|
108
|
+
public init(transport: Transport = Transport(), timeout: TimeInterval = 120) {
|
|
109
|
+
self.transport = transport
|
|
110
|
+
let configuration = URLSessionConfiguration.ephemeral
|
|
111
|
+
configuration.timeoutIntervalForRequest = timeout
|
|
112
|
+
configuration.waitsForConnectivity = false
|
|
113
|
+
self.session = URLSession(configuration: configuration)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
|
|
117
|
+
var prepared = request
|
|
118
|
+
transport.prepareRequest(&prepared)
|
|
119
|
+
let (data, response) = try await session.data(for: prepared)
|
|
120
|
+
guard let http = response as? HTTPURLResponse else {
|
|
121
|
+
throw URLError(.badServerResponse)
|
|
122
|
+
}
|
|
123
|
+
return (data, http)
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/// Disk-backed chunked file store for `sync_file` models on iOS and macOS.
|
|
128
|
+
///
|
|
129
|
+
/// Mirrors `frontend/files.js` and speaks directly to `InstantRecord::FilesController`:
|
|
130
|
+
/// - `attach` writes a record's bytes locally first (offline-safe) and queues
|
|
131
|
+
/// them for background chunked upload via `PUT <endpoint>/files/:type/:id`.
|
|
132
|
+
/// - `sync` uploads waiting files in proxy-safe chunks (512 KiB by default,
|
|
133
|
+
/// negotiated down if the server advertises a smaller `chunk_size`), resuming
|
|
134
|
+
/// interrupted transfers via `GET .../upload`.
|
|
135
|
+
/// - `open` / `download` reads locally when cached, or fetches via `Range`
|
|
136
|
+
/// requests and keeps partial progress across interruptions.
|
|
137
|
+
/// - Past `budget`, already-uploaded and unpinned files are evicted least
|
|
138
|
+
/// recently used first; unuploaded and pinned files are never dropped.
|
|
139
|
+
public actor FileStore {
|
|
140
|
+
/// Default chunk size (512 KiB), safely below common 1-2 MB reverse-proxy
|
|
141
|
+
/// request body limits.
|
|
142
|
+
public static let defaultChunkSize = 512 * 1024
|
|
143
|
+
public static let defaultTouchInterval: TimeInterval = 60
|
|
144
|
+
|
|
145
|
+
private static let rootFolderName = "instant-record-files"
|
|
146
|
+
private static let metaFileName = "meta.json"
|
|
147
|
+
private static let contentFileName = "content"
|
|
148
|
+
private static let partialFileName = "partial"
|
|
149
|
+
|
|
150
|
+
public nonisolated let root: URL
|
|
151
|
+
public nonisolated let endpoint: String
|
|
152
|
+
public nonisolated let scope: String?
|
|
153
|
+
public nonisolated let chunkSize: Int
|
|
154
|
+
public nonisolated let budget: Int64?
|
|
155
|
+
|
|
156
|
+
private let client: FileHTTPClient
|
|
157
|
+
private let autoSync: Bool
|
|
158
|
+
private let touchInterval: TimeInterval
|
|
159
|
+
private let now: @Sendable () -> Date
|
|
160
|
+
private let fileManager = FileManager.default
|
|
161
|
+
|
|
162
|
+
private var listeners: [UUID: @Sendable (FileEvent) -> Void] = [:]
|
|
163
|
+
private var downloads: [String: Task<URL, Error>] = [:]
|
|
164
|
+
private var syncTask: Task<FileSyncResult, Never>?
|
|
165
|
+
private var syncAgain = false
|
|
166
|
+
private var lockedKeys: Set<String> = []
|
|
167
|
+
private var lockWaiters: [String: [CheckedContinuation<Void, Never>]] = [:]
|
|
168
|
+
|
|
169
|
+
private struct StoredMeta: Codable {
|
|
170
|
+
var type: String
|
|
171
|
+
var id: String
|
|
172
|
+
var name: String
|
|
173
|
+
var contentType: String
|
|
174
|
+
var size: Int64
|
|
175
|
+
var piece: Int
|
|
176
|
+
var received: Int64
|
|
177
|
+
var upload: String?
|
|
178
|
+
var complete: Bool
|
|
179
|
+
var uploaded: Bool
|
|
180
|
+
var pinned: Bool
|
|
181
|
+
var failed: String?
|
|
182
|
+
var addedAt: TimeInterval
|
|
183
|
+
var usedAt: TimeInterval
|
|
184
|
+
|
|
185
|
+
func shown() -> FileMetadata {
|
|
186
|
+
FileMetadata(
|
|
187
|
+
type: type,
|
|
188
|
+
id: id,
|
|
189
|
+
name: name,
|
|
190
|
+
contentType: contentType,
|
|
191
|
+
size: size,
|
|
192
|
+
local: complete,
|
|
193
|
+
uploaded: uploaded,
|
|
194
|
+
pinned: pinned,
|
|
195
|
+
failed: failed,
|
|
196
|
+
addedAt: Date(timeIntervalSince1970: addedAt),
|
|
197
|
+
usedAt: Date(timeIntervalSince1970: usedAt)
|
|
198
|
+
)
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
private struct UploadStanding: Decodable {
|
|
203
|
+
let complete: Bool
|
|
204
|
+
let offset: Int64
|
|
205
|
+
let chunkSize: Int?
|
|
206
|
+
|
|
207
|
+
enum CodingKeys: String, CodingKey {
|
|
208
|
+
case complete, offset
|
|
209
|
+
case chunkSize = "chunk_size"
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
private struct ErrorPayload: Decodable {
|
|
214
|
+
let error: String?
|
|
215
|
+
let chunkSize: Int?
|
|
216
|
+
|
|
217
|
+
enum CodingKeys: String, CodingKey {
|
|
218
|
+
case error
|
|
219
|
+
case chunkSize = "chunk_size"
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
public init(
|
|
224
|
+
directory: URL,
|
|
225
|
+
endpoint: String,
|
|
226
|
+
scope: String? = nil,
|
|
227
|
+
name: String? = nil,
|
|
228
|
+
chunkSize: Int = FileStore.defaultChunkSize,
|
|
229
|
+
budget: Int64? = nil,
|
|
230
|
+
autoSync: Bool = false,
|
|
231
|
+
transport: Transport = Transport(),
|
|
232
|
+
client: FileHTTPClient? = nil,
|
|
233
|
+
touchInterval: TimeInterval = FileStore.defaultTouchInterval,
|
|
234
|
+
now: @escaping @Sendable () -> Date = { Date() }
|
|
235
|
+
) throws {
|
|
236
|
+
guard chunkSize > 0 else { throw FileStoreError.invalidChunkSize(chunkSize) }
|
|
237
|
+
var base = directory.appendingPathComponent(Self.rootFolderName, isDirectory: true)
|
|
238
|
+
if let name, !name.isEmpty {
|
|
239
|
+
base = base.appendingPathComponent("name-\(Self.safe(name))", isDirectory: true)
|
|
240
|
+
}
|
|
241
|
+
self.root = base
|
|
242
|
+
self.endpoint = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint
|
|
243
|
+
self.scope = scope?.isEmpty == true ? nil : scope
|
|
244
|
+
self.chunkSize = chunkSize
|
|
245
|
+
self.budget = budget
|
|
246
|
+
self.autoSync = autoSync
|
|
247
|
+
self.client = client ?? TransportFileHTTPClient(transport: transport)
|
|
248
|
+
self.touchInterval = touchInterval
|
|
249
|
+
self.now = now
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// MARK: - Writing
|
|
253
|
+
|
|
254
|
+
/// Store `data` locally as the file for `(type, id)` and mark it waiting for upload.
|
|
255
|
+
@discardableResult
|
|
256
|
+
public func attach(
|
|
257
|
+
type: String,
|
|
258
|
+
id: String,
|
|
259
|
+
data: Data,
|
|
260
|
+
filename: String = "",
|
|
261
|
+
contentType: String = "application/octet-stream",
|
|
262
|
+
pinned: Bool = false
|
|
263
|
+
) async throws -> AttachedFile {
|
|
264
|
+
guard !data.isEmpty else { throw FileStoreError.emptyFile }
|
|
265
|
+
let size = Int64(data.count)
|
|
266
|
+
return try await attachStream(
|
|
267
|
+
type: type,
|
|
268
|
+
id: id,
|
|
269
|
+
size: size,
|
|
270
|
+
filename: filename,
|
|
271
|
+
contentType: contentType,
|
|
272
|
+
pinned: pinned
|
|
273
|
+
) { partialURL in
|
|
274
|
+
try data.write(to: partialURL, options: .atomic)
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/// Stream an existing local file URL into the store in chunk-sized reads so
|
|
279
|
+
/// large files are never buffered whole in memory.
|
|
280
|
+
@discardableResult
|
|
281
|
+
public func attach(
|
|
282
|
+
type: String,
|
|
283
|
+
id: String,
|
|
284
|
+
fileURL sourceURL: URL,
|
|
285
|
+
filename: String? = nil,
|
|
286
|
+
contentType: String = "application/octet-stream",
|
|
287
|
+
pinned: Bool = false
|
|
288
|
+
) async throws -> AttachedFile {
|
|
289
|
+
let attributes = try fileManager.attributesOfItem(atPath: sourceURL.path)
|
|
290
|
+
let size = (attributes[.size] as? NSNumber)?.int64Value ?? 0
|
|
291
|
+
guard size > 0 else { throw FileStoreError.emptyFile }
|
|
292
|
+
let resolvedName = filename ?? sourceURL.lastPathComponent
|
|
293
|
+
let step = chunkSize
|
|
294
|
+
return try await attachStream(
|
|
295
|
+
type: type,
|
|
296
|
+
id: id,
|
|
297
|
+
size: size,
|
|
298
|
+
filename: resolvedName,
|
|
299
|
+
contentType: contentType,
|
|
300
|
+
pinned: pinned
|
|
301
|
+
) { partialURL in
|
|
302
|
+
fileManager.createFile(atPath: partialURL.path, contents: nil)
|
|
303
|
+
let reader = try FileHandle(forReadingFrom: sourceURL)
|
|
304
|
+
let writer = try FileHandle(forWritingTo: partialURL)
|
|
305
|
+
defer {
|
|
306
|
+
try? reader.close()
|
|
307
|
+
try? writer.close()
|
|
308
|
+
}
|
|
309
|
+
while true {
|
|
310
|
+
let chunk = try reader.read(upToCount: step) ?? Data()
|
|
311
|
+
if chunk.isEmpty { break }
|
|
312
|
+
try writer.write(contentsOf: chunk)
|
|
313
|
+
}
|
|
314
|
+
try writer.synchronize()
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
private func attachStream(
|
|
319
|
+
type: String,
|
|
320
|
+
id: String,
|
|
321
|
+
size: Int64,
|
|
322
|
+
filename: String,
|
|
323
|
+
contentType: String,
|
|
324
|
+
pinned: Bool,
|
|
325
|
+
writePartial: (URL) throws -> Void
|
|
326
|
+
) async throws -> AttachedFile {
|
|
327
|
+
let key = Self.recordKey(type, id)
|
|
328
|
+
let timestamp = now().timeIntervalSince1970
|
|
329
|
+
var meta = StoredMeta(
|
|
330
|
+
type: type,
|
|
331
|
+
id: id,
|
|
332
|
+
name: filename,
|
|
333
|
+
contentType: contentType,
|
|
334
|
+
size: size,
|
|
335
|
+
piece: chunkSize,
|
|
336
|
+
received: 0,
|
|
337
|
+
upload: Self.uploadToken(),
|
|
338
|
+
complete: false,
|
|
339
|
+
uploaded: false,
|
|
340
|
+
pinned: pinned,
|
|
341
|
+
failed: nil,
|
|
342
|
+
addedAt: timestamp,
|
|
343
|
+
usedAt: timestamp
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
let localURL = try await withRecordLock(key) { () async throws -> URL in
|
|
347
|
+
if readMeta(type: type, id: id) != nil {
|
|
348
|
+
throw FileStoreError.alreadyAttached(type: type, id: id)
|
|
349
|
+
}
|
|
350
|
+
try ensureRoom(for: meta, bytesToWrite: size)
|
|
351
|
+
do {
|
|
352
|
+
dropRecord(type: type, id: id)
|
|
353
|
+
let folder = try recordFolder(type: type, id: id, create: true)
|
|
354
|
+
try writeMeta(meta, in: folder)
|
|
355
|
+
let partialURL = folder.appendingPathComponent(Self.partialFileName)
|
|
356
|
+
let contentURL = folder.appendingPathComponent(Self.contentFileName)
|
|
357
|
+
try writePartial(partialURL)
|
|
358
|
+
if fileManager.fileExists(atPath: contentURL.path) {
|
|
359
|
+
try fileManager.removeItem(at: contentURL)
|
|
360
|
+
}
|
|
361
|
+
try fileManager.moveItem(at: partialURL, to: contentURL)
|
|
362
|
+
meta.received = size
|
|
363
|
+
meta.complete = true
|
|
364
|
+
try writeMeta(meta, in: folder)
|
|
365
|
+
return contentURL
|
|
366
|
+
} catch {
|
|
367
|
+
dropRecord(type: type, id: id)
|
|
368
|
+
throw error
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
emit(.added(type: type, id: id))
|
|
373
|
+
if autoSync {
|
|
374
|
+
Task { _ = await self.sync() }
|
|
375
|
+
}
|
|
376
|
+
return AttachedFile(
|
|
377
|
+
filename: meta.name,
|
|
378
|
+
contentType: meta.contentType,
|
|
379
|
+
byteSize: meta.size,
|
|
380
|
+
localURL: localURL
|
|
381
|
+
)
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// MARK: - Reading
|
|
385
|
+
|
|
386
|
+
/// Returns the local file URL if the complete file is cached on disk, else nil.
|
|
387
|
+
/// Never touches the network.
|
|
388
|
+
public func fileURL(forType type: String, id: String, touch: Bool = true) -> URL? {
|
|
389
|
+
guard var meta = readMeta(type: type, id: id), meta.complete else { return nil }
|
|
390
|
+
let folder = recordFolderURL(type: type, id: id)
|
|
391
|
+
let contentURL = folder.appendingPathComponent(Self.contentFileName)
|
|
392
|
+
guard fileManager.fileExists(atPath: contentURL.path) else { return nil }
|
|
393
|
+
if touch {
|
|
394
|
+
let timestamp = now().timeIntervalSince1970
|
|
395
|
+
if timestamp - meta.usedAt > touchInterval {
|
|
396
|
+
meta.usedAt = timestamp
|
|
397
|
+
try? writeMeta(meta, in: folder)
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
return contentURL
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/// Returns the file's bytes if cached locally, else nil. Never touches the network.
|
|
404
|
+
public func get(type: String, id: String, touch: Bool = true) throws -> Data? {
|
|
405
|
+
guard let url = fileURL(forType: type, id: id, touch: touch) else { return nil }
|
|
406
|
+
return try Data(contentsOf: url)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/// Returns the file's bytes from local cache, or fetches it from the server in
|
|
410
|
+
/// chunks and caches it. If the store's budget cannot accommodate caching the
|
|
411
|
+
/// file even after evicting droppable files, it still returns the bytes read
|
|
412
|
+
/// from the server without keeping them on disk.
|
|
413
|
+
public func open(
|
|
414
|
+
type: String,
|
|
415
|
+
id: String,
|
|
416
|
+
onProgress: (@Sendable (TransferProgress) -> Void)? = nil
|
|
417
|
+
) async throws -> Data {
|
|
418
|
+
if let local = try get(type: type, id: id) {
|
|
419
|
+
return local
|
|
420
|
+
}
|
|
421
|
+
do {
|
|
422
|
+
let url = try await download(type: type, id: id, onProgress: onProgress)
|
|
423
|
+
return try Data(contentsOf: url)
|
|
424
|
+
} catch FileStoreError.noRoom {
|
|
425
|
+
return try await fetchWholeUncached(type: type, id: id)
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/// Returns the local cached URL for `(type, id)`, downloading it in resumable
|
|
430
|
+
/// chunks from the server if not already cached. Concurrent callers for the
|
|
431
|
+
/// same record share a single download.
|
|
432
|
+
public func download(
|
|
433
|
+
type: String,
|
|
434
|
+
id: String,
|
|
435
|
+
onProgress: (@Sendable (TransferProgress) -> Void)? = nil
|
|
436
|
+
) async throws -> URL {
|
|
437
|
+
if let local = fileURL(forType: type, id: id) {
|
|
438
|
+
return local
|
|
439
|
+
}
|
|
440
|
+
let key = Self.recordKey(type, id)
|
|
441
|
+
if let existing = downloads[key] {
|
|
442
|
+
return try await existing.value
|
|
443
|
+
}
|
|
444
|
+
let task = Task<URL, Error> {
|
|
445
|
+
try await self.performDownload(type: type, id: id, onProgress: onProgress)
|
|
446
|
+
}
|
|
447
|
+
downloads[key] = task
|
|
448
|
+
defer { downloads.removeValue(forKey: key) }
|
|
449
|
+
return try await task.value
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// MARK: - Introspection
|
|
453
|
+
|
|
454
|
+
public func stat(type: String, id: String) -> FileMetadata? {
|
|
455
|
+
readMeta(type: type, id: id)?.shown()
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
public func list() -> [FileMetadata] {
|
|
459
|
+
allMetas().map { $0.shown() }
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
public func usage() -> StorageUsage {
|
|
463
|
+
let metas = allMetas()
|
|
464
|
+
let held = metas.filter(\.complete)
|
|
465
|
+
let waiting = held.filter { !$0.uploaded }
|
|
466
|
+
return StorageUsage(
|
|
467
|
+
files: held.count,
|
|
468
|
+
bytes: metas.reduce(0) { $0 + $1.size },
|
|
469
|
+
waiting: waiting.count,
|
|
470
|
+
waitingBytes: waiting.reduce(0) { $0 + $1.size }
|
|
471
|
+
)
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// MARK: - Keeping & Evicting
|
|
475
|
+
|
|
476
|
+
@discardableResult
|
|
477
|
+
public func pin(type: String, id: String) async throws -> Bool {
|
|
478
|
+
try await mark(type: type, id: id) { $0.pinned = true }
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
@discardableResult
|
|
482
|
+
public func unpin(type: String, id: String) async throws -> Bool {
|
|
483
|
+
try await mark(type: type, id: id) { $0.pinned = false }
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
public func remove(type: String, id: String) async {
|
|
487
|
+
let key = Self.recordKey(type, id)
|
|
488
|
+
await withRecordLock(key) {
|
|
489
|
+
dropRecord(type: type, id: id)
|
|
490
|
+
}
|
|
491
|
+
emit(.removed(type: type, id: id))
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
@discardableResult
|
|
495
|
+
public func prune(type: String, keepingIds: Set<String>) async -> Int {
|
|
496
|
+
let gone = allMetas().filter { $0.type == type && !keepingIds.contains($0.id) }
|
|
497
|
+
for meta in gone {
|
|
498
|
+
await remove(type: meta.type, id: meta.id)
|
|
499
|
+
}
|
|
500
|
+
return gone.count
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
@discardableResult
|
|
504
|
+
public func clear(type: String? = nil) async -> Int {
|
|
505
|
+
let gone = allMetas().filter { type == nil || $0.type == type }
|
|
506
|
+
for meta in gone {
|
|
507
|
+
await remove(type: meta.type, id: meta.id)
|
|
508
|
+
}
|
|
509
|
+
return gone.count
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/// Evict already-uploaded, unpinned files (incomplete downloads first, then
|
|
513
|
+
/// least recently used) until at least `bytes` are freed. Returns bytes freed.
|
|
514
|
+
@discardableResult
|
|
515
|
+
public func free(bytes: Int64) -> Int64 {
|
|
516
|
+
evict(bytes: bytes, keeping: nil)
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/// Remove torn partials left behind by an interrupted `attach`.
|
|
520
|
+
@discardableResult
|
|
521
|
+
public func tidy() -> Int {
|
|
522
|
+
let dead = allMetas(includeTorn: true).filter { !$0.complete && !$0.uploaded }
|
|
523
|
+
var removed = 0
|
|
524
|
+
for meta in dead {
|
|
525
|
+
let key = Self.recordKey(meta.type, meta.id)
|
|
526
|
+
guard tryLockRecord(key) else { continue }
|
|
527
|
+
defer { unlockRecord(key) }
|
|
528
|
+
if let current = readMeta(type: meta.type, id: meta.id, includeTorn: true),
|
|
529
|
+
!current.complete && !current.uploaded {
|
|
530
|
+
dropRecord(type: meta.type, id: meta.id)
|
|
531
|
+
removed += 1
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return removed
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// MARK: - Uploading
|
|
538
|
+
|
|
539
|
+
/// Upload all complete, non-failed files the server does not hold yet, oldest
|
|
540
|
+
/// first. Concurrent calls coalesce into one pass and loop again if called
|
|
541
|
+
/// mid-pass.
|
|
542
|
+
public func sync() async -> FileSyncResult {
|
|
543
|
+
if let existing = syncTask {
|
|
544
|
+
syncAgain = true
|
|
545
|
+
return await existing.value
|
|
546
|
+
}
|
|
547
|
+
let task = Task<FileSyncResult, Never> {
|
|
548
|
+
var totalSent = 0
|
|
549
|
+
var lastWaiting = 0
|
|
550
|
+
repeat {
|
|
551
|
+
self.syncAgain = false
|
|
552
|
+
let pass = await self.drain()
|
|
553
|
+
totalSent += pass.sent
|
|
554
|
+
lastWaiting = pass.waiting
|
|
555
|
+
} while self.syncAgain
|
|
556
|
+
return FileSyncResult(sent: totalSent, waiting: lastWaiting)
|
|
557
|
+
}
|
|
558
|
+
syncTask = task
|
|
559
|
+
let result = await task.value
|
|
560
|
+
syncTask = nil
|
|
561
|
+
return result
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// MARK: - Events & URLs
|
|
565
|
+
|
|
566
|
+
@discardableResult
|
|
567
|
+
public func subscribe(_ listener: @escaping @Sendable (FileEvent) -> Void) -> UUID {
|
|
568
|
+
let token = UUID()
|
|
569
|
+
listeners[token] = listener
|
|
570
|
+
return token
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
public func unsubscribe(_ token: UUID) {
|
|
574
|
+
listeners.removeValue(forKey: token)
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
public func serverURL(type: String, id: String, query: [(String, String)] = [], suffix: String = "") -> URL? {
|
|
578
|
+
let base = "\(endpoint)/files/\(Self.urlSegment(type))/\(Self.urlSegment(id))\(suffix)"
|
|
579
|
+
guard var components = URLComponents(string: base) else { return nil }
|
|
580
|
+
var items: [URLQueryItem] = []
|
|
581
|
+
if let scope, !scope.isEmpty {
|
|
582
|
+
items.append(URLQueryItem(name: "scope", value: scope))
|
|
583
|
+
}
|
|
584
|
+
for (name, value) in query {
|
|
585
|
+
items.append(URLQueryItem(name: name, value: value))
|
|
586
|
+
}
|
|
587
|
+
if !items.isEmpty {
|
|
588
|
+
components.queryItems = items
|
|
589
|
+
}
|
|
590
|
+
return components.url
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
// MARK: - Internal Transfer Logic
|
|
594
|
+
|
|
595
|
+
private func performDownload(
|
|
596
|
+
type: String,
|
|
597
|
+
id: String,
|
|
598
|
+
onProgress: (@Sendable (TransferProgress) -> Void)?
|
|
599
|
+
) async throws -> URL {
|
|
600
|
+
let key = Self.recordKey(type, id)
|
|
601
|
+
let localURL = try await withRecordLock(key) { () async throws -> URL in
|
|
602
|
+
if let existing = fileURL(forType: type, id: id) {
|
|
603
|
+
return existing
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
var meta: StoredMeta
|
|
607
|
+
if let existing = readMeta(type: type, id: id), existing.uploaded && !existing.complete {
|
|
608
|
+
meta = existing
|
|
609
|
+
} else {
|
|
610
|
+
guard let headURL = serverURL(type: type, id: id) else { throw FileStoreError.invalidURL }
|
|
611
|
+
var headRequest = URLRequest(url: headURL)
|
|
612
|
+
headRequest.httpMethod = "HEAD"
|
|
613
|
+
let (_, headResponse) = try await client.send(headRequest)
|
|
614
|
+
if headResponse.statusCode == 404 {
|
|
615
|
+
throw FileStoreError.fileMissing(type: type, id: id)
|
|
616
|
+
}
|
|
617
|
+
guard (200..<300).contains(headResponse.statusCode) else {
|
|
618
|
+
throw FileStoreError.httpError(status: headResponse.statusCode, message: nil)
|
|
619
|
+
}
|
|
620
|
+
let size = headResponse.value(forHTTPHeaderField: "Content-Length").flatMap(Int64.init) ?? 0
|
|
621
|
+
guard size > 0 else {
|
|
622
|
+
throw FileStoreError.httpError(status: headResponse.statusCode, message: "The server gave no size for \(type) \(id)")
|
|
623
|
+
}
|
|
624
|
+
let contentType = headResponse.value(forHTTPHeaderField: "Content-Type") ?? "application/octet-stream"
|
|
625
|
+
let advertised = headResponse.value(forHTTPHeaderField: "X-Instant-Record-Chunk-Size").flatMap(Int.init)
|
|
626
|
+
let piece = advertised.flatMap { $0 > 0 ? min(chunkSize, $0) : nil } ?? chunkSize
|
|
627
|
+
let timestamp = now().timeIntervalSince1970
|
|
628
|
+
dropRecord(type: type, id: id)
|
|
629
|
+
meta = StoredMeta(
|
|
630
|
+
type: type,
|
|
631
|
+
id: id,
|
|
632
|
+
name: "",
|
|
633
|
+
contentType: contentType,
|
|
634
|
+
size: size,
|
|
635
|
+
piece: piece,
|
|
636
|
+
received: 0,
|
|
637
|
+
upload: nil,
|
|
638
|
+
complete: false,
|
|
639
|
+
uploaded: true,
|
|
640
|
+
pinned: false,
|
|
641
|
+
failed: nil,
|
|
642
|
+
addedAt: timestamp,
|
|
643
|
+
usedAt: timestamp
|
|
644
|
+
)
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
let folder = try recordFolder(type: type, id: id, create: true)
|
|
648
|
+
let partialURL = folder.appendingPathComponent(Self.partialFileName)
|
|
649
|
+
let contentURL = folder.appendingPathComponent(Self.contentFileName)
|
|
650
|
+
|
|
651
|
+
let diskSize = fileSize(at: partialURL)
|
|
652
|
+
let committed = min(meta.received, diskSize)
|
|
653
|
+
meta.received = committed
|
|
654
|
+
|
|
655
|
+
do {
|
|
656
|
+
try ensureRoom(for: meta, bytesToWrite: meta.size - meta.received)
|
|
657
|
+
} catch {
|
|
658
|
+
dropRecord(type: type, id: id)
|
|
659
|
+
throw error
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
try writeMeta(meta, in: folder)
|
|
663
|
+
if !fileManager.fileExists(atPath: partialURL.path) {
|
|
664
|
+
fileManager.createFile(atPath: partialURL.path, contents: nil)
|
|
665
|
+
}
|
|
666
|
+
if diskSize > committed {
|
|
667
|
+
let handle = try FileHandle(forUpdating: partialURL)
|
|
668
|
+
try handle.truncate(atOffset: UInt64(committed))
|
|
669
|
+
try handle.close()
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
while meta.received < meta.size {
|
|
673
|
+
let from = meta.received
|
|
674
|
+
let to = min(from + Int64(meta.piece), meta.size) - 1
|
|
675
|
+
let expected = Int(to - from + 1)
|
|
676
|
+
|
|
677
|
+
guard let getURL = serverURL(type: type, id: id) else { throw FileStoreError.invalidURL }
|
|
678
|
+
var request = URLRequest(url: getURL)
|
|
679
|
+
request.httpMethod = "GET"
|
|
680
|
+
request.setValue("bytes=\(from)-\(to)", forHTTPHeaderField: "Range")
|
|
681
|
+
let (body, response) = try await client.send(request)
|
|
682
|
+
if response.statusCode == 404 {
|
|
683
|
+
dropRecord(type: type, id: id)
|
|
684
|
+
throw FileStoreError.fileMissing(type: type, id: id)
|
|
685
|
+
}
|
|
686
|
+
guard (200..<300).contains(response.statusCode) else {
|
|
687
|
+
throw FileStoreError.httpError(status: response.statusCode, message: nil)
|
|
688
|
+
}
|
|
689
|
+
var pieceData = body
|
|
690
|
+
if response.statusCode == 200 && Int64(body.count) == meta.size {
|
|
691
|
+
pieceData = body.subdata(in: Int(from)..<Int(to + 1))
|
|
692
|
+
}
|
|
693
|
+
guard pieceData.count == expected else {
|
|
694
|
+
throw FileStoreError.unexpectedPieceSize(expected: expected, actual: pieceData.count)
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
let handle = try FileHandle(forUpdating: partialURL)
|
|
698
|
+
defer { try? handle.close() }
|
|
699
|
+
try handle.seek(toOffset: UInt64(from))
|
|
700
|
+
try handle.write(contentsOf: pieceData)
|
|
701
|
+
try handle.synchronize()
|
|
702
|
+
|
|
703
|
+
meta.received = to + 1
|
|
704
|
+
try writeMeta(meta, in: folder)
|
|
705
|
+
|
|
706
|
+
let progress = TransferProgress(transferred: meta.received, size: meta.size)
|
|
707
|
+
onProgress?(progress)
|
|
708
|
+
emit(.progress(type: type, id: id, transferred: meta.received, size: meta.size))
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
if fileManager.fileExists(atPath: contentURL.path) {
|
|
712
|
+
try fileManager.removeItem(at: contentURL)
|
|
713
|
+
}
|
|
714
|
+
try fileManager.moveItem(at: partialURL, to: contentURL)
|
|
715
|
+
meta.complete = true
|
|
716
|
+
meta.usedAt = now().timeIntervalSince1970
|
|
717
|
+
try writeMeta(meta, in: folder)
|
|
718
|
+
return contentURL
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
emit(.fetched(type: type, id: id))
|
|
722
|
+
return localURL
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
private func fetchWholeUncached(type: String, id: String) async throws -> Data {
|
|
726
|
+
guard let url = serverURL(type: type, id: id) else { throw FileStoreError.invalidURL }
|
|
727
|
+
var request = URLRequest(url: url)
|
|
728
|
+
request.httpMethod = "GET"
|
|
729
|
+
let (data, response) = try await client.send(request)
|
|
730
|
+
if response.statusCode == 404 {
|
|
731
|
+
throw FileStoreError.fileMissing(type: type, id: id)
|
|
732
|
+
}
|
|
733
|
+
guard (200..<300).contains(response.statusCode) else {
|
|
734
|
+
throw FileStoreError.httpError(status: response.statusCode, message: nil)
|
|
735
|
+
}
|
|
736
|
+
return data
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
private func drain() async -> FileSyncResult {
|
|
740
|
+
let waiting = allMetas()
|
|
741
|
+
.filter { $0.complete && !$0.uploaded && $0.failed == nil }
|
|
742
|
+
.sorted { $0.addedAt < $1.addedAt }
|
|
743
|
+
var sent = 0
|
|
744
|
+
var left = 0
|
|
745
|
+
for meta in waiting {
|
|
746
|
+
do {
|
|
747
|
+
if try await sendFile(meta) {
|
|
748
|
+
sent += 1
|
|
749
|
+
} else {
|
|
750
|
+
left += 1
|
|
751
|
+
}
|
|
752
|
+
} catch {
|
|
753
|
+
// Offline or transient server failure: stop this pass and leave
|
|
754
|
+
// this file plus the remainder waiting.
|
|
755
|
+
left = waiting.count - sent
|
|
756
|
+
break
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
return FileSyncResult(sent: sent, waiting: left)
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
private func sendFile(_ meta: StoredMeta) async throws -> Bool {
|
|
763
|
+
guard let contentURL = fileURL(forType: meta.type, id: meta.id, touch: false),
|
|
764
|
+
let uploadToken = meta.upload else {
|
|
765
|
+
return false
|
|
766
|
+
}
|
|
767
|
+
guard let standingURL = serverURL(
|
|
768
|
+
type: meta.type,
|
|
769
|
+
id: meta.id,
|
|
770
|
+
query: [("upload", uploadToken)],
|
|
771
|
+
suffix: "/upload"
|
|
772
|
+
) else {
|
|
773
|
+
throw FileStoreError.invalidURL
|
|
774
|
+
}
|
|
775
|
+
var standingRequest = URLRequest(url: standingURL)
|
|
776
|
+
standingRequest.httpMethod = "GET"
|
|
777
|
+
let (standingData, standingResponse) = try await client.send(standingRequest)
|
|
778
|
+
if standingResponse.statusCode == 404 {
|
|
779
|
+
return false
|
|
780
|
+
}
|
|
781
|
+
guard (200..<300).contains(standingResponse.statusCode) else {
|
|
782
|
+
throw FileStoreError.httpError(status: standingResponse.statusCode, message: nil)
|
|
783
|
+
}
|
|
784
|
+
let initial = try JSONDecoder().decode(UploadStanding.self, from: standingData)
|
|
785
|
+
var complete = initial.complete
|
|
786
|
+
var offset = initial.offset
|
|
787
|
+
var step = initial.chunkSize.flatMap { $0 > 0 ? min(chunkSize, $0) : nil } ?? chunkSize
|
|
788
|
+
|
|
789
|
+
var turns = 0
|
|
790
|
+
while !complete {
|
|
791
|
+
let maxTurns = Int(ceil(Double(meta.size) / Double(step))) + 8
|
|
792
|
+
guard turns <= maxTurns else { throw FileStoreError.uploadStalled }
|
|
793
|
+
turns += 1
|
|
794
|
+
|
|
795
|
+
let length = Int(min(Int64(step), meta.size - offset))
|
|
796
|
+
let pieceData = try readSlice(from: contentURL, offset: offset, length: length)
|
|
797
|
+
guard let putURL = serverURL(
|
|
798
|
+
type: meta.type,
|
|
799
|
+
id: meta.id,
|
|
800
|
+
query: [("upload", uploadToken), ("offset", String(offset)), ("size", String(meta.size))]
|
|
801
|
+
) else {
|
|
802
|
+
throw FileStoreError.invalidURL
|
|
803
|
+
}
|
|
804
|
+
var putRequest = URLRequest(url: putURL)
|
|
805
|
+
putRequest.httpMethod = "PUT"
|
|
806
|
+
putRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type")
|
|
807
|
+
putRequest.httpBody = pieceData
|
|
808
|
+
|
|
809
|
+
let (replyData, replyResponse) = try await client.send(putRequest)
|
|
810
|
+
switch replyResponse.statusCode {
|
|
811
|
+
case 404:
|
|
812
|
+
return false
|
|
813
|
+
case 409:
|
|
814
|
+
let conflict = try JSONDecoder().decode(UploadStanding.self, from: replyData)
|
|
815
|
+
offset = conflict.offset
|
|
816
|
+
if let serverChunk = conflict.chunkSize, serverChunk > 0 {
|
|
817
|
+
step = min(step, serverChunk)
|
|
818
|
+
}
|
|
819
|
+
continue
|
|
820
|
+
case 413:
|
|
821
|
+
let payload = try? JSONDecoder().decode(ErrorPayload.self, from: replyData)
|
|
822
|
+
if let serverChunk = payload?.chunkSize, serverChunk > 0, serverChunk < step {
|
|
823
|
+
step = serverChunk
|
|
824
|
+
continue
|
|
825
|
+
}
|
|
826
|
+
let reason = payload?.error ?? "refused (413)"
|
|
827
|
+
_ = try await mark(type: meta.type, id: meta.id) { $0.failed = reason }
|
|
828
|
+
emit(.failed(type: meta.type, id: meta.id, reason: reason))
|
|
829
|
+
return false
|
|
830
|
+
case 400, 415, 422:
|
|
831
|
+
let payload = try? JSONDecoder().decode(ErrorPayload.self, from: replyData)
|
|
832
|
+
let reason = payload?.error ?? "refused (\(replyResponse.statusCode))"
|
|
833
|
+
_ = try await mark(type: meta.type, id: meta.id) { $0.failed = reason }
|
|
834
|
+
emit(.failed(type: meta.type, id: meta.id, reason: reason))
|
|
835
|
+
return false
|
|
836
|
+
case 200..<300:
|
|
837
|
+
let accepted = try JSONDecoder().decode(UploadStanding.self, from: replyData)
|
|
838
|
+
complete = accepted.complete
|
|
839
|
+
offset = accepted.offset
|
|
840
|
+
if let serverChunk = accepted.chunkSize, serverChunk > 0 {
|
|
841
|
+
step = min(step, serverChunk)
|
|
842
|
+
}
|
|
843
|
+
emit(.progress(type: meta.type, id: meta.id, transferred: offset, size: meta.size))
|
|
844
|
+
default:
|
|
845
|
+
throw FileStoreError.httpError(status: replyResponse.statusCode, message: nil)
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
_ = try await mark(type: meta.type, id: meta.id) { $0.uploaded = true }
|
|
850
|
+
emit(.uploaded(type: meta.type, id: meta.id))
|
|
851
|
+
return true
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// MARK: - Room & LRU Eviction
|
|
855
|
+
|
|
856
|
+
private func ensureRoom(for keep: StoredMeta, bytesToWrite: Int64) throws {
|
|
857
|
+
guard bytesToWrite > 0, let budget else { return }
|
|
858
|
+
let others = allMetas(includeTorn: true)
|
|
859
|
+
.filter { !($0.type == keep.type && $0.id == keep.id) }
|
|
860
|
+
.reduce(Int64(0)) { $0 + $1.size }
|
|
861
|
+
let over = others + keep.size - budget
|
|
862
|
+
guard over > 0 else { return }
|
|
863
|
+
let freed = evict(bytes: over, keeping: keep)
|
|
864
|
+
if freed < over {
|
|
865
|
+
throw FileStoreError.noRoom(needed: bytesToWrite)
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
private func evict(bytes: Int64, keeping keep: StoredMeta?) -> Int64 {
|
|
870
|
+
guard bytes > 0 else { return 0 }
|
|
871
|
+
let droppable = allMetas()
|
|
872
|
+
.filter { meta in
|
|
873
|
+
meta.uploaded
|
|
874
|
+
&& !meta.pinned
|
|
875
|
+
&& !(keep != nil && meta.type == keep!.type && meta.id == keep!.id)
|
|
876
|
+
}
|
|
877
|
+
.sorted { lhs, rhs in
|
|
878
|
+
if lhs.complete != rhs.complete {
|
|
879
|
+
return !lhs.complete && rhs.complete
|
|
880
|
+
}
|
|
881
|
+
return lhs.usedAt < rhs.usedAt
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
var freed: Int64 = 0
|
|
885
|
+
for meta in droppable {
|
|
886
|
+
if freed >= bytes { break }
|
|
887
|
+
let key = Self.recordKey(meta.type, meta.id)
|
|
888
|
+
if downloads[key] != nil { continue }
|
|
889
|
+
guard tryLockRecord(key) else { continue }
|
|
890
|
+
dropRecord(type: meta.type, id: meta.id)
|
|
891
|
+
unlockRecord(key)
|
|
892
|
+
freed += meta.size
|
|
893
|
+
emit(.evicted(type: meta.type, id: meta.id))
|
|
894
|
+
}
|
|
895
|
+
return freed
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
// MARK: - Disk Helpers
|
|
899
|
+
|
|
900
|
+
private func mark(type: String, id: String, mutate: (inout StoredMeta) -> Void) async throws -> Bool {
|
|
901
|
+
let key = Self.recordKey(type, id)
|
|
902
|
+
return try await withRecordLock(key) {
|
|
903
|
+
guard var meta = readMeta(type: type, id: id) else { return false }
|
|
904
|
+
mutate(&meta)
|
|
905
|
+
try writeMeta(meta, in: recordFolderURL(type: type, id: id))
|
|
906
|
+
return true
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
private func recordFolderURL(type: String, id: String) -> URL {
|
|
911
|
+
root
|
|
912
|
+
.appendingPathComponent("type-\(Self.safe(type))", isDirectory: true)
|
|
913
|
+
.appendingPathComponent(Self.safe(id), isDirectory: true)
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
private func recordFolder(type: String, id: String, create: Bool) throws -> URL {
|
|
917
|
+
let folder = recordFolderURL(type: type, id: id)
|
|
918
|
+
if create {
|
|
919
|
+
try fileManager.createDirectory(at: folder, withIntermediateDirectories: true)
|
|
920
|
+
}
|
|
921
|
+
return folder
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
private func writeMeta(_ meta: StoredMeta, in folder: URL) throws {
|
|
925
|
+
let data = try JSONEncoder().encode(meta)
|
|
926
|
+
try data.write(to: folder.appendingPathComponent(Self.metaFileName), options: .atomic)
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
private func readMeta(type: String, id: String, includeTorn: Bool = false) -> StoredMeta? {
|
|
930
|
+
readMeta(in: recordFolderURL(type: type, id: id), includeTorn: includeTorn)
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
private func readMeta(in folder: URL, includeTorn: Bool) -> StoredMeta? {
|
|
934
|
+
let metaURL = folder.appendingPathComponent(Self.metaFileName)
|
|
935
|
+
guard let data = try? Data(contentsOf: metaURL),
|
|
936
|
+
let meta = try? JSONDecoder().decode(StoredMeta.self, from: data) else {
|
|
937
|
+
return nil
|
|
938
|
+
}
|
|
939
|
+
return (includeTorn || meta.complete || meta.uploaded) ? meta : nil
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
private func allMetas(includeTorn: Bool = false) -> [StoredMeta] {
|
|
943
|
+
guard let typeFolders = try? fileManager.contentsOfDirectory(
|
|
944
|
+
at: root,
|
|
945
|
+
includingPropertiesForKeys: [.isDirectoryKey],
|
|
946
|
+
options: [.skipsHiddenFiles]
|
|
947
|
+
) else {
|
|
948
|
+
return []
|
|
949
|
+
}
|
|
950
|
+
var found: [StoredMeta] = []
|
|
951
|
+
for typeFolder in typeFolders where typeFolder.lastPathComponent.hasPrefix("type-") {
|
|
952
|
+
guard let recordFolders = try? fileManager.contentsOfDirectory(
|
|
953
|
+
at: typeFolder,
|
|
954
|
+
includingPropertiesForKeys: [.isDirectoryKey],
|
|
955
|
+
options: [.skipsHiddenFiles]
|
|
956
|
+
) else {
|
|
957
|
+
continue
|
|
958
|
+
}
|
|
959
|
+
for folder in recordFolders {
|
|
960
|
+
if let meta = readMeta(in: folder, includeTorn: includeTorn) {
|
|
961
|
+
found.append(meta)
|
|
962
|
+
}
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
return found
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
private func dropRecord(type: String, id: String) {
|
|
969
|
+
let folder = recordFolderURL(type: type, id: id)
|
|
970
|
+
try? fileManager.removeItem(at: folder)
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
private func fileSize(at url: URL) -> Int64 {
|
|
974
|
+
guard let attributes = try? fileManager.attributesOfItem(atPath: url.path),
|
|
975
|
+
let number = attributes[.size] as? NSNumber else {
|
|
976
|
+
return 0
|
|
977
|
+
}
|
|
978
|
+
return number.int64Value
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
private func readSlice(from url: URL, offset: Int64, length: Int) throws -> Data {
|
|
982
|
+
let handle = try FileHandle(forReadingFrom: url)
|
|
983
|
+
defer { try? handle.close() }
|
|
984
|
+
try handle.seek(toOffset: UInt64(offset))
|
|
985
|
+
return try handle.read(upToCount: length) ?? Data()
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// MARK: - Per-Record Serialization
|
|
989
|
+
|
|
990
|
+
private func withRecordLock<T>(_ key: String, _ work: () async throws -> T) async rethrows -> T {
|
|
991
|
+
if lockedKeys.contains(key) {
|
|
992
|
+
await withCheckedContinuation { continuation in
|
|
993
|
+
lockWaiters[key, default: []].append(continuation)
|
|
994
|
+
}
|
|
995
|
+
} else {
|
|
996
|
+
lockedKeys.insert(key)
|
|
997
|
+
}
|
|
998
|
+
defer { unlockRecord(key) }
|
|
999
|
+
return try await work()
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
private func tryLockRecord(_ key: String) -> Bool {
|
|
1003
|
+
if lockedKeys.contains(key) { return false }
|
|
1004
|
+
lockedKeys.insert(key)
|
|
1005
|
+
return true
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
private func unlockRecord(_ key: String) {
|
|
1009
|
+
if var waiters = lockWaiters[key], !waiters.isEmpty {
|
|
1010
|
+
let next = waiters.removeFirst()
|
|
1011
|
+
if waiters.isEmpty {
|
|
1012
|
+
lockWaiters.removeValue(forKey: key)
|
|
1013
|
+
} else {
|
|
1014
|
+
lockWaiters[key] = waiters
|
|
1015
|
+
}
|
|
1016
|
+
next.resume()
|
|
1017
|
+
} else {
|
|
1018
|
+
lockedKeys.remove(key)
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
|
|
1022
|
+
private func emit(_ event: FileEvent) {
|
|
1023
|
+
for listener in listeners.values {
|
|
1024
|
+
listener(event)
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// MARK: - Encoding
|
|
1029
|
+
|
|
1030
|
+
private static let unreserved = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~")
|
|
1031
|
+
|
|
1032
|
+
private static func recordKey(_ type: String, _ id: String) -> String {
|
|
1033
|
+
"\(type)/\(id)"
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
private static func urlSegment(_ value: String) -> String {
|
|
1037
|
+
value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? value
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
private static func safe(_ value: String) -> String {
|
|
1041
|
+
let encoded = urlSegment(value)
|
|
1042
|
+
return encoded.hasPrefix(".") ? "%2E" + encoded.dropFirst() : encoded
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
private static func uploadToken() -> String {
|
|
1046
|
+
UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
|
|
1047
|
+
}
|
|
1048
|
+
}
|