SPB Git

Repository Public BSD-3-Clause

README.md 11.8 KB

# ORIXMapPackage

Region packages for ORIX Maps: the .orixmap container (reader and writer), manifest, Ed25519 signature verification, the installer and region store, the catalog client and the download manager. This module contains the only network code of the application.

Depends on ORIXGeoCore, Foundation and CryptoKit. iOS 18 / macOS 15, Swift 6 language mode, no third-party code. Specifications: docs/ORIXMAP_FORMAT.md, docs/CATALOG_API.md.

# API overview

swift
// Trust (compiled into the app)
let trust = TrustStore(keys: [TrustedKey(publicKey: Data(base64Encoded: "…")!, label: "production 2026")!], revokedKeyIds: [])

// Store — root = Application Support/Maps (marked excluded from backup by the store)
var config = RegionStore.Configuration(trustStore: trust)
config.compatibility = PackageCompatibility(appVersion: AppVersion("1.0"),
                                            supportedComponentFormats: [.map: 3...3, .search: 1...1, .routing: 1...1])
let store = try RegionStore(root: mapsDirectory, configuration: config)       // throws(RegionStoreError); recovers
store.recoveryReport                                                          // what was cleaned or repaired

await store.regions()                         // [InstalledRegion] — manifest, directory, sizeOnDisk, previousVersion
await store.region("ca-qc-montreal")?.mapURL  // …/regions/ca-qc-montreal/2026.11.24/map.pmtiles (also searchURL, routingURL, terrainURL)
for await change in await store.changes() { } // .activated(region, replaced:) / .removed(regionId:version:)

try await store.install(packageAt: url, options: InstallOptions(allowDowngrade: false, reinstall: false, deleteSourceOnSuccess: false),
                        progress: { p in })   // throws(RegionStoreError)
try await store.importPackage(from: pickedURL)  // Files: security-scoped access, same verification, file left untouched
try await store.rollback(regionId: id)          // previous version active again, newer one deleted
try await store.removePreviousVersion(regionId: id)   // free the rollback copy; returns bytes freed
try await store.delete(regionId: id)
try await store.verifyInstalled(regionId: id)   // signature + SHA-256 of installed files
try store.checkSpace(downloadSize:installedSize:alreadyDownloaded:)   // throws .notEnoughSpace(required:available:missing:)
try await store.checkInstallable(manifest)      // app version, component formats, downgrade, already installed

// Catalog
let transport = URLSessionTransport(userAgent: "ORIXMaps/1.0")
let catalog = CatalogClient(baseURL: CatalogClient.defaultBaseURL, transport: transport, cacheDirectory: cachesDirectory)
let snapshot = try await catalog.catalog()      // CatalogSnapshot<Catalog>: document, fetchedAt, validatedAt, origin, isStale
try await catalog.regionDetail(id: id); try await catalog.versions(id: id)

// Download
var dc = DownloadManager.Configuration(); dc.baseURL = CatalogClient.defaultBaseURL
let downloads = DownloadManager(store: store, transport: transport, configuration: dc)
let request = DownloadRequest(region: snapshot.document.regions[0])
let preamble = try await downloads.fetchManifest(request, preambleSize: region.latest.preambleSize)   // signed manifest only
await downloads.start(request)                  // returns at once; or: try await downloads.download(request)
for await event in await downloads.events() { } // .downloading(progress) .waitingToRetry .verifying .installing .paused .completed .failed .cancelled
await downloads.pause(regionId: id); try await downloads.resume(regionId: id); await downloads.cancel(regionId: id)
downloads.pendingDownloads()                    // partial files left by a previous launch
try await downloads.installDownloadedFile(at: fileURL, for: request)   // hand-over point for a background URLSession

// Lower level
let verifier = PackageVerifier(trustStore: trust)
try verifier.verify(at: url)                    // throws(PackageError): structure, limits, signature, streaming SHA-256
try verifier.readPreamble(at: url); try verifier.verifyPreamble(data)
try PackageWriter.write(description:components:signingKey:to:)   // build tools only

Errors are typed and Equatable: PackageError (with ManifestProblem, LayoutProblem), RegionStoreError, CatalogError, DownloadError, TransportError. They carry values (bytes missing, versions, key ids), never sentences. All public types are Sendable; RegionStore, CatalogClient and DownloadManager are actors; nothing is a singleton.

# Region store

text
<root>/regions/<regionId>/state.json                 {"active": "2026.11.24", "previous": "2026.11.10", "activatedAt": …}
<root>/regions/<regionId>/<dataVersion>/manifest.json   exact signed bytes      manifest.sig   64-byte signature
<root>/regions/<regionId>/<dataVersion>/map.pmtiles | search.sqlite | routing.orixgraph | terrain.pmtiles
<root>/staging/install-<uuid>/    extraction in progress        <root>/staging/trash-<uuid>/   deletion in progress
<root>/staging/downloads/<regionId>-<dataVersion>.orixmap.part + .download.json    partial downloads (kept)

Install = (1) preamble verified, compatibility / downgrade / free-space checks; (2) off the actor, one streaming pass copies each known component into staging/install-<uuid>/ through a 1 MiB buffer while hashing it (the bytes hashed are the bytes written), checks zero padding, fsyncs every file and the directory; (3) on the actor the checks are repeated on the extracted manifest, the directory is renamed to regions/<id>/<version>/ and state.json is replaced by write-temp + F_FULLFSYNC + rename — that rename is the commit. The previously active version becomes the rollback copy; the one before it is deleted. Components are sub-ranges of one file, so clonefile/copyfile (whole files only) do not apply: extraction is a range copy.

Crash recovery (when the store is opened; tested by interrupting commits and re-opening):

State found Result
staging/install-*, staging/trash-*, stray files in staging/ removed (staging/downloads/ is kept)
version directory but no state.json (first install never committed) region removed: nothing was active
version directory not referenced by state.json (update not committed, or old copy not yet deleted) removed
state.json points to missing/damaged data (manifest invalid, component missing or wrong length) falls back to the rollback copy, state rewritten
state.json unreadable newest valid version becomes active
directory under regions/ that is not a region id, or whose manifest names another region removed

Consumers: a replaced version stays on disk as the rollback copy, and deleted files stay readable through descriptors and mappings already open, so the map / search / routing layers can switch files on .activated without racing.

# Measured (2026-11-25, Mac17,6 — M5 Max, 18 cores, 48 GB, macOS 27.0, APFS internal SSD, release build, warm page cache)

Commands: Infrastructure/package-builder/bench.sh <key> <trust> <dir> (synthetic: pseudo-random components behind a valid PMTiles header; three runs each, all three shown when they differ) and, for the real package, the commands of Infrastructure/package-builder/README.md under /usr/bin/time -l.

Package Size Container overhead verify install (extract + fsync + commit) Peak memory footprint verify / install Max RSS verify / install
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
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
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

Memory does not grow with the package (same footprint at 50 and 300 MB). Not measured: cold-cache reads, an iPhone (slower storage and CPU; expect several times these durations), packages over 300 MB.

# Tests

swift test — 94 tests in 7 suites, all passing (2026-11-25; run 12 times in a row without failure after the fix of a late-progress race found by repetition). Includes: manifest round-trip and every limit; container round-trip with multi-megabyte components; every rejection path (magic, major, truncation at every structural boundary, overlap, out-of-file, misalignment, wrong lengths, wrong SHA-256, tampered manifest / signature / padding, unknown / revoked / expired / not-yet-valid key, key mismatch, oversized manifest, hostile region and component ids, integer overflow); fuzzing (4 000 byte-level mutations of a valid package, 2 500 manifests mutated and re-signed with a trusted key, 2 500 random inputs, 7 000 random JSON / byte strings through the manifest, catalog and header decoders — outcome must be success or a typed error, with nothing written outside the staging directory); store install / update / rollback / delete / downgrade / reinstall / incompatibility / space / five crash-recovery scenarios / concurrency (two installs of one region, six concurrent versions, install during delete, cancellation); catalog decoding compatibility and cache; downloads on an in-process server and on a real HTTP server on 127.0.0.1 (Network framework) with the real URLSessionTransport: interruption, Range + If-Range resume, changed ETag, 429, truncated body, wrong checksum.

The library also compiles for iOS (swift build --triple arm64-apple-ios18.0 --sdk $(xcrun --sdk iphoneos --show-sdk-path), checked 2026-11-25); it was not run on a device or a simulator.

# Background downloads — what exists and what does not

Implemented: foreground transfers on a default-style ephemeral URLSession behind HTTPTransport, with all resume state on disk (partial file + sidecar), so a download continues after the app is killed when the app runs again. Not implemented: a background URLSession. The design leaves one seam for it: a background download task delivers a complete temporary file to the app delegate, which calls DownloadManager.installDownloadedFile(at:for:) (size and SHA-256 check, then the same RegionStore.install). The persisted DownloadRequest (sidecar) is what the delegate needs to find the request for a finished task. Progress events and pause/resume for background tasks would have to be bridged from the session delegate.

# Known limits

  • One RegionStore per root directory; two processes or two instances on the same root are not coordinated.
  • A resumed partial file is trusted until the final SHA-256: after a power loss that corrupted it, the whole file is downloaded again (no per-block hashes).
  • Without a strong ETag from the server nothing is resumed.
  • The response body stream is unbounded: if the disk were slower than the network, chunks would queue in memory (not observed; no back-pressure implemented).
  • importPackage reads the URL directly: for a file that a file provider has not downloaded yet, present the picker with asCopy: true (or coordinate the read) in the app.
  • notAfter is compared with the signed build date, not the device clock (see the format document, section 5).
  • Deleting a region forgets its version: a later install of an older version is then not a "downgrade".
  • Redirects are followed by URLSession with its default policy; the specification asks the server not to redirect.
  • Rollback keeps one previous version only.

# Not done

  • Background URLSession (above). Server side of the catalog API. Signed catalog. Delta updates.
  • Any run on iOS hardware or simulator; any request to the real www.orixlab.dev.
  • Localized messages for the error cases (the app's job, by convention).
  • File headers (applied by the repository header tool at the end, per docs/CONVENTIONS.md).
Files main
Menu

Theme