field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

TeraHistoricalHostWriter.swift (7445B)


      1 import CoreGraphics
      2 import Foundation
      3 import ImageIO
      4 import RadrootsKit
      5 import UniformTypeIdentifiers
      6 import XCTest
      7 
      8 @MainActor
      9 final class TeraHistoricalFixtureWriterTests: XCTestCase {
     10   func testProduceHistoricalOwnerBytes() async throws {
     11     let environment = ProcessInfo.processInfo.environment
     12     let output = try URL(fileURLWithPath: XCTUnwrap(environment["TERA_LEGACY_FIXTURE_OUTPUT"]), isDirectory: true)
     13     let roots = try roots(output)
     14     if environment["TERA_LEGACY_FIXTURE_PHASE"] == "host" {
     15       try await produceHost(output, roots: roots)
     16     } else {
     17       XCTAssertEqual(environment["TERA_LEGACY_FIXTURE_PHASE"], "transfer")
     18       try await produceTransfer(output, roots: roots)
     19     }
     20   }
     21 
     22   private func roots(_ output: URL) throws -> RadrootsAppleFileRoots {
     23     for directory in ["data", "cache", "tmp", "logs"] {
     24       try FileManager.default.createDirectory(at: output.appendingPathComponent(directory), withIntermediateDirectories: true)
     25     }
     26     return try RadrootsAppleFileRoots(appIdentifier: "dev.local.radroots",
     27                                       dataRoot: output.appendingPathComponent("data"), cacheRoot: output.appendingPathComponent("cache"),
     28                                       temporaryRoot: output.appendingPathComponent("tmp"), logsRoot: output.appendingPathComponent("logs"))
     29   }
     30 
     31   private func produceHost(_ output: URL, roots: RadrootsAppleFileRoots) async throws {
     32     let metadata = RadrootsRuntimeAppMetadata(bundleIdentifier: "dev.local.radroots", version: "1.0.0-alpha", buildNumber: "1", buildSHA: nil)
     33     let bootstrap = RadrootsConfigurationBootstrap(runtimeMode: "production",
     34                                                    relayURLs: ["wss://relay-one.example", "wss://relay-two.example"], blossomOrigins: ["https://blossom.example"],
     35                                                    keychainServicePrefix: "org.radroots.field_ios.local", bundleIdentifier: "dev.local.radroots", appMetadata: metadata)
     36     let configuration = RadrootsConfigurationStore(bootstrap: bootstrap, roots: roots, clock: .fixed(unixSeconds: 1_700_000_000))
     37     let selected = try await configuration.load()
     38     XCTAssertEqual(selected.generation, 1)
     39     let generation = try await configuration.sourceGeneration()
     40     let source = try RadrootsFileReference(scope: .temporary, relativePath: "synthetic_source.png")
     41     try RadrootsAppleFileAccess(roots: roots).write(.inline(syntheticPNG()), to: source)
     42     let image = try await RadrootsAppleMediaPreparer(roots: roots).prepareImage(RadrootsAppleImagePreparationRequest(source: .file(source)))
     43     let staged = try roots.stagedBlobURL(for: image.file)
     44     let value: [String: Any] = ["source_generation": generation.generationHex,
     45                                 "generation_created_at_unix_ms": generation.createdAtUnixMilliseconds,
     46                                 "media_sha256": image.sha256, "media_bytes": image.file.sizeBytes,
     47                                 "media_width": image.width, "media_height": image.height,
     48                                 "staged_relative_path": String(staged.path.dropFirst(output.path.count + 1)),
     49                                 "bundle_identifier": selected.bundleIdentifier, "keychain_service_prefix": selected.keychainServicePrefix]
     50     try write(value, to: output.appendingPathComponent("host-metadata.json"))
     51     // Keep the actual historical sanitized blob, never the temporary source.
     52     try RadrootsAppleFileAccess(roots: roots).delete(source)
     53   }
     54 
     55   private func produceTransfer(_ output: URL, roots: RadrootsAppleFileRoots) async throws {
     56     let host = try dictionary(output.appendingPathComponent("host-metadata.json"))
     57     let rust = try dictionary(output.appendingPathComponent("rust-metadata.json"))
     58     let job = try XCTUnwrap(rust["native_pending"] as? [String: Any])
     59     let hash = try XCTUnwrap(job["sha256"] as? String)
     60     let count = try XCTUnwrap(Int(exactly: XCTUnwrap(job["byte_size"] as? NSNumber).uint64Value))
     61     let blob = try RadrootsStagedBlobReference(blobID: hash, sizeBytes: count, mediaType: "image/png", filenameHint: hash + ".png")
     62     let id = try "radroots.add.\(XCTUnwrap(job["draft_id"] as? String)).\(XCTUnwrap(job["revision"] as? NSNumber)).\(XCTUnwrap(job["operation_id"] as? String))"
     63     let request = try RadrootsBackgroundTransferRequest(identifier: RadrootsBackgroundTransferIdentifier(id),
     64                                                         remoteURL: XCTUnwrap(try URL(string: XCTUnwrap(job["remote_url"] as? String))), method: .put,
     65                                                         operation: .upload(source: .stagedBlob(blob)), responsePolicy: .boundedJSON(), expectedSourceSHA256: hash)
     66     let descriptor: [String: Any] = ["url": "https://blossom.example/\(hash).png", "sha256": hash, "size": count, "type": "image/png", "uploaded": 1_786_000_000]
     67     let body = try JSONSerialization.data(withJSONObject: descriptor, options: [.sortedKeys])
     68     let response = try RadrootsBackgroundTransferResponse(statusCode: 200, mediaType: "application/json", body: body)
     69     let snapshot = try RadrootsBackgroundTransferSnapshot(request: request, state: .awaitingVerification,
     70                                                           progress: RadrootsBackgroundTransferProgress(bytesTransferred: Int64(count), totalBytesExpected: Int64(count)),
     71                                                           response: response, updatedAt: Date())
     72     let store = RadrootsAppleBackgroundTransferStore(roots: roots)
     73     try await store.saveSnapshot(snapshot)
     74     let loaded = try await store.loadSnapshots()
     75     XCTAssertEqual(loaded.count, 1)
     76     XCTAssertEqual(loaded[0].request.headers, [:])
     77     XCTAssertEqual(loaded[0].identifier.rawValue, id)
     78     try write(["native_identifier": id, "media_sha256": hash, "public_key": XCTUnwrap(rust["public_key"] as? String),
     79                "source_generation": XCTUnwrap(host["source_generation"] as? String),
     80                "state": "awaitingVerification", "limit": "Actual old typed persistence; no physical OS upload/termination claim."], to: output.appendingPathComponent("native-metadata.json"))
     81   }
     82 
     83   private func dictionary(_ url: URL) throws -> [String: Any] {
     84     try XCTUnwrap(JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any])
     85   }
     86 
     87   private func write(_ value: [String: Any], to url: URL) throws {
     88     try JSONSerialization.data(withJSONObject: value, options: [.prettyPrinted, .sortedKeys]).write(to: url, options: [.atomic])
     89   }
     90 
     91   private func syntheticPNG() throws -> Data {
     92     let bytes = Data([255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 0, 255, 255, 0, 255, 255, 0, 255, 255, 255])
     93     let provider = try XCTUnwrap(CGDataProvider(data: bytes as CFData))
     94     let image = try XCTUnwrap(CGImage(width: 2, height: 3, bitsPerComponent: 8, bitsPerPixel: 32,
     95                                       bytesPerRow: 8, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
     96                                       provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent))
     97     let data = NSMutableData()
     98     let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil))
     99     CGImageDestinationAddImage(destination, image, [:] as CFDictionary)
    100     XCTAssertTrue(CGImageDestinationFinalize(destination))
    101     return data as Data
    102   }
    103 }