Skip to content

Commit a274967

Browse files
feat(docs): add sample for chat app
1 parent 2588c31 commit a274967

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+1698
-122
lines changed

AtalaPrismSDK/Castor/Sources/CastorImpl+Public.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ extension CastorImpl: Castor {
8989
/// - Returns: The DID Document associated with the DID
9090
/// - Throws: An error if the DID is invalid or the document cannot be retrieved
9191
public func resolveDID(did: DID) async throws -> DIDDocument {
92-
logger.info(message: "Trying to resolve DID", metadata: [
92+
logger.debug(message: "Trying to resolve DID", metadata: [
9393
.maskedMetadataByLevel(key: "DID", value: did.string, level: .debug)
9494
])
9595

AtalaPrismSDK/Domain/Sources/BBs/Mercury.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ public protocol Mercury {
2222
/// - Returns: The response data
2323
/// - Throws: An error if the message is invalid or the send operation fails
2424
@discardableResult
25-
func sendMessage(msg: Message) async throws -> Data?
25+
func sendMessage(_ msg: Message) async throws -> Data?
2626

2727
/// sendMessageParseMessage asynchronously sends a given message and returns the response message object. This function may throw an error if the message is invalid, the send operation fails, or the response message is invalid.
2828
///

AtalaPrismSDK/Domain/Sources/Models/Errors.swift

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,8 @@ public enum UnknownError: UnknownPrismError {
8181
return errors
8282
}
8383
}
84+
85+
public var errorDescription: String? { message }
8486
}
8587

8688
extension UnknownError: Equatable {
@@ -143,6 +145,10 @@ public enum CommonError: KnownPrismError {
143145
return message
144146
}
145147
}
148+
149+
public var description: String {
150+
"Code \(code): \(message)"
151+
}
146152
}
147153

148154
extension CommonError: Equatable {
@@ -377,14 +383,7 @@ public enum MercuryError: KnownPrismError {
377383

378384
/// An error case representing invalid body data in a message.
379385
case messageInvalidBodyDataError
380-
381-
/**
382-
An error case representing a DIDComm error.
383-
384-
- Parameters:
385-
- msg: The message describing the error.
386-
*/
387-
case didcommError(msg: String)
386+
case didcommError(msg: String, underlyingErrors: [Error]? = nil)
388387

389388
/// The error code returned by the server.
390389
public var code: Int {
@@ -427,8 +426,11 @@ public enum MercuryError: KnownPrismError {
427426
return "While decoding a message, a message attachment was found without \"id\" this is invalid"
428427
case .messageInvalidBodyDataError:
429428
return "While decoding a message, a body was found to be invalid while decoding"
430-
case .didcommError(let msg):
431-
return "DIDComm error as ocurred with message: \(msg)"
429+
case let .didcommError(msg, errors):
430+
let errorsMessages = errors.map {
431+
"\n" + $0.map { $0.localizedDescription }.joined(separator: "\n")
432+
} ?? ""
433+
return "DIDComm error as ocurred with message: \(msg)\nErrors: \(errorsMessages)"
432434
}
433435
}
434436
}

AtalaPrismSDK/Domain/Sources/Models/MessageAttachment.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ public struct AttachmentDescriptor {
135135
/// - byteCount: The byte count associated with the attachment.
136136
/// - description: The description associated with the attachment.
137137
public init(
138-
id: String,
138+
id: String = UUID().uuidString,
139139
mediaType: String? = nil,
140140
data: AttachmentData,
141141
filename: [String]? = nil,

AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/DIDCommSecretsResolverWrapper.swift

Lines changed: 83 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -11,29 +11,26 @@ class DIDCommSecretsResolverWrapper {
1111
let pluto: Pluto
1212
let castor: Castor
1313
let logger: PrismLogger
14-
@Published var availableSecrets = [Domain.Secret]()
15-
var cancellables = [AnyCancellable]()
1614

1715
init(apollo: Apollo, pluto: Pluto, castor: Castor, logger: PrismLogger) {
1816
self.apollo = apollo
1917
self.pluto = pluto
2018
self.castor = castor
2119
self.logger = logger
22-
23-
startUpdating()
2420
}
2521

26-
private func startUpdating() {
27-
pluto
22+
fileprivate func getListOfAllSecrets() async throws -> [Domain.Secret] {
23+
try await pluto
2824
.getAllPeerDIDs()
29-
.tryMap { [weak self] in
25+
.first()
26+
.tryMap {
3027
try $0.map { did, privateKeys, _ in
31-
try self?.parsePrivateKeys(did: did, privateKeys: privateKeys)
28+
try self.parsePrivateKeys(did: did, privateKeys: privateKeys)
3229
}
3330
}
3431
.map { $0.compactMap { $0 }.flatMap { $0 } }
35-
.replaceError(with: [])
36-
.assign(to: &$availableSecrets)
32+
.first()
33+
.await()
3734
}
3835

3936
private func parsePrivateKeys(
@@ -68,45 +65,92 @@ extension DIDCommSecretsResolverWrapper: SecretsResolver {
6865
secretid: String,
6966
cb: OnGetSecretResult
7067
) -> ErrorCode {
71-
$availableSecrets
72-
.first()
73-
.map { $0.first { $0.id == secretid } }
74-
.sink { [weak self] in
75-
do {
76-
try cb.success(result: $0.map { DIDCommxSwift.Secret(from: $0) })
77-
} catch {
78-
self?.logger.error(message: "Could not find secret", metadata: [
79-
.publicMetadata(key: "SecretId", value: secretid),
80-
.publicMetadata(key: "Error", value: error.localizedDescription)
81-
])
82-
}
68+
Task {
69+
do {
70+
let secret = try await getListOfAllSecrets().first { $0.id == secretid }
71+
try cb.success(result: secret.map { DIDCommxSwift.Secret(from: $0) })
72+
} catch let error {
73+
let mercuryError = MercuryError.didcommError(
74+
msg: "Could not find secret \(secretid)",
75+
underlyingErrors: [error]
76+
)
77+
logger.error(error: mercuryError)
8378
}
84-
.store(in: &cancellables)
79+
}
80+
// getListOfAllSecrets()
81+
// .first()
82+
// .map {
83+
// $0.first { $0.id == secretid }
84+
// }
85+
// .sink { [weak self] in
86+
// do {
87+
// try cb.success(result: $0.map { DIDCommxSwift.Secret(from: $0) })
88+
// } catch {
89+
// self?.logger.error(message: "Could not find secret", metadata: [
90+
// .publicMetadata(key: "SecretId", value: secretid),
91+
// .publicMetadata(key: "Error", value: error.localizedDescription)
92+
// ])
93+
// }
94+
// }
95+
// .store(in: &cancellables)
8596
return .success
8697
}
8798

8899
func findSecrets(
89100
secretids: [String],
90101
cb: OnFindSecretsResult
91102
) -> ErrorCode {
92-
$availableSecrets
93-
.first()
94-
.map {
95-
$0
96-
.filter { secretids.contains($0.id) }
97-
.map { $0.id }
98-
}
99-
.sink { [weak self] in
100-
do {
101-
try cb.success(result: $0)
102-
} catch {
103-
self?.logger.error(message: "Could not find secrets", metadata: [
104-
.publicMetadata(key: "SecretsIds", value: secretids.description),
105-
.publicMetadata(key: "Error", value: error.localizedDescription)
106-
])
103+
Task {
104+
do {
105+
let secrets = try await getListOfAllSecrets()
106+
.filter { secretids.contains($0.id) }
107+
.map { $0.id }
108+
let secretsSet = Set(secretids)
109+
let resultsSet = Set(secrets)
110+
let missingSecrets = secretsSet.subtracting(resultsSet)
111+
if !missingSecrets.isEmpty {
112+
logger.error(message:
113+
"""
114+
Could not find secrets the following secrets:\(missingSecrets.joined(separator: ", "))
115+
"""
116+
)
107117
}
118+
try cb.success(result: secrets)
119+
} catch {
120+
let mercuryError = MercuryError.didcommError(
121+
msg: "Could not find secrets \(secretids.joined(separator: "\n"))",
122+
underlyingErrors: [error]
123+
)
124+
logger.error(error: mercuryError)
108125
}
109-
.store(in: &cancellables)
126+
}
127+
// getListOfAllSecrets()
128+
// .first()
129+
// .map {
130+
// $0
131+
// .filter { secretids.contains($0.id) }
132+
// .map { $0.id }
133+
// }
134+
// .sink { [weak self] in
135+
// do {
136+
// let secretsSet = Set(secretids)
137+
// let resultsSet = Set($0)
138+
// let missingSecrets = secretsSet.subtracting(resultsSet)
139+
// if !missingSecrets.isEmpty {
140+
// self?.logger.error(
141+
// message:
142+
//"""
143+
//Could not find secrets the following secrets:\(missingSecrets.joined(separator: ", "))
144+
//"""
145+
// )
146+
// }
147+
// try cb.success(result: $0)
148+
// } catch {
149+
// let error = MercuryError.didcommError(msg: error.localizedDescription)
150+
// self?.logger.error(error: error)
151+
// }
152+
// }
153+
// .store(in: &cancellables)
110154
return .success
111155
}
112156
}

AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/PackEncryptedOperation.swift

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,17 +7,19 @@ import Foundation
77
final class PackEncryptedOperation: OnPackEncryptedResult {
88
private let didcomm: DIDCommProtocol
99
private let logger: PrismLogger
10+
private let message: Domain.Message
1011
private var published = CurrentValueSubject<String?, Error>(nil)
1112
private var cancellable: AnyCancellable?
1213

13-
init(didcomm: DIDCommProtocol, logger: PrismLogger) {
14+
init(didcomm: DIDCommProtocol, message: Domain.Message, logger: PrismLogger) {
1415
self.didcomm = didcomm
1516
self.logger = logger
17+
self.message = message
1618
}
1719

18-
func packEncrypted(msg: Domain.Message) async throws -> String {
19-
guard let fromDID = msg.from else { throw MercuryError.noSenderDIDSetError }
20-
guard let toDID = msg.to else { throw MercuryError.noRecipientDIDSetError }
20+
func packEncrypted() async throws -> String {
21+
guard let fromDID = message.from else { throw MercuryError.noSenderDIDSetError }
22+
guard let toDID = message.to else { throw MercuryError.noRecipientDIDSetError }
2123

2224
let result: String = try await withCheckedThrowingContinuation { [weak self] continuation in
2325
guard let self else { return }
@@ -42,8 +44,9 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
4244
continuation.resume(returning: result)
4345
})
4446
do {
47+
print("Packing message \(message.piuri) sender:\(fromDID) \nto:\(toDID)")
4548
let status = didcomm.packEncrypted(
46-
msg: try DIDCommxSwift.Message(domain: msg, mediaType: .contentTypePlain),
49+
msg: try DIDCommxSwift.Message(domain: message, mediaType: .contentTypePlain),
4750
to: toDID.string,
4851
from: fromDID.string,
4952
signBy: nil,
@@ -65,7 +68,7 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
6568
msg: "Unknown error on initializing pack encrypted function"
6669
))
6770
}
68-
} catch let error {
71+
} catch {
6972
continuation.resume(throwing: MercuryError.didcommError(
7073
msg: "Error on parsing Domain message to DIDComm library model: \(error.localizedDescription)"
7174
))
@@ -80,19 +83,20 @@ final class PackEncryptedOperation: OnPackEncryptedResult {
8083
}
8184

8285
func error(err: DIDCommxSwift.ErrorKind, msg: String) {
86+
let error = MercuryError.didcommError(
87+
msg: """
88+
Error on trying to pack encrypted a message of type \(message.piuri): \(msg)
89+
"""
90+
)
8391
logger.error(
8492
message: "Packing message failed with error",
8593
metadata: [
8694
.publicMetadata(
8795
key: "Error",
88-
value: MercuryError
89-
.didcommError(msg: msg)
90-
.localizedDescription
96+
value: error.errorDescription ?? ""
9197
)
9298
]
9399
)
94-
published.send(completion: .failure(MercuryError.didcommError(
95-
msg: "Error on trying to pack encrypted a message: \(msg)"
96-
)))
100+
published.send(completion: .failure(error))
97101
}
98102
}

AtalaPrismSDK/Mercury/Sources/DIDCommWrappers/UnpackOperation.swift

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,22 +60,46 @@ final class UnpackOperation: OnUnpackResult {
6060
do {
6161
let message: Domain.Message = try result.toDomain(castor: castor)
6262
published.send(message)
63-
} catch {
63+
} catch let error as LocalizedError {
6464
logger.error(
6565
message: "Could not unpack message",
6666
metadata: [
6767
.publicMetadata(key: "Error", value: error.localizedDescription)
6868
]
6969
)
7070
published.send(completion: .failure(MercuryError.didcommError(
71-
msg: "Error on parsing DIDComm library model message to Domain message : \(error.localizedDescription)"
71+
msg:
72+
"""
73+
Error on parsing DIDComm library model message to Domain message : \(error.errorDescription ?? "")
74+
"""
75+
)))
76+
} catch {
77+
published.send(completion: .failure(MercuryError.didcommError(
78+
msg:
79+
"""
80+
Error on parsing DIDComm library model message to Domain message : \(error.localizedDescription)
81+
"""
7282
)))
7383
}
7484
}
7585

7686
func error(err: DIDCommxSwift.ErrorKind, msg: String) {
77-
published.send(completion: .failure(MercuryError.didcommError(
78-
msg: "Error on trying to unpack a message: \(msg)"
79-
)))
87+
print(err.localizedDescription)
88+
let error = MercuryError.didcommError(
89+
msg:
90+
"""
91+
Error on trying to unpack a message: \(msg)
92+
"""
93+
)
94+
logger.error(
95+
message: "Unpack message failed with error",
96+
metadata: [
97+
.publicMetadata(
98+
key: "Error",
99+
value: error.errorDescription ?? ""
100+
)
101+
]
102+
)
103+
published.send(completion: .failure(error))
80104
}
81105
}

0 commit comments

Comments
 (0)