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

evalResourceT :: ResourceT m a -> m (a, IO ()) to defer cleanup to the user #516

Open
parsonsmatt opened this issue Dec 13, 2024 · 0 comments

Comments

@parsonsmatt
Copy link
Contributor

We're doing some moderately cursed things in our test suite to share some global test resources, and as a result, we can't use ResourceT or bracket for resource control. Instead, we have records with a data Res = Res { cleanup :: IO () } field, and we call them manually when exiting the process. This works alright, but there are still some cases where we want guarantees similar to what ResourceT can provide.

An idea that I had was to use ResourceT but change the way we run the type:

evalResourceT :: MonadUnliftIO m => ResourceT m a -> m (a, IO ())
evalResourceT (ResourceT r) = withRunInIO $ \run -> do
    istate <- createInternalState
    E.mask $ \restore -> do
        res <- restore (run (r istate)) `E.catch` \e -> do
            stateCleanupChecked (Just e) istate
            E.throwIO e
        
        return (res, stateCleanupChecked Nothing istate)

Instead of calling stateCleanupChecked Nothing istate), we just return the IO action that does that. This should allow us to define resources in an exception-safe way, and then relinquish the resources when we're ready or able to do so outside of the block.

If we end up going with this, I'd be happy to try and upstream it, but I thought I'd write an issue just in case anyone else thought of it.

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