@@ -57,7 +57,6 @@ extension USBSmartCardConnection: SmartCardConnection {
57
57
58
58
// @TraceScope
59
59
public func close( error: Error ? ) async {
60
-
61
60
try ? await didClose. fulfill ( error)
62
61
trace ( message: " disconnect called on sessionManager " )
63
62
}
@@ -166,12 +165,10 @@ private final actor SmartCardConnectionsManager {
166
165
167
166
// @TraceScope
168
167
func connect( slot: SmartCardSlot ) async throws -> USBSmartCardConnection {
169
- // if there is already a connection for this slot...
170
- // we close it and create a new one reusing it's TKSmartCard
171
- if let state = connections [ slot] {
172
- // finish it
173
- await state. didClose. fulfill ( nil )
174
- connections [ slot] = nil
168
+ // if there is already a connection for this slot we throw `ConnectionError.busy`.
169
+ // The caller must close the connection first.
170
+ guard connections [ slot] == nil else {
171
+ throw ConnectionError . busy
175
172
}
176
173
177
174
// To proceed with a new connection we need to acquire a lock
@@ -201,8 +198,20 @@ private final actor SmartCardConnectionsManager {
201
198
}
202
199
trace ( message: " card.beginSession() succeded " )
203
200
204
- // create a new state and return a new connection
205
- connections [ slot] = ConnectionState ( card: card)
201
+ // create and save a new connection state
202
+ let state = ConnectionState ( card: card)
203
+ connections [ slot] = state
204
+
205
+ // register for the eventual clean up when the connection is closed
206
+ Task {
207
+ _ = try await state. didClose. value ( )
208
+ state. card. endSession ( )
209
+ if connections [ slot] === state {
210
+ connections [ slot] = nil
211
+ }
212
+ }
213
+
214
+ // return the newly established connection
206
215
return USBSmartCardConnection ( slot: slot)
207
216
}
208
217
0 commit comments