Ensuring exclusive access to a function in structured concurrency

So our back end manages tokens in a strange way.

Whenever we try to request a new access token using our refresh token, it invalidates our old refresh token and returns us with a new access + refresh token.

The problem with this is that multiple concurrent network requests can see that a user's access token has expired and try to get a new access token, potentially causing us to get a 401 unauthorized error.

Is there any way with structured/unstructured concurrency to ensure that our method for grabbing the access token can only at max be run once at a time?

Im assuming the only realistic way would be to do something like this:

@MyGlobalActor private var tokenTask: Task<String, any Error>?

@MyGlobalActor func getAccessToken() async await -> String {
    if let tokenTask {
        return try await tokenTask.value
    }

    self.tokenTask = Task<String, any Error> {
        // refresh access token
    }

   let token = try await self.tokenTask!.value
   self.tokenTask = nil       

   return token
}
Is there any way with structured/unstructured concurrency to ensure that our method for grabbing the access token can only at max be run once at a time?

There are a variety of different ways that you can approach this but, honestly, the code in your example seems reasonable to me.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Ensuring exclusive access to a function in structured concurrency
 
 
Q