diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift index 19cec7a9e48..34269d26f1b 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/FFI/PlatformQueryExtensions.swift @@ -217,21 +217,15 @@ extension SDK { // MARK: - Identity Queries /// Get an identity by ID - @MainActor - public func identityGet(identityId: String) async throws -> [String: Any] { - print("🔵 SDK.identityGet: Called with ID: \(identityId)") - - guard let sdkHandle = handle else { - print("❌ SDK.identityGet: SDK handle is nil") - throw SDKError.invalidState("SDK not initialized") + /// + /// `nonisolated`: the fetch blocks on the network inside Rust, so it runs + /// on the shared Platform query queue (see ``performBlockingQuery(_:)``) + /// instead of on the caller's actor. + public nonisolated func identityGet(identityId: String) async throws -> sending [String: Any] { + let json = try await performBlockingQuery { handle in + try Self.consumeStringResult(dash_sdk_identity_fetch(handle, identityId)) } - - print("🔵 SDK.identityGet: SDK handle exists: \(sdkHandle)") - print("🔵 SDK.identityGet: About to call dash_sdk_identity_fetch with handle and ID: \(identityId)") - - // Make the FFI call directly and return the parsed JSON - let result = dash_sdk_identity_fetch(sdkHandle, identityId) - return try processJSONResult(result) + return try Self.parseJSONObject(json) } /// Get identity keys @@ -1124,16 +1118,23 @@ extension SDK { // MARK: - DPNS Queries /// Get DPNS usernames for identity - @MainActor - public func dpnsGetUsername(identityId: String, limit: UInt32?) async throws -> [[String: Any]] { - guard let handle = handle else { - throw SDKError.invalidState("SDK not initialized") + /// + /// `nonisolated`: the lookup blocks on the network inside Rust, so it runs + /// on the shared Platform query queue (see ``performBlockingQuery(_:)``) + /// instead of on the caller's actor. + public nonisolated func dpnsGetUsername(identityId: String, limit: UInt32?) async throws -> sending [[String: Any]] { + let json: String? = try await performBlockingQuery { handle in + let result = dash_sdk_dpns_get_usernames(handle, identityId, limit ?? 10) + // No data and no error means no usernames. + if result.error == nil && result.data == nil { + return nil + } + return try Self.consumeStringResult(result) } - - // Call native FFI function with identity ID as string - let result = dash_sdk_dpns_get_usernames(handle, identityId, limit ?? 10) - - return try processJSONArrayResult(result) + guard let json else { + return [] + } + return try Self.parseJSONArray(json) } /// Check DPNS name availability @@ -2425,4 +2426,13 @@ extension SDK { } return object } + + /// Parse a JSON array payload returned by a query. + fileprivate nonisolated static func parseJSONArray(_ json: String) throws -> sending [[String: Any]] { + guard let data = json.data(using: .utf8), + let array = try? JSONSerialization.jsonObject(with: data) as? [[String: Any]] else { + throw SDKError.serializationError("Failed to parse JSON array") + } + return array + } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift index 9a58b42448a..2ae4aa4681f 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/PlatformQueryOffMainTests.swift @@ -1,4 +1,5 @@ import Foundation +import os import XCTest @testable import SwiftDashSDK @@ -45,6 +46,61 @@ final class PlatformQueryOffMainTests: XCTestCase { XCTAssertTrue(released, "the parked query was not released by the main actor") } + private struct MainHoldError: Error, CustomStringConvertible { + let message: String + var description: String { message } + } + + /// `identityGet` and `dpnsGetUsername` make their FFI call without the + /// main actor: the main thread is held for the whole of both calls, and + /// each still returns (with the mock's missing-expectation error) before it + /// is released. A call that needed the main actor would wait until the hold + /// timed out. + func testIdentityReadsDoNotNeedTheMainActor() async throws { + let sdk = try SDK(mockVectorsDirectory: nil) + let mainHeld = DispatchSemaphore(value: 0) + let releaseMain = DispatchSemaphore(value: 0) + let holdTimedOut = OSAllocatedUnfairLock(initialState: false) + + DispatchQueue.main.async { + mainHeld.signal() + if releaseMain.wait(timeout: .now() + 5) == .timedOut { + holdTimedOut.withLock { $0 = true } + } + } + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + DispatchQueue.global().async { + if mainHeld.wait(timeout: .now() + 5) == .timedOut { + releaseMain.signal() + continuation.resume( + throwing: MainHoldError(message: "the main queue never ran the hold")) + } else { + continuation.resume() + } + } + } + + do { + _ = try await sdk.identityGet(identityId: "5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk") + XCTFail("identityGet should fail without recorded responses") + } catch SDKError.invalidState { + XCTFail("identityGet must reach the FFI, not fail on an unavailable SDK handle") + } catch {} + + do { + _ = try await sdk.dpnsGetUsername( + identityId: "5DbLwAxGBzUzo81VewMUwn4b5P4bpv9FNFybi25XB5Bk", limit: 1) + XCTFail("dpnsGetUsername should fail without recorded responses") + } catch SDKError.invalidState { + XCTFail("dpnsGetUsername must reach the FFI, not fail on an unavailable SDK handle") + } catch {} + + let returnedWhileMainWasHeld = !holdTimedOut.withLock { $0 } + releaseMain.signal() + XCTAssertTrue( + returnedWhileMainWasHeld, "an identity read waited for the main actor") + } + /// The off-main entry points marshal their arguments, make the FFI call and /// surface its error from a main-actor caller. The mock has no recorded /// responses, so each one must fail rather than return data.