-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Scoped adopted callback registrations. All contexts participating in one C
-- operation share one native worker; group cancellation signals every callback
-- control and joins that worker before releasing any reference or buffer.
module Cometa.Internal.Runtime
  ( Runtime,
    Context,
    Buffer,
    Dispatch,
    withRuntime,
    withRetained,
    close,
    withOperation,
    withOperations,
    withBytes,
    copyBuffer,
    withOwnedBuffer,
    checkStatus,
    liveContexts,
  )
where

-- IMPORTS --------------------------------------------------------------------

import Cometa.Error (Error (..))
import qualified Cometa.Internal.Callback as Callback
import Cometa.Internal.Error (fromNativeFailure)
import qualified Cometa.Internal.FFI.Native as Status
import Cometa.Internal.FFI.Runtime (Buffer, Context)
import qualified Cometa.Internal.FFI.Runtime as FFI
import Cometa.Internal.Failure (NativeFailure (..))
import Cometa.Internal.Ownership (copyStaticText)
import Control.Concurrent (forkFinally, newEmptyMVar, putMVar, readMVar)
import Control.Concurrent.MVar (MVar, newMVar, takeMVar, tryTakeMVar)
import Control.Exception (SomeException, bracket, catch, evaluate, finally, getMaskingState, mask, mask_, onException, throwIO, uninterruptibleMask_)
import Control.Monad (forM, forM_, when)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import Data.Maybe (catMaybes, listToMaybe)
import Data.Text (Text)
import Data.Word (Word32, Word8)
import Foreign.C.Types (CSize)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (Ptr, castPtr, freeHaskellFunPtr, nullPtr)
import Foreign.StablePtr (deRefStablePtr, freeStablePtr, newStablePtr)
import Foreign.Storable (peek, poke)

-- TYPES ----------------------------------------------------------------------

-- | Families own operation identifiers and the complete request/reply schema.
type Dispatch = Word32 -> ByteString -> IO (Either Error ByteString)

data Shared = Shared (MVar ()) Callback.CallbackControl (IORef (Maybe Error))

data Runtime = Runtime (IORef (Maybe (Ptr Context))) Shared

data State = State Dispatch Callback.CallbackControl (IORef (Maybe Error))

-- DEFINITIONS ----------------------------------------------------------------

-- | Success adopts callback handles in C; failure leaves cleanup with Haskell.
-- Continuation cleanup waits until every operation using this handle has joined.
withRuntime :: Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
withRuntime :: forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
withRuntime Dispatch
dispatch Runtime -> IO (Either Error a)
action = ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO (Either Error a))
 -> IO (Either Error a))
-> ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
  Either Error Runtime
acquired <- Dispatch -> IO (Either Error Runtime)
acquire Dispatch
dispatch
  case Either Error Runtime
acquired of
    Left Error
failure -> Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error a
forall a b. a -> Either a b
Left Error
failure)
    Right Runtime
runtime -> IO (Either Error a) -> IO (Either Error a)
forall a. IO a -> IO a
restore (Runtime -> IO (Either Error a)
action Runtime
runtime) IO (Either Error a) -> IO () -> IO (Either Error a)
forall a b. IO a -> IO b -> IO a
`finally` Runtime -> IO ()
closeWaiting Runtime
runtime

-- | An alias owns an independent reference but shares callback operation state.
-- Acquisition during an active operation fails fast instead of racing refcounts.
withRetained :: Runtime -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
withRetained :: forall a.
Runtime -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
withRetained Runtime
original Runtime -> IO (Either Error a)
action = ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO (Either Error a))
 -> IO (Either Error a))
-> ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
  Either Error Runtime
acquired <- Runtime -> IO (Either Error Runtime)
retain Runtime
original
  case Either Error Runtime
acquired of
    Left Error
failure -> Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error a
forall a b. a -> Either a b
Left Error
failure)
    Right Runtime
alias -> IO (Either Error a) -> IO (Either Error a)
forall a. IO a -> IO a
restore (Runtime -> IO (Either Error a)
action Runtime
alias) IO (Either Error a) -> IO () -> IO (Either Error a)
forall a b. IO a -> IO b -> IO a
`finally` Runtime -> IO ()
closeWaiting Runtime
alias

acquire :: Dispatch -> IO (Either Error Runtime)
acquire :: Dispatch -> IO (Either Error Runtime)
acquire Dispatch
dispatch = do
  CallbackControl
control <- IO CallbackControl
Callback.newCallbackControl
  IORef (Maybe Error)
expected <- Maybe Error -> IO (IORef (Maybe Error))
forall a. a -> IO (IORef a)
newIORef Maybe Error
forall a. Maybe a
Nothing
  MVar ()
gate <- () -> IO (MVar ())
forall a. a -> IO (MVar a)
newMVar ()
  StablePtr State
stable <- State -> IO (StablePtr State)
forall a. a -> IO (StablePtr a)
newStablePtr (Dispatch -> CallbackControl -> IORef (Maybe Error) -> State
State Dispatch
dispatch CallbackControl
control IORef (Maybe Error)
expected)
  FunPtr (Callback State)
fun <- Callback State -> IO (FunPtr (Callback State))
forall state. Callback state -> IO (FunPtr (Callback state))
FFI.wrapCallback Callback State
callback IO (FunPtr (Callback State))
-> IO () -> IO (FunPtr (Callback State))
forall a b. IO a -> IO b -> IO a
`onException` StablePtr State -> IO ()
forall a. StablePtr a -> IO ()
freeStablePtr StablePtr State
stable
  let freeRegistration :: IO ()
freeRegistration = FunPtr (Callback State) -> IO ()
forall a. FunPtr a -> IO ()
freeHaskellFunPtr FunPtr (Callback State)
fun IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> StablePtr State -> IO ()
forall a. StablePtr a -> IO ()
freeStablePtr StablePtr State
stable
  (Ptr (Ptr Context) -> IO (Either Error Runtime))
-> IO (Either Error Runtime)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Context) -> IO (Either Error Runtime))
 -> IO (Either Error Runtime))
-> (Ptr (Ptr Context) -> IO (Either Error Runtime))
-> IO (Either Error Runtime)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Context)
slot -> do
    Ptr (Ptr Context) -> Ptr Context -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Context)
slot Ptr Context
forall a. Ptr a
nullPtr
    Either Error ()
result <- Text -> NativeCode -> IO (Either Error ())
checkStatus Text
"runtime.acquire" (NativeCode -> IO (Either Error ()))
-> IO NativeCode -> IO (Either Error ())
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< (StablePtr State
-> FunPtr (Callback State) -> Ptr (Ptr Context) -> IO NativeCode
forall state.
StablePtr state
-> FunPtr (Callback state) -> Ptr (Ptr Context) -> IO NativeCode
FFI.cNew StablePtr State
stable FunPtr (Callback State)
fun Ptr (Ptr Context)
slot IO NativeCode -> IO () -> IO NativeCode
forall a b. IO a -> IO b -> IO a
`onException` IO ()
freeRegistration)
    case Either Error ()
result of
      Left Error
failure -> IO ()
freeRegistration IO () -> IO (Either Error Runtime) -> IO (Either Error Runtime)
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either Error Runtime -> IO (Either Error Runtime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Runtime
forall a b. a -> Either a b
Left Error
failure)
      Right () -> do
        Ptr Context
pointer <- Ptr (Ptr Context) -> IO (Ptr Context)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Context)
slot
        if Ptr Context
pointer Ptr Context -> Ptr Context -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Context
forall a. Ptr a
nullPtr
          then IO ()
freeRegistration IO () -> IO (Either Error Runtime) -> IO (Either Error Runtime)
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either Error Runtime -> IO (Either Error Runtime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Runtime
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"runtime.acquire"))
          else (do IORef (Maybe (Ptr Context))
handle <- Maybe (Ptr Context) -> IO (IORef (Maybe (Ptr Context)))
forall a. a -> IO (IORef a)
newIORef (Ptr Context -> Maybe (Ptr Context)
forall a. a -> Maybe a
Just Ptr Context
pointer); Either Error Runtime -> IO (Either Error Runtime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Runtime -> Either Error Runtime
forall a b. b -> Either a b
Right (IORef (Maybe (Ptr Context)) -> Shared -> Runtime
Runtime IORef (Maybe (Ptr Context))
handle (MVar () -> CallbackControl -> IORef (Maybe Error) -> Shared
Shared MVar ()
gate CallbackControl
control IORef (Maybe Error)
expected)))) IO (Either Error Runtime) -> IO () -> IO (Either Error Runtime)
forall a b. IO a -> IO b -> IO a
`onException` Ptr Context -> IO ()
FFI.cRelease Ptr Context
pointer

retain :: Runtime -> IO (Either Error Runtime)
retain :: Runtime -> IO (Either Error Runtime)
retain (Runtime IORef (Maybe (Ptr Context))
handle shared :: Shared
shared@(Shared MVar ()
gate CallbackControl
_ IORef (Maybe Error)
_)) = do
  Maybe ()
entered <- MVar () -> IO (Maybe ())
forall a. MVar a -> IO (Maybe a)
tryTakeMVar MVar ()
gate
  case Maybe ()
entered of
    Maybe ()
Nothing -> Either Error Runtime -> IO (Either Error Runtime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Runtime
forall a b. a -> Either a b
Left Error
RuntimeBusy)
    Just () ->
      ( do
          Maybe (Ptr Context)
current <- IORef (Maybe (Ptr Context)) -> IO (Maybe (Ptr Context))
forall a. IORef a -> IO a
readIORef IORef (Maybe (Ptr Context))
handle
          case Maybe (Ptr Context)
current of
            Maybe (Ptr Context)
Nothing -> Either Error Runtime -> IO (Either Error Runtime)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Runtime
forall a b. a -> Either a b
Left Error
RuntimeClosed)
            Just Ptr Context
pointer -> do
              Ptr Context -> IO ()
FFI.cRef Ptr Context
pointer
              (Runtime -> Either Error Runtime
forall a b. b -> Either a b
Right (Runtime -> Either Error Runtime)
-> (IORef (Maybe (Ptr Context)) -> Runtime)
-> IORef (Maybe (Ptr Context))
-> Either Error Runtime
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (IORef (Maybe (Ptr Context)) -> Shared -> Runtime
`Runtime` Shared
shared) (IORef (Maybe (Ptr Context)) -> Either Error Runtime)
-> IO (IORef (Maybe (Ptr Context))) -> IO (Either Error Runtime)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Ptr Context) -> IO (IORef (Maybe (Ptr Context)))
forall a. a -> IO (IORef a)
newIORef (Ptr Context -> Maybe (Ptr Context)
forall a. a -> Maybe a
Just Ptr Context
pointer)) IO (Either Error Runtime) -> IO () -> IO (Either Error Runtime)
forall a b. IO a -> IO b -> IO a
`onException` Ptr Context -> IO ()
FFI.cRelease Ptr Context
pointer
      )
        IO (Either Error Runtime) -> IO () -> IO (Either Error Runtime)
forall a b. IO a -> IO b -> IO a
`finally` MVar () -> () -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar ()
gate ()

-- | Closing while active returns busy. Scope cleanup waits instead. This rule
-- serializes native non-atomic reference transitions, including factory adoption.
close :: Runtime -> IO (Either Error ())
close :: Runtime -> IO (Either Error ())
close runtime :: Runtime
runtime@(Runtime IORef (Maybe (Ptr Context))
_ (Shared MVar ()
gate CallbackControl
_ IORef (Maybe Error)
_)) = IO (Either Error ()) -> IO (Either Error ())
forall a. IO a -> IO a
mask_ (IO (Either Error ()) -> IO (Either Error ()))
-> IO (Either Error ()) -> IO (Either Error ())
forall a b. (a -> b) -> a -> b
$ do
  Maybe ()
entered <- MVar () -> IO (Maybe ())
forall a. MVar a -> IO (Maybe a)
tryTakeMVar MVar ()
gate
  case Maybe ()
entered of
    Maybe ()
Nothing -> Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ()
forall a b. a -> Either a b
Left Error
RuntimeBusy)
    Just () -> (Runtime -> IO ()
releaseHandle Runtime
runtime IO () -> IO (Either Error ()) -> IO (Either Error ())
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either Error ()
forall a b. b -> Either a b
Right ())) IO (Either Error ()) -> IO () -> IO (Either Error ())
forall a b. IO a -> IO b -> IO a
`finally` MVar () -> () -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar ()
gate ()

closeWaiting :: Runtime -> IO ()
closeWaiting :: Runtime -> IO ()
closeWaiting runtime :: Runtime
runtime@(Runtime IORef (Maybe (Ptr Context))
_ (Shared MVar ()
gate CallbackControl
_ IORef (Maybe Error)
_)) = IO () -> IO ()
forall a. IO a -> IO a
uninterruptibleMask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  MVar () -> IO ()
forall a. MVar a -> IO a
takeMVar MVar ()
gate
  Runtime -> IO ()
releaseHandle Runtime
runtime IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` MVar () -> () -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar ()
gate ()

releaseHandle :: Runtime -> IO ()
releaseHandle :: Runtime -> IO ()
releaseHandle (Runtime IORef (Maybe (Ptr Context))
handle Shared
_) = do
  Maybe (Ptr Context)
current <- IORef (Maybe (Ptr Context)) -> IO (Maybe (Ptr Context))
forall a. IORef a -> IO a
readIORef IORef (Maybe (Ptr Context))
handle
  IORef (Maybe (Ptr Context)) -> Maybe (Ptr Context) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe (Ptr Context))
handle Maybe (Ptr Context)
forall a. Maybe a
Nothing
  IO () -> (Ptr Context -> IO ()) -> Maybe (Ptr Context) -> IO ()
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (() -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()) Ptr Context -> IO ()
FFI.cRelease Maybe (Ptr Context)
current

-- | One context is the one-element grouped operation, never a nested worker.
withOperation :: Runtime -> (Ptr Context -> IO (Either Error a)) -> IO (Either Error a)
withOperation :: forall a.
Runtime
-> (Ptr Context -> IO (Either Error a)) -> IO (Either Error a)
withOperation Runtime
runtime Ptr Context -> IO (Either Error a)
action = [Runtime]
-> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
forall a.
[Runtime]
-> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
withOperations [Runtime
runtime] (([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a))
-> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \case
  [Ptr Context
pointer] -> Ptr Context -> IO (Either Error a)
action Ptr Context
pointer
  [Ptr Context]
_ -> Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error a
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"runtime.withOperation"))

-- | Acquire unique gates without blocking, then retain all input handles.
-- Repeated aliases share one callback control. A busy/closed member runs no C.
-- Factories and native owner cleanup must stay inside the supplied operation.
withOperations :: [Runtime] -> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
withOperations :: forall a.
[Runtime]
-> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
withOperations [Runtime]
runtimes [Ptr Context] -> IO (Either Error a)
action = do
  -- Force the supplied list and abstract handle constructors before acquiring
  -- any gates; a lazy group argument must not strand an ownership obligation.
  (Runtime -> IO Runtime) -> [Runtime] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Runtime -> IO Runtime
forall a. a -> IO a
evaluate [Runtime]
runtimes
  MaskingState
masking <- IO MaskingState
getMaskingState
  ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall b. ((forall a. IO a -> IO a) -> IO b) -> IO b
mask (((forall a. IO a -> IO a) -> IO (Either Error a))
 -> IO (Either Error a))
-> ((forall a. IO a -> IO a) -> IO (Either Error a))
-> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ \forall a. IO a -> IO a
restore -> do
    Either Error ([Ptr Context], [Shared])
acquired <- [Runtime] -> IO (Either Error ([Ptr Context], [Shared]))
acquireGroup [Runtime]
runtimes
    case Either Error ([Ptr Context], [Shared])
acquired of
      Left Error
failure -> Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error a
forall a b. a -> Either a b
Left Error
failure)
      Right ([Ptr Context]
pointers, [Shared]
shared) ->
        ( do
            [Shared] -> (Shared -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Shared]
shared ((Shared -> IO ()) -> IO ()) -> (Shared -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \(Shared MVar ()
_ CallbackControl
control IORef (Maybe Error)
expected) -> IORef (Maybe Error) -> Maybe Error -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe Error)
expected Maybe Error
forall a. Maybe a
Nothing IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> CallbackControl -> MaskingState -> IO ()
Callback.beginCallbackOperation CallbackControl
control MaskingState
masking
            MVar (Either SomeException (Either Error a))
finished <- IO (MVar (Either SomeException (Either Error a)))
forall a. IO (MVar a)
newEmptyMVar
            let native :: IO (Either Error a)
native = do
                  Either Error a
result <- [Ptr Context] -> IO (Either Error a)
action [Ptr Context]
pointers
                  (Shared -> IO ()) -> [Shared] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\(Shared MVar ()
_ CallbackControl
control IORef (Maybe Error)
_) -> CallbackControl -> IO ()
Callback.rethrowCallbackException CallbackControl
control) [Shared]
shared
                  [Maybe Error]
errors <- (Shared -> IO (Maybe Error)) -> [Shared] -> IO [Maybe Error]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> [a] -> m [b]
mapM (\(Shared MVar ()
_ CallbackControl
_ IORef (Maybe Error)
slot) -> IORef (Maybe Error) -> IO (Maybe Error)
forall a. IORef a -> IO a
readIORef IORef (Maybe Error)
slot) [Shared]
shared
                  Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error a -> IO (Either Error a))
-> Either Error a -> IO (Either Error a)
forall a b. (a -> b) -> a -> b
$ case Either Error a
result of
                    Right a
_ -> Either Error a
result
                    Left Error
_ -> Either Error a
-> (Error -> Either Error a) -> Maybe Error -> Either Error a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Either Error a
result Error -> Either Error a
forall a b. a -> Either a b
Left ([Error] -> Maybe Error
forall a. [a] -> Maybe a
listToMaybe ([Maybe Error] -> [Error]
forall a. [Maybe a] -> [a]
catMaybes [Maybe Error]
errors))
            ThreadId
_ <- IO (Either Error a)
-> (Either SomeException (Either Error a) -> IO ()) -> IO ThreadId
forall a. IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally IO (Either Error a)
native (MVar (Either SomeException (Either Error a))
-> Either SomeException (Either Error a) -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Either SomeException (Either Error a))
finished)
            Either SomeException (Either Error a)
outcome <- IO (Either SomeException (Either Error a))
-> IO (Either SomeException (Either Error a))
forall a. IO a -> IO a
restore (MVar (Either SomeException (Either Error a))
-> IO (Either SomeException (Either Error a))
forall a. MVar a -> IO a
readMVar MVar (Either SomeException (Either Error a))
finished) IO (Either SomeException (Either Error a))
-> (SomeException -> IO (Either SomeException (Either Error a)))
-> IO (Either SomeException (Either Error a))
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` [Shared]
-> MVar (Either SomeException (Either Error a))
-> SomeException
-> IO (Either SomeException (Either Error a))
forall a b.
[Shared] -> MVar (Either SomeException a) -> SomeException -> IO b
cancelGroup [Shared]
shared MVar (Either SomeException (Either Error a))
finished
            (SomeException -> IO (Either Error a))
-> (Either Error a -> IO (Either Error a))
-> Either SomeException (Either Error a)
-> IO (Either Error a)
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either SomeException -> IO (Either Error a)
forall e a. Exception e => e -> IO a
throwIO Either Error a -> IO (Either Error a)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Either SomeException (Either Error a)
outcome
        )
          IO (Either Error a) -> IO () -> IO (Either Error a)
forall a b. IO a -> IO b -> IO a
`finally` ((Shared -> IO ()) -> [Shared] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\(Shared MVar ()
_ CallbackControl
control IORef (Maybe Error)
_) -> CallbackControl -> IO ()
Callback.finishCallbackOperation CallbackControl
control) [Shared]
shared IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Ptr Context] -> [Shared] -> IO ()
releaseGroup [Ptr Context]
pointers [Shared]
shared)

acquireGroup :: [Runtime] -> IO (Either Error ([Ptr Context], [Shared]))
acquireGroup :: [Runtime] -> IO (Either Error ([Ptr Context], [Shared]))
acquireGroup = [Ptr Context]
-> [Shared]
-> [Runtime]
-> IO (Either Error ([Ptr Context], [Shared]))
go [] []
  where
    go :: [Ptr Context]
-> [Shared]
-> [Runtime]
-> IO (Either Error ([Ptr Context], [Shared]))
go [Ptr Context]
pointers [Shared]
shared [] = Either Error ([Ptr Context], [Shared])
-> IO (Either Error ([Ptr Context], [Shared]))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (([Ptr Context], [Shared]) -> Either Error ([Ptr Context], [Shared])
forall a b. b -> Either a b
Right ([Ptr Context] -> [Ptr Context]
forall a. [a] -> [a]
reverse [Ptr Context]
pointers, [Shared] -> [Shared]
forall a. [a] -> [a]
reverse [Shared]
shared))
    go [Ptr Context]
pointers [Shared]
shared (Runtime IORef (Maybe (Ptr Context))
handle item :: Shared
item@(Shared MVar ()
gate CallbackControl
_ IORef (Maybe Error)
_) : [Runtime]
rest) = do
      Maybe ()
entered <- if (Shared -> Bool) -> [Shared] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (MVar () -> Shared -> Bool
sameGate MVar ()
gate) [Shared]
shared then Maybe () -> IO (Maybe ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Maybe ()
forall a. a -> Maybe a
Just ()) else MVar () -> IO (Maybe ())
forall a. MVar a -> IO (Maybe a)
tryTakeMVar MVar ()
gate
      case Maybe ()
entered of
        Maybe ()
Nothing -> [Ptr Context] -> [Shared] -> IO ()
releaseGroup [Ptr Context]
pointers [Shared]
shared IO ()
-> IO (Either Error ([Ptr Context], [Shared]))
-> IO (Either Error ([Ptr Context], [Shared]))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either Error ([Ptr Context], [Shared])
-> IO (Either Error ([Ptr Context], [Shared]))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ([Ptr Context], [Shared])
forall a b. a -> Either a b
Left Error
RuntimeBusy)
        Just () -> do
          let owners :: [Shared]
owners = if (Shared -> Bool) -> [Shared] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (MVar () -> Shared -> Bool
sameGate MVar ()
gate) [Shared]
shared then [Shared]
shared else Shared
item Shared -> [Shared] -> [Shared]
forall a. a -> [a] -> [a]
: [Shared]
shared
          Maybe (Ptr Context)
current <- IORef (Maybe (Ptr Context)) -> IO (Maybe (Ptr Context))
forall a. IORef a -> IO a
readIORef IORef (Maybe (Ptr Context))
handle
          case Maybe (Ptr Context)
current of
            Maybe (Ptr Context)
Nothing -> [Ptr Context] -> [Shared] -> IO ()
releaseGroup [Ptr Context]
pointers [Shared]
owners IO ()
-> IO (Either Error ([Ptr Context], [Shared]))
-> IO (Either Error ([Ptr Context], [Shared]))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either Error ([Ptr Context], [Shared])
-> IO (Either Error ([Ptr Context], [Shared]))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ([Ptr Context], [Shared])
forall a b. a -> Either a b
Left Error
RuntimeClosed)
            Just Ptr Context
pointer -> Ptr Context -> IO ()
FFI.cRef Ptr Context
pointer IO ()
-> IO (Either Error ([Ptr Context], [Shared]))
-> IO (Either Error ([Ptr Context], [Shared]))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> [Ptr Context]
-> [Shared]
-> [Runtime]
-> IO (Either Error ([Ptr Context], [Shared]))
go (Ptr Context
pointer Ptr Context -> [Ptr Context] -> [Ptr Context]
forall a. a -> [a] -> [a]
: [Ptr Context]
pointers) [Shared]
owners [Runtime]
rest
    sameGate :: MVar () -> Shared -> Bool
sameGate MVar ()
gate (Shared MVar ()
candidate CallbackControl
_ IORef (Maybe Error)
_) = MVar ()
gate MVar () -> MVar () -> Bool
forall a. Eq a => a -> a -> Bool
== MVar ()
candidate

releaseGroup :: [Ptr Context] -> [Shared] -> IO ()
releaseGroup :: [Ptr Context] -> [Shared] -> IO ()
releaseGroup [Ptr Context]
pointers [Shared]
shared = do
  (Ptr Context -> IO ()) -> [Ptr Context] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Ptr Context -> IO ()
FFI.cRelease [Ptr Context]
pointers
  [Shared] -> (Shared -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [Shared]
shared ((Shared -> IO ()) -> IO ()) -> (Shared -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \(Shared MVar ()
gate CallbackControl
_ IORef (Maybe Error)
_) -> MVar () -> () -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar ()
gate ()

cancelGroup :: [Shared] -> MVar (Either SomeException a) -> SomeException -> IO b
cancelGroup :: forall a b.
[Shared] -> MVar (Either SomeException a) -> SomeException -> IO b
cancelGroup [Shared]
shared MVar (Either SomeException a)
finished SomeException
cause = IO b -> IO b
forall a. IO a -> IO a
uninterruptibleMask_ (IO b -> IO b) -> IO b -> IO b
forall a b. (a -> b) -> a -> b
$ do
  -- throwTo is synchronous: independent senders ensure a masked worker cannot
  -- delay cancellation of another context whose finalizer lets it unwind.
  [MVar (Either SomeException ())]
senders <- [Shared]
-> (Shared -> IO (MVar (Either SomeException ())))
-> IO [MVar (Either SomeException ())]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM [Shared]
shared ((Shared -> IO (MVar (Either SomeException ())))
 -> IO [MVar (Either SomeException ())])
-> (Shared -> IO (MVar (Either SomeException ())))
-> IO [MVar (Either SomeException ())]
forall a b. (a -> b) -> a -> b
$ \(Shared MVar ()
_ CallbackControl
control IORef (Maybe Error)
_) -> do
    MVar (Either SomeException ())
completed <- IO (MVar (Either SomeException ()))
forall a. IO (MVar a)
newEmptyMVar
    ThreadId
_ <- IO () -> (Either SomeException () -> IO ()) -> IO ThreadId
forall a. IO a -> (Either SomeException a -> IO ()) -> IO ThreadId
forkFinally (CallbackControl -> SomeException -> IO ()
Callback.cancelCallbackOperation CallbackControl
control SomeException
cause) (MVar (Either SomeException ()) -> Either SomeException () -> IO ()
forall a. MVar a -> a -> IO ()
putMVar MVar (Either SomeException ())
completed)
    MVar (Either SomeException ())
-> IO (MVar (Either SomeException ()))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure MVar (Either SomeException ())
completed
  Either SomeException a
_ <- MVar (Either SomeException a) -> IO (Either SomeException a)
forall a. MVar a -> IO a
readMVar MVar (Either SomeException a)
finished
  (MVar (Either SomeException ()) -> IO (Either SomeException ()))
-> [MVar (Either SomeException ())] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ MVar (Either SomeException ()) -> IO (Either SomeException ())
forall a. MVar a -> IO a
readMVar [MVar (Either SomeException ())]
senders
  SomeException -> IO b
forall e a. Exception e => e -> IO a
throwIO SomeException
cause

-- | The complete callback decode/action/encode/copy runs inside the protected
-- user worker. Only an owned native buffer crosses back to C on success.
callback :: FFI.Callback State
callback :: Callback State
callback StablePtr State
stable Word32
operation Ptr Word8
input CSize
size Ptr (Ptr Buffer)
output CString
diagnostic CSize
capacity = IO NativeCode -> IO NativeCode
forall a. IO a -> IO a
mask_ (IO NativeCode -> IO NativeCode) -> IO NativeCode -> IO NativeCode
forall a b. (a -> b) -> a -> b
$ do
  Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
output Ptr Buffer
forall a. Ptr a
nullPtr
  State Dispatch
dispatch CallbackControl
control IORef (Maybe Error)
expected <- StablePtr State -> IO State
forall a. StablePtr a -> IO a
deRefStablePtr StablePtr State
stable
  let failed :: SomeException -> IO a
failed (SomeException
cause :: SomeException) = IO a -> IO a
forall a. IO a -> IO a
uninterruptibleMask_ (IO a -> IO a) -> IO a -> IO a
forall a b. (a -> b) -> a -> b
$ do
        CallbackControl -> SomeException -> IO ()
Callback.rememberCallbackException CallbackControl
control SomeException
cause
        Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (CString
diagnostic CString -> CString -> Bool
forall a. Eq a => a -> a -> Bool
/= CString
forall a. Ptr a
nullPtr Bool -> Bool -> Bool
&& CSize
capacity CSize -> CSize -> Bool
forall a. Ord a => a -> a -> Bool
> CSize
0) (CString -> CChar -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke CString
diagnostic CChar
0)
        a -> IO a
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
1
  CallbackControl -> IO NativeCode -> IO NativeCode
forall a. CallbackControl -> IO a -> IO a
Callback.runCallbackWorker
    CallbackControl
control
    ( do
        IORef (Maybe Error) -> Maybe Error -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe Error)
expected Maybe Error
forall a. Maybe a
Nothing
        ByteString
bytes <- if CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
== CSize
0 then ByteString -> IO ByteString
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ByteString
B.empty else CStringLen -> IO ByteString
B.packCStringLen (Ptr Word8 -> CString
forall a b. Ptr a -> Ptr b
castPtr Ptr Word8
input, CSize -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral CSize
size)
        Either Error ByteString
result <- Dispatch
dispatch Word32
operation ByteString
bytes
        case Either Error ByteString
result of
          Left Error
failure -> do
            Int
_ <- Int -> IO Int
forall a. a -> IO a
evaluate ([Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Error -> [Char]
forall a. Show a => a -> [Char]
show Error
failure))
            IORef (Maybe Error) -> Maybe Error -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef IORef (Maybe Error)
expected (Error -> Maybe Error
forall a. a -> Maybe a
Just Error
failure)
            Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (CString
diagnostic CString -> CString -> Bool
forall a. Eq a => a -> a -> Bool
/= CString
forall a. Ptr a
nullPtr Bool -> Bool -> Bool
&& CSize
capacity CSize -> CSize -> Bool
forall a. Ord a => a -> a -> Bool
> CSize
0) (CString -> CChar -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke CString
diagnostic CChar
0)
            NativeCode -> IO NativeCode
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure NativeCode
1
          Right ByteString
reply -> ByteString
-> (Ptr Word8 -> CSize -> IO NativeCode) -> IO NativeCode
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
withBytes ByteString
reply ((Ptr Word8 -> CSize -> IO NativeCode) -> IO NativeCode)
-> (Ptr Word8 -> CSize -> IO NativeCode) -> IO NativeCode
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
pointer CSize
count -> Ptr Word8 -> CSize -> Ptr (Ptr Buffer) -> IO NativeCode
FFI.cBufferNew Ptr Word8
pointer CSize
count Ptr (Ptr Buffer)
output
    )
    IO NativeCode -> (SomeException -> IO NativeCode) -> IO NativeCode
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` SomeException -> IO NativeCode
forall {a}. Num a => SomeException -> IO a
failed

-- | Byte storage stays alive for the entire synchronous call.
withBytes :: ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
withBytes :: forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
withBytes ByteString
bytes Ptr Word8 -> CSize -> IO a
action = ByteString -> (CStringLen -> IO a) -> IO a
forall a. ByteString -> (CStringLen -> IO a) -> IO a
B.useAsCStringLen ByteString
bytes ((CStringLen -> IO a) -> IO a) -> (CStringLen -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$ \(CString
pointer, Int
size) -> Ptr Word8 -> CSize -> IO a
action (CString -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr CString
pointer) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
size)

-- | Copy borrowed public bytes while the native owner is still live.
copyBuffer :: Text -> Ptr Buffer -> IO (Either Error ByteString)
copyBuffer :: Text -> Ptr Buffer -> IO (Either Error ByteString)
copyBuffer Text
operation Ptr Buffer
buffer
  | Ptr Buffer
buffer Ptr Buffer -> Ptr Buffer -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Buffer
forall a. Ptr a
nullPtr = Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
operation))
  | Bool
otherwise = do
      CSize
size <- Ptr Buffer -> IO CSize
FFI.cBufferSize Ptr Buffer
buffer
      Ptr Word8
bytes <- Ptr Buffer -> IO (Ptr Word8)
FFI.cBufferData Ptr Buffer
buffer
      if CSize -> Integer
forall a. Integral a => a -> Integer
toInteger CSize
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int
forall a. Bounded a => a
maxBound :: Int) Bool -> Bool -> Bool
|| (Ptr Word8
bytes Ptr Word8 -> Ptr Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Word8
forall a. Ptr a
nullPtr Bool -> Bool -> Bool
&& CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
/= CSize
0)
        then Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
operation))
        else if CSize
size CSize -> CSize -> Bool
forall a. Eq a => a -> a -> Bool
== CSize
0 then Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right ByteString
B.empty) else ByteString -> Either Error ByteString
forall a b. b -> Either a b
Right (ByteString -> Either Error ByteString)
-> IO ByteString -> IO (Either Error ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> CStringLen -> IO ByteString
B.packCStringLen (Ptr Word8 -> CString
forall a b. Ptr a -> Ptr b
castPtr Ptr Word8
bytes, CSize -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral CSize
size)

-- | Initialize, adopt, copy and release an owned public buffer on every exit.
withOwnedBuffer :: Text -> (Ptr (Ptr Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)
withOwnedBuffer :: Text
-> (Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
withOwnedBuffer Text
operation Ptr (Ptr Buffer) -> IO NativeCode
call = (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
slot -> IO (Ptr (Ptr Buffer))
-> (Ptr (Ptr Buffer) -> IO ())
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket (Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
slot Ptr Buffer
forall a. Ptr a
nullPtr IO () -> IO (Ptr (Ptr Buffer)) -> IO (Ptr (Ptr Buffer))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr (Ptr Buffer) -> IO (Ptr (Ptr Buffer))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Ptr (Ptr Buffer)
slot) Ptr (Ptr Buffer) -> IO ()
FFI.cBufferRelease ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
output -> do
  Either Error ()
result <- Ptr (Ptr Buffer) -> IO NativeCode
call Ptr (Ptr Buffer)
output IO NativeCode
-> (NativeCode -> IO (Either Error ())) -> IO (Either Error ())
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> NativeCode -> IO (Either Error ())
checkStatus Text
operation
  case Either Error ()
result of
    Left Error
failure -> Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
failure)
    Right () -> Ptr (Ptr Buffer) -> IO (Ptr Buffer)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Buffer)
output IO (Ptr Buffer)
-> (Ptr Buffer -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Ptr Buffer -> IO (Either Error ByteString)
copyBuffer Text
operation

-- | Preserve native status and copy its static diagnostic before returning.
checkStatus :: Text -> Status.NativeCode -> IO (Either Error ())
checkStatus :: Text -> NativeCode -> IO (Either Error ())
checkStatus Text
operation NativeCode
code
  | NativeCode
code NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success = Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either Error ()
forall a b. b -> Either a b
Right ())
  | Bool
otherwise = do
      Text
message <- NativeCode -> IO CString
Status.cErrorMessage NativeCode
code IO CString -> (CString -> IO Text) -> IO Text
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= CString -> IO Text
copyStaticText
      Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ()
forall a b. a -> Either a b
Left (NativeFailure -> Error
fromNativeFailure (Text -> Integer -> Text -> NativeFailure
NativeFailure Text
operation (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
code) Text
message)))

-- | Test-only count of contexts rooting runtime handles.
liveContexts :: IO Int
liveContexts :: IO Int
liveContexts = CSize -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral (CSize -> Int) -> IO CSize -> IO Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO CSize
FFI.cLiveContexts