packages feed

memcache-0.6.0.0: Database/Memcache/Internal/Lookup.hs

{-# OPTIONS_HADDOCK not-home #-}

{-|
Module      : Database.Memcache.Internal.Lookup
Description : Host lookups that a timeout can end
Copyright   : (c) David Terei, 2026
License     : BSD
Maintainer  : code@davidterei.com
Stability   : internal
Portability : GHC

This module is internal: it isn't covered by the PVP, and may change in any
release.

Host lookups in a thread of their own, so that a timeout can end the wait.
-}
module Database.Memcache.Internal.Lookup (
        Lookup, newLookup, addressesOf
    ) where

import           Control.Concurrent       (forkIO)
import           Control.Concurrent.MVar  (MVar, modifyMVarMasked, newEmptyMVar, newMVar, putMVar,
                                           readMVar, swapMVar)
import           Control.Exception        (SomeException, throwIO, try)
import           Network.Socket           (AddrInfo, HostName, ServiceName)
import qualified Network.Socket           as S

-- | A server's host lookup, while one runs: where it will put its result.
newtype Lookup = Lookup (MVar (Maybe (MVar (Either SomeException [AddrInfo]))))

-- | A 'Lookup' with no lookup running, for a new server.
newLookup :: IO Lookup
newLookup = Lookup <$> newMVar Nothing

-- | The addresses to try for a host and port; a path is a Unix socket. The
-- resolver runs in a thread of its own, so that a timeout ends the wait at
-- once, though it can't interrupt the foreign call, which is left to finish.
-- Calls made meanwhile wait for it rather than start another lookup.
addressesOf
    :: Lookup
    -> (Maybe AddrInfo -> Maybe HostName -> Maybe ServiceName -> IO [AddrInfo])
    -> HostName -> ServiceName -> IO [AddrInfo]
addressesOf (Lookup running) resolve host port = case host of
    '/' : _ -> return [S.defaultHints {
        S.addrFamily = S.AF_UNIX,
        S.addrSocketType = S.Stream,
        S.addrAddress = S.SockAddrUnix host
      }]
    _ -> do
        result <- modifyMVarMasked running $ \current -> case current of
            Just started -> return (current, started)
            Nothing -> do
                new <- newEmptyMVar
                -- Cleared before the result is out, so later calls look up
                -- afresh.
                _ <- forkIO $ do
                    addresses <- try $ resolve (Just hints) (Just host) (Just port)
                    _ <- swapMVar running Nothing
                    putMVar new addresses
                return (Just new, new)
        readMVar result >>= either throwIO return
  where
    hints = S.defaultHints { S.addrSocketType = S.Stream }