I am working with Salesforce Connect and I am storing my token and expiration times in an encrypted custom setting. My connection is through the client credentials Oauth 2 flow.
When a user queries an external object, it makes sense to me in the initial method of salesforce connect DataSource.Connection class to:
Update the custom settings fields if there is no information or the token has expired.
Use the custom settings to get the access token if the token has not expired.
This would be fine, however within the same transaction, in the query method of the DataSource.Connection class, webservice callouts to fetch the external objects with the newly updated token must occur. This results in an "uncommitted work pending" error as we would expect because webservice callouts cannot be made after DML statements.
Future methods don't seem to be a plausible solution here because if the token is expired I need those custom settings to be updated at that time otherwise the rest callout will fail.
I thought calling a new instance of another class with a method to update the custom setting might be considered a new transactions, but my assumption was wrong.
I could have users request a token every rest call and store them within the class and not within the custom setting, but that seems so absurdly excessive where as the custom setting would allow multiple users to utilize the same token and only make a token callout when necessary since it's a client connection anyways.