SPB Git

Repository Public BSD-3-Clause

README.md 11.8 KB 161 lines markdown

1# ORIXMapPackage23Region packages for ORIX Maps: the `.orixmap` container (reader **and** writer), manifest, Ed25519 signature4verification, the installer and region store, the catalog client and the download manager. This module contains the5only network code of the application.67Depends on `ORIXGeoCore`, Foundation and CryptoKit. iOS 18 / macOS 15, Swift 6 language mode, no third-party code.8Specifications: [`docs/ORIXMAP_FORMAT.md`](../../docs/ORIXMAP_FORMAT.md), [`docs/CATALOG_API.md`](../../docs/CATALOG_API.md).910## API overview1112```swift13// Trust (compiled into the app)14let trust = TrustStore(keys: [TrustedKey(publicKey: Data(base64Encoded: "…")!, label: "production 2026")!], revokedKeyIds: [])1516// Store — root = Application Support/Maps (marked excluded from backup by the store)17var config = RegionStore.Configuration(trustStore: trust)18config.compatibility = PackageCompatibility(appVersion: AppVersion("1.0"),19                                            supportedComponentFormats: [.map: 3...3, .search: 1...1, .routing: 1...1])20let store = try RegionStore(root: mapsDirectory, configuration: config)       // throws(RegionStoreError); recovers21store.recoveryReport                                                          // what was cleaned or repaired2223await store.regions()                         // [InstalledRegion] — manifest, directory, sizeOnDisk, previousVersion24await store.region("ca-qc-montreal")?.mapURL  // …/regions/ca-qc-montreal/2026.11.24/map.pmtiles (also searchURL, routingURL, terrainURL)25for await change in await store.changes() { } // .activated(region, replaced:) / .removed(regionId:version:)2627try await store.install(packageAt: url, options: InstallOptions(allowDowngrade: false, reinstall: false, deleteSourceOnSuccess: false),28                        progress: { p in })   // throws(RegionStoreError)29try await store.importPackage(from: pickedURL)  // Files: security-scoped access, same verification, file left untouched30try await store.rollback(regionId: id)          // previous version active again, newer one deleted31try await store.removePreviousVersion(regionId: id)   // free the rollback copy; returns bytes freed32try await store.delete(regionId: id)33try await store.verifyInstalled(regionId: id)   // signature + SHA-256 of installed files34try store.checkSpace(downloadSize:installedSize:alreadyDownloaded:)   // throws .notEnoughSpace(required:available:missing:)35try await store.checkInstallable(manifest)      // app version, component formats, downgrade, already installed3637// Catalog38let transport = URLSessionTransport(userAgent: "ORIXMaps/1.0")39let catalog = CatalogClient(baseURL: CatalogClient.defaultBaseURL, transport: transport, cacheDirectory: cachesDirectory)40let snapshot = try await catalog.catalog()      // CatalogSnapshot<Catalog>: document, fetchedAt, validatedAt, origin, isStale41try await catalog.regionDetail(id: id); try await catalog.versions(id: id)4243// Download44var dc = DownloadManager.Configuration(); dc.baseURL = CatalogClient.defaultBaseURL45let downloads = DownloadManager(store: store, transport: transport, configuration: dc)46let request = DownloadRequest(region: snapshot.document.regions[0])47let preamble = try await downloads.fetchManifest(request, preambleSize: region.latest.preambleSize)   // signed manifest only48await downloads.start(request)                  // returns at once; or: try await downloads.download(request)49for await event in await downloads.events() { } // .downloading(progress) .waitingToRetry .verifying .installing .paused .completed .failed .cancelled50await downloads.pause(regionId: id); try await downloads.resume(regionId: id); await downloads.cancel(regionId: id)51downloads.pendingDownloads()                    // partial files left by a previous launch52try await downloads.installDownloadedFile(at: fileURL, for: request)   // hand-over point for a background URLSession5354// Lower level55let verifier = PackageVerifier(trustStore: trust)56try verifier.verify(at: url)                    // throws(PackageError): structure, limits, signature, streaming SHA-25657try verifier.readPreamble(at: url); try verifier.verifyPreamble(data)58try PackageWriter.write(description:components:signingKey:to:)   // build tools only59```6061Errors are typed and `Equatable`: `PackageError` (with `ManifestProblem`, `LayoutProblem`), `RegionStoreError`,62`CatalogError`, `DownloadError`, `TransportError`. They carry values (bytes missing, versions, key ids), never sentences.63All public types are `Sendable`; `RegionStore`, `CatalogClient` and `DownloadManager` are actors; nothing is a singleton.6465## Region store6667```68<root>/regions/<regionId>/state.json                 {"active": "2026.11.24", "previous": "2026.11.10", "activatedAt": …}69<root>/regions/<regionId>/<dataVersion>/manifest.json   exact signed bytes      manifest.sig   64-byte signature70<root>/regions/<regionId>/<dataVersion>/map.pmtiles | search.sqlite | routing.orixgraph | terrain.pmtiles71<root>/staging/install-<uuid>/    extraction in progress        <root>/staging/trash-<uuid>/   deletion in progress72<root>/staging/downloads/<regionId>-<dataVersion>.orixmap.part + .download.json    partial downloads (kept)73```7475**Install** = (1) preamble verified, compatibility / downgrade / free-space checks; (2) off the actor, one streaming pass76copies each known component into `staging/install-<uuid>/` through a 1 MiB buffer while hashing it (the bytes hashed are77the bytes written), checks zero padding, `fsync`s every file and the directory; (3) on the actor the checks are repeated78on the extracted manifest, the directory is renamed to `regions/<id>/<version>/` and `state.json` is replaced by79write-temp + `F_FULLFSYNC` + rename — **that rename is the commit**. The previously active version becomes the rollback80copy; the one before it is deleted. Components are sub-ranges of one file, so `clonefile`/`copyfile` (whole files only)81do not apply: extraction is a range copy.8283**Crash recovery** (when the store is opened; tested by interrupting commits and re-opening):8485| State found | Result |86|---|---|87| `staging/install-*`, `staging/trash-*`, stray files in `staging/` | removed (`staging/downloads/` is kept) |88| version directory but no `state.json` (first install never committed) | region removed: nothing was active |89| version directory not referenced by `state.json` (update not committed, or old copy not yet deleted) | removed |90| `state.json` points to missing/damaged data (manifest invalid, component missing or wrong length) | falls back to the rollback copy, state rewritten |91| `state.json` unreadable | newest valid version becomes active |92| directory under `regions/` that is not a region id, or whose manifest names another region | removed |9394Consumers: a replaced version stays on disk as the rollback copy, and deleted files stay readable through descriptors95and mappings already open, so the map / search / routing layers can switch files on `.activated` without racing.9697## Measured (2026-11-25, Mac17,6 — M5 Max, 18 cores, 48 GB, macOS 27.0, APFS internal SSD, release build, warm page cache)9899Commands: `Infrastructure/package-builder/bench.sh <key> <trust> <dir>` (synthetic: pseudo-random components behind a100valid PMTiles header; three runs each, all three shown when they differ) and, for the real package, the commands of101`Infrastructure/package-builder/README.md` under `/usr/bin/time -l`.102103| Package | Size | Container overhead | `verify` | `install` (extract + fsync + commit) | Peak memory footprint verify / install | Max RSS verify / install |104|---|---:|---:|---:|---:|---:|---:|105| synthetic 50 MB (30 + 10 + 10) | 50 009 728 B | 9 728 B | 0.018 s | 0.046–0.053 s | 3.87 MB / 5.9 MB | 9.2 MB / 13.4 MB |106| synthetic 300 MB (180 + 60 + 60) | 300 009 216 B | 9 216 B | 0.105–0.106 s | 0.153–0.157 s | 3.87 MB / 5.9 MB | 9.3 MB / 13.4 MB |107| real Greater Montréal (map 96.4 MB, search 40.5 MB, routing 99.3 MB) | 236 150 784 B | 4 185 B | 0.081 s | 0.133 s | 3.87 MB / 5.9 MB | 9.3 MB / 13.4 MB |108109Memory does not grow with the package (same footprint at 50 and 300 MB). Not measured: cold-cache reads, an iPhone110(slower storage and CPU; expect several times these durations), packages over 300 MB.111112## Tests113114`swift test` — **94 tests in 7 suites, all passing** (2026-11-25; run 12 times in a row without failure after the fix115of a late-progress race found by repetition). Includes: manifest round-trip and every limit; container round-trip with116multi-megabyte components; every rejection path (magic, major, truncation at every structural boundary, overlap,117out-of-file, misalignment, wrong lengths, wrong SHA-256, tampered manifest / signature / padding, unknown / revoked /118expired / not-yet-valid key, key mismatch, oversized manifest, hostile region and component ids, integer overflow);119fuzzing (4 000 byte-level mutations of a valid package, 2 500 manifests mutated **and re-signed with a trusted key**,1202 500 random inputs, 7 000 random JSON / byte strings through the manifest, catalog and header decoders — outcome must be121success or a typed error, with nothing written outside the staging directory); store install / update / rollback /122delete / downgrade / reinstall / incompatibility / space / five crash-recovery scenarios / concurrency (two installs of123one region, six concurrent versions, install during delete, cancellation); catalog decoding compatibility and cache;124downloads on an in-process server and on a **real HTTP server on 127.0.0.1** (Network framework) with the real125`URLSessionTransport`: interruption, Range + If-Range resume, changed ETag, 429, truncated body, wrong checksum.126127The library also compiles for iOS (`swift build --triple arm64-apple-ios18.0 --sdk $(xcrun --sdk iphoneos --show-sdk-path)`,128checked 2026-11-25); it was **not run** on a device or a simulator.129130## Background downloads — what exists and what does not131132Implemented: foreground transfers on a default-style ephemeral `URLSession` behind `HTTPTransport`, with all resume133state on disk (partial file + sidecar), so a download continues after the app is killed **when the app runs again**.134Not implemented: a background `URLSession`. The design leaves one seam for it: a background download task delivers a135complete temporary file to the app delegate, which calls `DownloadManager.installDownloadedFile(at:for:)` (size and136SHA-256 check, then the same `RegionStore.install`). The persisted `DownloadRequest` (sidecar) is what the delegate needs137to find the request for a finished task. Progress events and pause/resume for background tasks would have to be bridged138from the session delegate.139140## Known limits141142- One `RegionStore` per root directory; two processes or two instances on the same root are not coordinated.143- A resumed partial file is trusted until the final SHA-256: after a power loss that corrupted it, the whole file is144  downloaded again (no per-block hashes).145- Without a strong ETag from the server nothing is resumed.146- The response body stream is unbounded: if the disk were slower than the network, chunks would queue in memory (not147  observed; no back-pressure implemented).148- `importPackage` reads the URL directly: for a file that a file provider has not downloaded yet, present the picker149  with `asCopy: true` (or coordinate the read) in the app.150- `notAfter` is compared with the signed build date, not the device clock (see the format document, section 5).151- Deleting a region forgets its version: a later install of an older version is then not a "downgrade".152- Redirects are followed by `URLSession` with its default policy; the specification asks the server not to redirect.153- Rollback keeps one previous version only.154155## Not done156157- Background `URLSession` (above). Server side of the catalog API. Signed catalog. Delta updates.158- Any run on iOS hardware or simulator; any request to the real `www.orixlab.dev`.159- Localized messages for the error cases (the app's job, by convention).160- File headers (applied by the repository header tool at the end, per `docs/CONVENTIONS.md`).161
Files main
Menu

Theme