Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix invalid token (in parallel requests) #9

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

EnzoD86
Copy link

@EnzoD86 EnzoD86 commented Jul 26, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant