lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

Smoke.swift (17100B)


      1 import Foundation
      2 
      3 enum SmokeFailure: Swift.Error {
      4     case failed(String)
      5 }
      6 func trace(_ message: String) {
      7     FileHandle.standardOutput.write(Data((message + "\n").utf8))
      8 }
      9 func check(_ value: Bool, _ message: String) throws {
     10     if !value { throw SmokeFailure.failed(message) }
     11 }
     12 func request(_ host: Host, _ id: String) throws -> CommandRequest {
     13     CommandRequest(operationId: String(repeating: id, count: 32),
     14         firstIssueNotAfter: String(UInt64(try host.unixSeconds())! + 120), correlationId: "Swift actual calls")
     15 }
     16 func listing(_ host: Host, _ id: String) throws -> ListingInput {
     17     let option = String(repeating: "02", count: 32)
     18     let profile: [String: Any] = [
     19         "profile": "radroots.listing", "version": 1, "state": "active",
     20         "product": ["name": "Carrots", "description": "Fresh carrots", "producer": NSNull(), "origin_summary": NSNull()],
     21         "default_option": option,
     22         "options": [["id": option, "label": "Bunch", "unit": ["type": "package", "label": "bunch", "contents": ["type": "unspecified"]],
     23             "increment": "1", "minimum": "1", "price": ["type": "quote_required"], "supply": ["type": "available", "amount": "10"], "lead_seconds": "0"]],
     24         "fulfillment": ["modes": ["pickup"], "area": "Example", "lead_seconds": "0"], "authority": NSNull(), "media": []
     25     ]
     26     let input: [String: Any] = ["id": String(repeating: id, count: 16), "title": "  Swift carrots 🥕  ",
     27         "summary": "Quote required", "description_markdown": "Exact native terms", "published_at": try host.unixSeconds(), "profile": profile]
     28     return try ListingInput.parse(input: JSONSerialization.data(withJSONObject: input))
     29 }
     30 func close(_ host: Host, _ session: Session) async throws {
     31     let callbacks = UInt64(try host.measurements().closedCallbacks)!
     32     try await session.client.close()
     33     try check(session.client.state() == .closed, "actual closed state")
     34     try check(UInt64(try host.measurements().closedCallbacks)! == callbacks + 1, "actual provider closure")
     35     try await host.cleanup()
     36 }
     37 
     38 func publicFlow() async throws {
     39     let host = try await Host.open(seller: true, unknownSigning: false, pauseAfterSigning: false)
     40     let first = host.session()
     41     try check(first.client.state() == .ready, "host does not auto-start")
     42     _ = try await first.client.start(mode: .online)
     43     host.setAccepting(accepting: false)
     44     var context = try request(host, "11")
     45     context.firstIssueNotAfter = String(UInt64(try host.unixSeconds())! + 10)
     46     let input = try listing(host, "11")
     47     let result = try await first.client.publishListing(workspace: first.workspace, request: context, input: input)
     48     try check(result.kind == .listing && result.admission == .confirmed, "real public admission")
     49     try check(result.businessInstallation == .installed && result.issuance == .obtained, "independent install/issuance")
     50     guard case let .listing(value)? = result.businessResult else { throw SmokeFailure.failed("typed listing result") }
     51     try check(value.title() == "  Swift carrots 🥕  ", "exact Unicode/whitespace")
     52     try check(result.messageId == nil && result.artifacts.allSatisfy { $0.recipient == nil }, "public optional identity")
     53     try check(result.deliveryObservations.count == 1 && result.deliveryObservations[0].outcome == .rejected, "actual rejection")
     54     let before = try host.measurements()
     55     try check(before.signingCalls == "1" && before.legacySigningCalls == "0" && before.relayReads == "0", "actual public effects")
     56     let event = try JSONSerialization.jsonObject(with: Data(before.originalSignedEvents[0].utf8)) as! [String: Any]
     57     try check(event["id"] as? String == value.revision(), "actual wire revision")
     58     let replay = try await first.client.publishListing(workspace: first.workspace, request: context, input: input)
     59     try check(replay.operationCheckpoint == result.operationCheckpoint, "replay retains facts")
     60     try check(try host.measurements().originalSignedEvents == before.originalSignedEvents, "replay has no network effect")
     61     try await first.client.close()
     62     let next = try await host.reopen()
     63     _ = try await next.client.start(mode: .online)
     64     let queried = try await next.client.operation(workspace: next.workspace, operationId: result.operationId, expectedDigest: result.commandDigest)
     65     try check(queried?.operationCheckpoint == result.operationCheckpoint, "scoped reopened query")
     66     host.setAccepting(accepting: true)
     67     while UInt64(try host.unixSeconds())! <= UInt64(result.firstIssueNotAfter)! {
     68         try await Task.sleep(nanoseconds: 100_000_000)
     69     }
     70     let resumed = try await next.client.resume(workspace: next.workspace, operationId: result.operationId, expectedDigest: result.commandDigest)
     71     try check(resumed.deliveryAttempts.count == 2, "fresh retained retry count=\(resumed.deliveryAttempts.count), issuance=\(resumed.issuance), recovery=\(resumed.recovery), error=\(String(describing: resumed.error))")
     72     try check(Set(resumed.deliveryAttempts.map { $0.targetOrdinals }) == Set([Data([1]), Data([2])]), "both original and fresh ordinals are retained independently of identity order")
     73     try check(resumed.deliveryAttempts[0].originalBytesDigest == resumed.deliveryAttempts[1].originalBytesDigest, "original byte commitment")
     74     try check(resumed.deliveryAttempts[0].publicationPolicyDigest == resumed.deliveryAttempts[1].publicationPolicyDigest, "original policy")
     75     try check(resumed.deliveryObservations.contains { $0.outcome == .accepted }, "actual acceptance")
     76     let after = try host.measurements()
     77     try check(after.signingCalls == "1" && after.originalSignedEvents == [before.originalSignedEvents[0], before.originalSignedEvents[0]], "same actual bytes, no resign")
     78     try await close(host, next)
     79 }
     80 
     81 func privateFlowAndErrors() async throws {
     82     let host = try await Host.open(seller: false, unknownSigning: false, pauseAfterSigning: false)
     83     let session = host.session(); _ = try await session.client.start(mode: .online)
     84     let peer = "c6047f9441ed7d6d3045406e95c07cd85c778e4b8cef3ca7abac09b95c709ee5"
     85     let text = "\u{feff}  Cafe\u{301} / Café Swift inquiry 🥕\nExact text\0  "
     86     let input = try InquiryInput(threadId: String(repeating: "22", count: 32), peer: peer, source: nil, text: text)
     87     let result = try await session.client.inquire(workspace: session.workspace, request: request(host, "12"), input: input)
     88     guard case let .chat(value)? = result.businessResult else { throw SmokeFailure.failed("typed chat") }
     89     try check(result.kind == .chat && value.peer() == peer && value.text().utf8.elementsEqual(text.utf8), "actual private UTF8 data without normalization")
     90     try check(result.artifacts.count == 2 && result.artifacts.allSatisfy { $0.recipient != nil }, "original private subjects")
     91     let before = try host.measurements(); try check(before.signingCalls == "2" && before.relayReads != "0", "private route/signing effects")
     92     do {
     93         _ = try InquiryInput(threadId: String(repeating: "22", count: 32), peer: peer.uppercased(), source: nil, text: "private input must not enter errors")
     94         throw SmokeFailure.failed("uppercase key accepted")
     95     } catch Error.InvalidInput(let field) { try check(field == "peer", "safe input cause") }
     96     do { _ = try ListingInput.parse(input: Data("{}".utf8)); throw SmokeFailure.failed("invalid listing accepted") }
     97     catch Error.InvalidInput(let field) { try check(field == "listing_input", "shared input parser") }
     98     do { _ = try ListingInput.parse(input: Data("{\"profile\":{\"version\":2}}".utf8)); throw SmokeFailure.failed("unsupported profile accepted") }
     99     catch Error.CommandInput(let field, let kind) { try check(field == "listing_input" && kind == .unsupportedProfile, "typed unsupported profile") }
    100     do { _ = try ListingInput.parse(input: Data(repeating: 32, count: 65_537)); throw SmokeFailure.failed("oversize input accepted") }
    101     catch Error.CommandInput(let field, let kind) { try check(field == "listing_input" && kind == .limitExceeded, "typed shared bound") }
    102     let otherHost = try await Host.open(seller: false, unknownSigning: false, pauseAfterSigning: false)
    103     let other = otherHost.session(); _ = try await other.client.start(mode: .online)
    104     do {
    105         _ = try await session.client.inquire(workspace: other.workspace, request: request(host, "13"), input: input)
    106         throw SmokeFailure.failed("foreign scope accepted")
    107     } catch Error.Operation(_, _, let operation, let admission, let rejected) {
    108         try check(rejected == nil, "foreign admission has no signer diagnostic")
    109         try check(operation == String(repeating: "13", count: 32) && admission == .notAdmitted, "retained safe error context")
    110     }
    111     try check(try host.measurements().signingCalls == before.signingCalls, "refusal has no signature")
    112     try check(try otherHost.measurements().signingCalls == "0", "foreign host unused")
    113     session.workspace.close()
    114     do {
    115         _ = try await session.client.inquire(workspace: session.workspace, request: request(host, "16"), input: input)
    116         throw SmokeFailure.failed("closed attachment accepted")
    117     } catch Error.Operation(_, _, _, let admission, let rejected) {
    118         try check(rejected == nil, "closed admission has no signer diagnostic")
    119         try check(admission == .notAdmitted, "actual attachment close releases authority")
    120     }
    121     try check(try host.measurements().signingCalls == before.signingCalls, "closed scope has no signature")
    122     try await close(otherHost, other); try await close(host, session)
    123 }
    124 
    125 func unknownFlow() async throws {
    126     let host = try await Host.open(seller: true, unknownSigning: true, pauseAfterSigning: false)
    127     let session = host.session(); _ = try await session.client.start(mode: .online)
    128     let result = try await session.client.publishListing(workspace: session.workspace, request: request(host, "14"), input: listing(host, "14"))
    129     try check(result.issuance == .unknown && result.businessResult == nil, "unknown result remains explicit")
    130     try await session.client.close(); host.setUnknownSigning(unknown: false)
    131     let next = try await host.reopen(); _ = try await next.client.start(mode: .online)
    132     let resumed = try await next.client.resume(workspace: next.workspace, operationId: result.operationId, expectedDigest: result.commandDigest)
    133     try check(resumed.issuance == .unknown && resumed.businessResult == nil, "reopen cannot turn uncertainty into permission")
    134     let measured = try host.measurements(); try check(measured.signingCalls == "1" && measured.originalSignedEvents.isEmpty, "no repeated invocation")
    135     try await close(host, next)
    136 }
    137 
    138 func cancelledObservers() async throws {
    139     let host = try await Host.open(seller: true, unknownSigning: false, pauseAfterSigning: true)
    140     let session = host.session(); _ = try await session.client.start(mode: .online)
    141     let context = try request(host, "15"); let input = try listing(host, "15")
    142     let observer = Task { try await session.client.publishListing(workspace: session.workspace, request: context, input: input) }
    143     try await host.waitUntilSignerPaused()
    144     for _ in 0..<2 {
    145         let safe = await withTaskGroup(of: Bool.self) { group in
    146             for index in 0..<16 {
    147                 group.addTask {
    148                     let query = Task { try await session.client.operation(workspace: session.workspace, operationId: context.operationId, expectedDigest: nil) }
    149                     if index % 2 == 0 { await Task.yield() }
    150                     query.cancel()
    151                     do { _ = try await query.value; return true }
    152                     catch is CancellationError { return true }
    153                     catch { return false }
    154                 }
    155             }
    156             var accepted = true
    157             for await outcome in group { accepted = accepted && outcome }
    158             return accepted
    159         }
    160         try check(safe, "cancel/completion race preserves safe future lifetime")
    161     }
    162     observer.cancel(); _ = await observer.result
    163     let closing = Task { try await session.client.close() }
    164     for _ in 0..<200 where session.client.state() != .closing { try await Task.sleep(nanoseconds: 5_000_000) }
    165     try check(session.client.state() == .closing, "close owns pending produced signature")
    166     closing.cancel(); _ = await closing.result; host.releaseSigner(); try await session.client.close()
    167     let next = try await host.reopen(); _ = try await next.client.start(mode: .online)
    168     let recovered = try await next.client.resume(workspace: next.workspace, operationId: context.operationId, expectedDigest: nil)
    169     try check(recovered.issuance == .obtained && recovered.businessInstallation == .installed, "actual obtained result recovered")
    170     try check(try host.measurements().signingCalls == "1", "observer loss never resigns")
    171     try await close(host, next)
    172 }
    173 
    174 
    175 func rejectedSignerFlow() async throws {
    176     let cases: [(FixtureRejection, SignerRejectionReason, String?, String?, String?)] = [
    177         (.malformed, .invalidArtifact, String("synthetic private rejection canary".utf8.count), String("synthetic private rejection canary".utf8.count), "ba883ea08dff4c078672a055dd2be042d9debb5b22c66527e4499c068011879d"),
    178         (.oversized, .tooLarge, "65536", "65537", "d2d5af5c0316f5c2b119635386239edc87abce035f851c3f6ee127e6c3cbf435"),
    179         (.foreign, .bindingMismatch, nil, nil, nil)
    180     ]
    181     for (mode, reason, covered, total, digest) in cases {
    182         let host = try await Host.open(seller: true, unknownSigning: false, pauseAfterSigning: false)
    183         host.setRejectedSigning(mode: mode)
    184         let session = host.session(); _ = try await session.client.start(mode: .online)
    185         let context = try request(host, "18")
    186         do {
    187             _ = try await session.client.publishListing(workspace: session.workspace, request: context, input: listing(host, "18"))
    188             throw SmokeFailure.failed("rejected signer accepted")
    189         } catch Error.Operation(let code, let retry, let operation, let admission, let diagnostic) {
    190             try check(code == "signer_tampering" && retry == "manual_reconciliation", "original rejection code/retry")
    191             try check(operation == context.operationId && admission == .confirmed, "original confirmed command")
    192             guard let diagnostic else { throw SmokeFailure.failed("lost bounded signer metadata") }
    193             try check(diagnostic.reason == reason, "fixed rejection reason")
    194             if let fingerprint = diagnostic.fingerprint {
    195                 try check(fingerprint.coveredBytes == covered && fingerprint.totalBytes == total, "exact prefix coverage")
    196                 try check(fingerprint.sha256.count == 32, "bounded SHA-256")
    197                 let actual = fingerprint.sha256.map { String(format: "%02x", $0) }.joined()
    198                 try check(actual == digest, "actual original prefix hash")
    199             } else {
    200                 try check(digest == nil, "no fabricated/missing fingerprint")
    201             }
    202         }
    203         let facts = try await session.client.operation(workspace: session.workspace, operationId: context.operationId, expectedDigest: nil)
    204         try check(facts?.businessInstallation == .notInstalled, "rejection is no business success")
    205         let measured = try host.measurements()
    206         try check(measured.signingCalls == "1" && measured.legacySigningCalls == "0" && measured.originalSignedEvents.isEmpty, "no signature or legacy fallback")
    207         try await close(host, session)
    208     }
    209 }
    210 
    211 
    212 @main enum NativeSmoke {
    213     static func main() async throws {
    214         if CommandLine.arguments.contains("--plain-panic") { _ = fixturePanicProbe(); throw SmokeFailure.failed("plain panic returned") }
    215         var resultPanicCaught = false
    216         do { _ = try fixtureResultPanicProbe() } catch { resultPanicCaught = true }
    217         try check(resultPanicCaught, "actual Result panic boundary")
    218         let host = try await Host.open(seller: false, unknownSigning: false, pauseAfterSigning: false)
    219         let session = host.session()
    220         let alreadyCancelled = Task {
    221             do { try await Task.sleep(nanoseconds: 5_000_000_000) } catch {}
    222             return try await session.client.start(mode: .online)
    223         }
    224         alreadyCancelled.cancel()
    225         do { _ = try await alreadyCancelled.value; throw SmokeFailure.failed("already cancelled call started") }
    226         catch is CancellationError {}
    227         try check(session.client.state() == .ready, "already cancelled binding call has no host effect")
    228         try await close(host, session)
    229         trace("swift already-cancelled call passed")
    230         try await publicFlow(); trace("swift public workflow passed")
    231         try await privateFlowAndErrors(); trace("swift private workflow passed")
    232         try await unknownFlow(); trace("swift unknown workflow passed")
    233         try await cancelledObservers(); trace("swift cancellation workflow passed")
    234         try await rejectedSignerFlow(); trace("swift bounded rejection workflow passed")
    235         print("{\"language\":\"swift\",\"state\":\"passed\",\"actual_workflows\":5,\"result_panic_caught\":true}")
    236     }
    237 }