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

Make xrpc.Client thread-safe using RWMutex and Getters/Setters #924

Open
davhofer opened this issue Feb 1, 2025 · 0 comments
Open

Make xrpc.Client thread-safe using RWMutex and Getters/Setters #924

davhofer opened this issue Feb 1, 2025 · 0 comments

Comments

@davhofer
Copy link

davhofer commented Feb 1, 2025

Description

The fields of the Client in xrpc/xrpc.go are currently accessed directly for reads and writes. When using the client across multiple threads, this could lead to race conditions (e.g. when simultaneously updating the AuthInfo while also trying to make an API request). Thus it would be useful to have the option to access these fields (and generally, use the XRPC client) in a thread-safe manner.

The alternative of isolating the full interactions with the client in the caller code, e.g. wrapping every API call in a Lock()/Unlock(), would be very inefficient.

Implementation

Since many tools and applications use the XRPC client, but most of them do not require this thread-safe access, it would probably be a good idea to let them interact with the client the same way as before, while providing an opt-in alternative for multithreaded applications.

One option would be to leave the fields as they are, public, but add a single RWMutex and additional getters and setters for the all client fields, which lock the mutex when accessing the field. Furthermore, all the client field accesses in func (c *Client) Do(...) error {} would be replaced with the getters & setters.
Then any code using the Client could easily use the same client across different threads while using the thread-safe getters and setters to access the fields, making API calls, updating auth tokens, etc.
And applications that don't require this can just use the client as before.

This is the implementation I currently use in my fork. I am happy to provide a PR if you think this is a good solution.

There could of course be other ways of doing this, the above seemed like a simple and flexible way to do it, but lmk if you have better ideas.

Example use case

An client application/bot could have various threads running that interact with the API/PDSes, e.g. event handlers/listeners for things like mentions, likes, etc., while also asynchronously update the auth tokens.

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

No branches or pull requests

1 participant