Fix invalid token (in parallel requests) #9
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi, I'm working on a Home Assistant integration and I'm using TuyaOpenAPI inside the asynchronous code.
I initialize a client (TuyaOpenAPI) that is used by multiple entities that asynchronously make calls to the API servers.
During operation, the client works fine until it needs to refresh the token; only one of the N parallel calls manages to update it, while the others get an invalid token error.
After a long debugging, I found out that the problem is related to the token emptying in the token refresh function (__refresh_access_token_if_need) on line 147; the first request that does the token update, empties the old token and the other parallel requests find a request with the empty token.
I also realized that to generate the sign correctly the token must be empty (line 120).
After several attempts, I think I've found a possible fix/workaround that solves the problem.
The idea is to add a flag that is set to True when the first token refresh request is fired, preventing other parallel requests from requesting a token refresh.
While the token is being updated (by the first request), subsequent requests will use the old token (which is still valid because the token is updated one minute before it expires) which will then be updated by the first request when it gets the server's response and sets the flag to False.
After this change I have no more problems with invalid tokens.
I hope I was clear, but from the code you should be able to better understand what I explained.
Thank you