Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Foundation
import os
import XCTest

@testable import SwiftDashSDK
Expand Down Expand Up @@ -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<Void, Error>) 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 {}
Comment thread
romchornyi marked this conversation as resolved.
Resolved

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.
Expand Down
Loading