packages feed

simple-sendfile 0.2.33 → 0.2.34

raw patch · 7 files changed

+236/−62 lines, 7 filesdep +stmdep ~network

Dependencies added: stm

Dependency ranges changed: network

Files

ChangeLog.md view
@@ -1,5 +1,10 @@ # ChangeLog for simple-sendfile +## 0.2.34++* Add give-up variants: sendfileWith and friends+  [#54](https://github.com/kazu-yamamoto/simple-sendfile/pull/54)+ ## 0.2.33  GHC 9.2 or later is required.
Network/Sendfile.hs view
@@ -9,9 +9,13 @@ module Network.Sendfile (     sendfile   , sendfileWithHeader+  , sendfileWith+  , sendfileWithHeaderWith #if OS_BSD || OS_MacOS || OS_Linux   , sendfileFd   , sendfileFdWithHeader+  , sendfileFdWith+  , sendfileFdWithHeaderWith #endif   , FileRange(..)   ) where
Network/Sendfile/BSD.hsc view
@@ -6,11 +6,16 @@   , sendfileFd   , sendfileWithHeader   , sendfileFdWithHeader+  , sendfileWith+  , sendfileFdWith+  , sendfileWithHeaderWith+  , sendfileFdWithHeaderWith   ) where  import Control.Concurrent import Control.Exception-import Control.Monad+import Data.Void (Void, absurd)+import GHC.Conc (STM) import Data.ByteString (ByteString) import qualified Data.ByteString as BS import Foreign.C.Error (eAGAIN, eINTR, getErrno, throwErrno)@@ -62,21 +67,50 @@ -- is sent and before waiting the socket to be ready for writing.  sendfileFd :: Socket -> Fd -> FileRange -> IO () -> IO ()-sendfileFd sock fd range hook = do+sendfileFd sock fd range hook =+    withFdSocket sock $ \s ->+        sendfileFdWait (blocking (Fd s)) sock fd range hook >>= either absurd return++-- | 'sendfile' which gives up once the 'STM' action succeeds, while+--   waiting for the socket to become writable.  What the action gave is+--   returned as 'Left'; part of the file may have been sent by then.+sendfileWith :: Socket -> FilePath -> FileRange -> IO () -> STM a -> IO (Either a ())+sendfileWith sock path range hook giveUp = bracket setup teardown $ \fd ->+    sendfileFdWith sock fd range hook giveUp+  where+    setup = openFd path ReadOnly defaultFileFlags{nonBlock=True}+    teardown = closeFd++-- | 'sendfileFd' which gives up as 'sendfileWith' does.+sendfileFdWith :: Socket -> Fd -> FileRange -> IO () -> STM a -> IO (Either a ())+sendfileFdWith sock fd range hook giveUp =+    sendfileFdWait (writable sock giveUp) sock fd range hook++-- Waiting for the socket to become writable: 'Left' when given up.+type Wait a = IO (Either a ())++blocking :: Fd -> Wait Void+blocking dst = Right <$> threadWaitWrite dst++writable :: Socket -> STM a -> Wait a+writable sock giveUp = withWritable sock giveUp (return ())++sendfileFdWait :: Wait a -> Socket -> Fd -> FileRange -> IO () -> IO (Either a ())+sendfileFdWait wait sock fd range hook = do   checkRange range   withFdSocket sock $ \s -> do     let dst = Fd s     alloca $ \sentp -> case range of-        EntireFile -> sendloop dst fd 0 entire sentp hook+        EntireFile -> sendloop wait dst fd 0 entire sentp hook         -- 0 means the entire file for BSD sendfile(), so skip it.         PartOfFile off len-          | len <= 0  -> return ()-          | otherwise -> sendloop dst fd (fromInteger off) (fromInteger len) sentp hook+          | len <= 0  -> return $ Right ()+          | otherwise -> sendloop wait dst fd (fromInteger off) (fromInteger len) sentp hook -sendloop :: Fd -> Fd -> COff -> COff -> Ptr COff -> IO () -> IO ()-sendloop dst src off len sentp hook = do+sendloop :: Wait a -> Fd -> Fd -> COff -> COff -> Ptr COff -> IO () -> IO (Either a ())+sendloop wait dst src off len sentp hook = do     rc <- sendFile src dst off len sentp nullPtr-    when (rc /= 0) $ do+    if rc == 0 then return $ Right () else do         errno <- getErrno         if errno `elem` [eAGAIN, eINTR] then do             sent <- peek sentp@@ -84,11 +118,11 @@             let newoff = off + sent                 newlen = if len == entire then entire else len - sent             -- newlen must not reach 0, which means the entire file.-            unless (len /= entire && newlen <= 0) $ do+            if len /= entire && newlen <= 0 then return $ Right () else do                 -- Parallel IO manager use edge-trigger mode.-                -- So, calling threadWaitWrite only when errnor is eAGAIN.-                when (errno == eAGAIN) $ threadWaitWrite dst-                sendloop dst src newoff newlen sentp hook+                -- So, waiting only when errnor is eAGAIN.+                r <- if errno == eAGAIN then wait else return $ Right ()+                either (return . Left) (\_ -> sendloop wait dst src newoff newlen sentp hook) r           else             throwErrno "Network.Sendfile.BSD.sendloop" @@ -132,20 +166,42 @@ -- is sent and before waiting the socket to be ready for writing.  sendfileFdWithHeader :: Socket -> Fd -> FileRange -> IO () -> [ByteString] -> IO ()-sendfileFdWithHeader sock fd range hook hdr = do+sendfileFdWithHeader sock fd range hook hdr =+    withFdSocket sock $ \s ->+        sendfileFdWithHeaderWait (blocking (Fd s)) (fmap Right . sendMany sock) sock fd range hook hdr+            >>= either absurd return++-- | 'sendfileWithHeader' which gives up as 'sendfileWith' does, also+--   while sending the header.+sendfileWithHeaderWith :: Socket -> FilePath -> FileRange -> IO () -> [ByteString] -> STM a -> IO (Either a ())+sendfileWithHeaderWith sock path range hook hdr giveUp =+    bracket setup teardown $ \fd -> sendfileFdWithHeaderWith sock fd range hook hdr giveUp+  where+    setup = openFd path ReadOnly defaultFileFlags{nonBlock=True}+    teardown = closeFd++-- | 'sendfileFdWithHeader' which gives up as 'sendfileWith' does, also+--   while sending the header.+sendfileFdWithHeaderWith :: Socket -> Fd -> FileRange -> IO () -> [ByteString] -> STM a -> IO (Either a ())+sendfileFdWithHeaderWith sock fd range hook hdr giveUp =+    sendfileFdWithHeaderWait (writable sock giveUp) (\bss -> sendManyWith sock bss giveUp) sock fd range hook hdr++sendfileFdWithHeaderWait+    :: Wait a -> ([ByteString] -> IO (Either a ())) -> Socket -> Fd -> FileRange -> IO () -> [ByteString] -> IO (Either a ())+sendfileFdWithHeaderWait wait sendHdr sock fd range hook hdr = do   checkRange range   withFdSocket sock $ \s -> do     let dst = Fd s     alloca $ \sentp ->         if isEmptyPart then             -- 0 means the entire file for BSD sendfile(), so skip it.-            sendMany sock hdr+            sendHdr hdr           else if isFreeBSD && hlen >= 8192 then do             -- If the length of the header is larger than 8191,             -- threadWaitWrite does not come back on FreeBSD, sigh.             -- We use writev() for the header and sendfile() for the file.-            sendMany sock hdr-            sendfileFd sock fd range hook+            r <- sendHdr hdr+            either (return . Left) (\_ -> sendfileFdWait wait sock fd range hook) r           else do             -- On MacOS, the header and the body are sent separately.             -- But it's fast. the writev() and sendfile() combination@@ -154,21 +210,22 @@                     EntireFile           -> (0,entire)                     PartOfFile off' len' -> (fromInteger off'                                             ,fromInteger len' + hlen)-            mrc <- sendloopHeader dst fd off len sentp hdr hlen hook+            mrc <- sendloopHeader wait dst fd off len sentp hdr hlen hook             case mrc of-                Nothing              -> return ()-                Just (newoff,newlen) -> sendloop dst fd newoff newlen sentp hook+                Left a                       -> return $ Left a+                Right Nothing                -> return $ Right ()+                Right (Just (newoff,newlen)) -> sendloop wait dst fd newoff newlen sentp hook   where     hlen = fromIntegral . sum . map BS.length $ hdr     isEmptyPart = case range of         PartOfFile _ len -> len <= 0         EntireFile       -> False -sendloopHeader :: Fd -> Fd -> COff -> COff -> Ptr COff -> [ByteString] -> COff -> IO () -> IO (Maybe (COff, COff))-sendloopHeader dst src off len sentp hdr hlen hook = do+sendloopHeader :: Wait a -> Fd -> Fd -> COff -> COff -> Ptr COff -> [ByteString] -> COff -> IO () -> IO (Either a (Maybe (COff, COff)))+sendloopHeader wait dst src off len sentp hdr hlen hook = do     rc <- withSfHdtr hdr $ sendFile src dst off len sentp     if rc == 0 then-        return Nothing+        return $ Right Nothing       else do         errno <- getErrno         if errno `elem` [eAGAIN, eINTR] then do@@ -176,22 +233,23 @@             hook             -- Parallel IO manager use edge-trigger mode.             -- So, calling threadWaitWrite only when errnor is eAGAIN.-            let wait = when (errno == eAGAIN) $ threadWaitWrite dst+            let waitThen k = do+                    r <- if errno == eAGAIN then wait else return $ Right ()+                    either (return . Left) (const k) r             if sent >= hlen then do                 let newoff = off + sent - hlen                 if len == entire then-                    wait >> return (Just (newoff, entire))+                    waitThen $ return $ Right $ Just (newoff, entire)                   else if len - sent <= 0 then                     -- 0 means the entire file, so stop here.-                    return Nothing+                    return $ Right Nothing                   else-                    wait >> return (Just (newoff, len - sent))+                    waitThen $ return $ Right $ Just (newoff, len - sent)               else do                 let newlen = if len == entire then entire else len - sent                     newhdr = remainingChunks (fromIntegral sent) hdr                     newhlen = hlen - sent-                wait-                sendloopHeader dst src off newlen sentp newhdr newhlen hook+                waitThen $ sendloopHeader wait dst src off newlen sentp newhdr newhlen hook           else             throwErrno "Network.Sendfile.BSD.sendloopHeader" 
Network/Sendfile/Fallback.hs view
@@ -1,9 +1,12 @@ module Network.Sendfile.Fallback (     sendfile   , sendfileWithHeader+  , sendfileWith+  , sendfileWithHeaderWith   ) where  import Control.Monad.IO.Class (MonadIO(liftIO))+import GHC.Conc (STM) import Data.ByteString (ByteString) import Data.Conduit import qualified Data.Conduit.Binary as EB@@ -37,12 +40,38 @@         SB.sendMany sock hdr         sendHandle sock h range hook -sendHandle :: Socket -> Handle -> FileRange -> IO () -> IO ()-sendHandle sock h range hook = runConduit $ source .| sinkSocket sock hook+-- | 'sendfile' which gives up once the 'STM' action succeeds, while+--   waiting for the socket to become writable.  What the action gave is+--   returned as 'Left'; part of the file may have been sent by then.+sendfileWith :: Socket -> FilePath -> FileRange -> IO () -> STM a -> IO (Either a ())+sendfileWith sock path range hook giveUp = do+    checkRange range+    withBinaryFile path ReadMode $ \h -> sendHandleWith sock h range hook giveUp++-- | 'sendfileWithHeader' which gives up as 'sendfileWith' does, also+--   while sending the header.+sendfileWithHeaderWith :: Socket -> FilePath -> FileRange -> IO () -> [ByteString] -> STM a -> IO (Either a ())+sendfileWithHeaderWith sock path range hook hdr giveUp = do+    checkRange range+    withBinaryFile path ReadMode $ \h -> do+        r <- SB.sendManyWith sock hdr giveUp+        either (return . Left) (\_ -> sendHandleWith sock h range hook giveUp) r++sendHandleWith :: Socket -> Handle -> FileRange -> IO () -> STM a -> IO (Either a ())+sendHandleWith sock h range hook giveUp = runConduit $ source h range .| loop   where-    source = case range of-        EntireFile         -> EB.sourceHandle h-        PartOfFile off len -> EB.sourceHandleRange h (Just off) (Just len)+    loop = await >>= maybe (return $ Right ()) send+    send bs = do+        r <- liftIO $ SB.sendAllWith sock bs giveUp+        either (return . Left) (\_ -> liftIO hook >> loop) r++sendHandle :: Socket -> Handle -> FileRange -> IO () -> IO ()+sendHandle sock h range hook = runConduit $ source h range .| sinkSocket sock hook++source :: MonadIO m => Handle -> FileRange -> ConduitT i ByteString m ()+source h range = case range of+    EntireFile         -> EB.sourceHandle h+    PartOfFile off len -> EB.sourceHandleRange h (Just off) (Just len)  -- See sinkHandle. sinkSocket :: MonadIO m => Socket -> IO () -> ConduitT ByteString Void m ()
Network/Sendfile/Linux.hsc view
@@ -11,10 +11,13 @@   , sendfileFd'   , sendfileWithHeader   , sendfileFdWithHeader+  , sendfileWith+  , sendfileFdWith+  , sendfileWithHeaderWith+  , sendfileFdWithHeaderWith   ) where  import Control.Exception-import Control.Monad import Data.ByteString (ByteString) import qualified Data.ByteString as B import Data.ByteString.Unsafe (unsafeUseAsCStringLen)@@ -22,8 +25,9 @@ import Foreign.C.Types import Foreign.Marshal (alloca) import Foreign.Ptr (Ptr, plusPtr)+import Data.Void (Void, absurd) import Foreign.Storable (poke, sizeOf)-import GHC.Conc (threadWaitWrite)+import GHC.Conc (STM, threadWaitWrite) import Network.Sendfile.Types import Network.Socket import System.Posix.Files@@ -99,21 +103,50 @@     sendfileFd' dst fd range hook  sendfileFd' :: Fd -> Fd -> FileRange -> IO () -> IO ()-sendfileFd' dst src range hook = do+sendfileFd' dst src range hook =+    sendfileFdWait (blocking dst) dst src range hook >>= either absurd return++-- | 'sendfile' which gives up once the 'STM' action succeeds, while+--   waiting for the socket to become writable.  What the action gave is+--   returned as 'Left'; part of the file may have been sent by then.+sendfileWith :: Socket -> FilePath -> FileRange -> IO () -> STM a -> IO (Either a ())+sendfileWith sock path range hook giveUp = bracket setup teardown $ \fd ->+    sendfileFdWith sock fd range hook giveUp+  where+    setup = openFd path ReadOnly defaultFileFlags{nonBlock=True}+    teardown = closeFd++-- | 'sendfileFd' which gives up as 'sendfileWith' does.+sendfileFdWith :: Socket -> Fd -> FileRange -> IO () -> STM a -> IO (Either a ())+sendfileFdWith sock fd range hook giveUp =+    withFdSocket sock $ \s ->+        sendfileFdWait (writable sock giveUp) (Fd s) fd range hook++-- Waiting for the socket to become writable: 'Left' when given up.+type Wait a = IO (Either a ())++blocking :: Fd -> Wait Void+blocking dst = Right <$> threadWaitWrite dst++writable :: Socket -> STM a -> Wait a+writable sock giveUp = withWritable sock giveUp (return ())++sendfileFdWait :: Wait a -> Fd -> Fd -> FileRange -> IO () -> IO (Either a ())+sendfileFdWait wait dst src range hook = do   checkRange range   alloca $ \offp -> case range of         EntireFile -> do             poke offp 0             -- System call is very slow. Use PartOfFile instead.             len <- fileSize <$> getFdStatus src-            sendfileloop dst src offp len hook+            sendfileloop wait dst src offp len hook         PartOfFile off len -> do             poke offp (fromIntegral off)-            sendfileloop dst src offp (fromIntegral len) hook+            sendfileloop wait dst src offp (fromIntegral len) hook  -- The remaining length is COff since CSize is 32-bit on 32-bit platforms.-sendfileloop :: Fd -> Fd -> Ptr COff -> COff -> IO () -> IO ()-sendfileloop dst src offp len hook = do+sendfileloop :: Wait a -> Fd -> Fd -> Ptr COff -> COff -> IO () -> IO (Either a ())+sendfileloop wait dst src offp len hook = do     -- Multicore IO manager use edge-trigger mode.     -- So, calling threadWaitWrite only when errnor is eAGAIN.     let toSend@@ -123,18 +156,17 @@     case bytes of         -1 -> do             errno <- getErrno-            if errno == eAGAIN then do-                threadWaitWrite dst-                sendfileloop dst src offp len hook+            if errno == eAGAIN then+                wait >>= either (return . Left) (\_ -> sendfileloop wait dst src offp len hook)               else if errno == eINTR then-                sendfileloop dst src offp len hook+                sendfileloop wait dst src offp len hook               else                 throwErrno "Network.Sendfile.Linux.sendfileloop"-        0  -> return () -- the file is truncated+        0  -> return $ Right () -- the file is truncated         _  -> do             hook             let left = len - fromIntegral bytes-            when (left /= 0) $ sendfileloop dst src offp left hook+            if left /= 0 then sendfileloop wait dst src offp left hook else return $ Right ()  -- Dst Src in order. take care foreign import capi unsafe "sys/sendfile.h sendfile"@@ -193,31 +225,48 @@ sendfileFdWithHeader sock fd range hook hdr = do     checkRange range     -- Copying is much faster than syscall.-    sendMsgMore sock $ B.concat hdr+    sendMsgMore blocking sock (B.concat hdr) >>= either absurd return     sendfileFd sock fd range hook -sendMsgMore :: Socket -> ByteString -> IO ()-sendMsgMore sock bs = unsafeUseAsCStringLen bs $ \(buf, len) ->-    withFdSocket sock $ \fd -> sendloop (Fd fd) buf (fromIntegral len)+-- | 'sendfileWithHeader' which gives up as 'sendfileWith' does, also+--   while sending the header.+sendfileWithHeaderWith :: Socket -> FilePath -> FileRange -> IO () -> [ByteString] -> STM a -> IO (Either a ())+sendfileWithHeaderWith sock path range hook hdr giveUp = bracket setup teardown $ \fd ->+    sendfileFdWithHeaderWith sock fd range hook hdr giveUp+  where+    setup = openFd path ReadOnly defaultFileFlags{nonBlock=True}+    teardown = closeFd -sendloop :: Fd -> Ptr CChar -> CSize -> IO ()-sendloop s buf len = do+-- | 'sendfileFdWithHeader' which gives up as 'sendfileWith' does, also+--   while sending the header.+sendfileFdWithHeaderWith :: Socket -> Fd -> FileRange -> IO () -> [ByteString] -> STM a -> IO (Either a ())+sendfileFdWithHeaderWith sock fd range hook hdr giveUp = do+    checkRange range+    r <- sendMsgMore (const $ writable sock giveUp) sock $ B.concat hdr+    either (return . Left) (\_ -> sendfileFdWith sock fd range hook giveUp) r++sendMsgMore :: (Fd -> Wait a) -> Socket -> ByteString -> IO (Either a ())+sendMsgMore wait sock bs = unsafeUseAsCStringLen bs $ \(buf, len) ->+    withFdSocket sock $ \fd -> sendloop (wait (Fd fd)) (Fd fd) buf (fromIntegral len)++sendloop :: Wait a -> Fd -> Ptr CChar -> CSize -> IO (Either a ())+sendloop wait s buf len = do     bytes <- c_send s buf len (#const MSG_MORE)     if bytes == -1 then do         errno <- getErrno-        if errno == eAGAIN then do-            threadWaitWrite s-            sendloop s buf len+        if errno == eAGAIN then+            wait >>= either (return . Left) (\_ -> sendloop wait s buf len)           else if errno == eINTR then-            sendloop s buf len+            sendloop wait s buf len           else             throwErrno "Network.Sendfile.Linux.sendloop"       else do         let sent = fromIntegral bytes-        when (sent /= len) $ do+        if sent /= len then do             let left = len - sent                 ptr = buf `plusPtr` fromIntegral bytes-            sendloop s ptr left+            sendloop wait s ptr left+          else return $ Right ()  foreign import ccall unsafe "send"   c_send :: Fd -> Ptr CChar -> CSize -> CInt -> IO CSsize
simple-sendfile.cabal view
@@ -1,6 +1,6 @@ cabal-version:      >=1.10 name:               simple-sendfile-version:            0.2.33+version:            0.2.34 license:            BSD3 license-file:       LICENSE maintainer:         Kazu Yamamoto <kazu@iij.ad.jp>@@ -36,7 +36,7 @@     ghc-options:      -Wall     build-depends:         base >=4.16 && <5,-        network >=3.1.4,+        network >=3.2.12,         bytestring      if (os(freebsd) && flag(allow-bsd) && !flag(fallback))@@ -90,4 +90,5 @@         network,         process,         resourcet,-        simple-sendfile+        simple-sendfile,+        stm
test/SendfileSpec.hs view
@@ -5,6 +5,7 @@ module SendfileSpec where  import Control.Concurrent+import Control.Concurrent.STM import Control.Exception import Control.Monad import Control.Monad.Trans.Resource (MonadResource, runResourceT)@@ -76,7 +77,19 @@             sendRejectedH (PartOfFile 2000 (-1)) `shouldReturn` ""         it "sends nothing if the file does not exist" $ do             sendMissingH `shouldReturn` ""+    describe "sendfileWith" $ do+        it "sends an entire file" $ do+            sendFileWith EntireFile [] `shouldReturn` True+        it "sends an header and a part of file" $ do+            sendFileWith (PartOfFile 2000 1000000) headers `shouldReturn` True+        it "gives up on a peer which does not read" $ do+            givingUp (\s g -> sendfileWith s "test/inputFile" EntireFile (return ()) g)+                `shouldReturn` Just (Left ())+        it "gives up on a peer which does not read the header" $ do+            givingUp (\s g -> sendfileWithHeaderWith s "test/inputFile" EntireFile (return ()) [BS.replicate 4000000 'h'] g)+                `shouldReturn` Just (Left ())   where+    headers = [BS.replicate 100 'a', "\n", BS.replicate 200 'b', "\n"]     fiveSecs = 5000000     shouldTerminate body = do         r <- timeout fiveSecs body@@ -112,8 +125,21 @@       , "\n"       ] +sendFileWith :: FileRange -> [ByteString] -> IO Bool+sendFileWith = sendFileCore' True++-- Runs a give-up variant against a peer which never reads, giving up+-- after 0.1 second.  Nothing if it does not return within 5 seconds.+givingUp :: (Socket -> STM () -> IO (Either () ())) -> IO (Maybe (Either () ()))+givingUp act = bracket (socketPair AF_UNIX Stream 0) (\(s1,s2) -> close s1 >> close s2) $ \(s1,_) -> do+    late <- registerDelay 100000+    timeout 5000000 $ act s1 (readTVar late >>= check)+ sendFileCore :: FileRange -> [ByteString] -> IO Bool-sendFileCore range headers = bracket setup teardown $ \(s2,_) -> do+sendFileCore = sendFileCore' False++sendFileCore' :: Bool -> FileRange -> [ByteString] -> IO Bool+sendFileCore' useWith range headers = bracket setup teardown $ \(s2,_) -> do     tr "reader:begin"     runResourceT $ runConduit (sourceSocket s2 .| sinkFile outputFile)     tr "reader:eof"@@ -144,6 +170,8 @@         return (s2,tid)       where         sf s1+          | useWith && headers == [] = sendfileWith s1 inputFile range (tr "sender:hook") retry >>= either return return+          | useWith = sendfileWithHeaderWith s1 inputFile range (tr "sender:hook") headers retry >>= either return return           | headers == [] = sendfile s1 inputFile range (tr "sender:hook")           | otherwise     = sendfileWithHeader s1 inputFile range (tr "sender:hook") headers         sendEOF = close