Skip to content

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

@parsonsmatt

Description

@parsonsmatt

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions