@@ -1,23 +1,48 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE DeriveDataTypeable #-}
3−{-# LANGUAGE DeriveGeneric #-}
4−{-# LANGUAGE FlexibleInstances #-}
1+{-# LANGUAGE DataKinds #-}
2+{-# LANGUAGE DeriveDataTypeable #-}
3+{-# LANGUAGE DeriveGeneric #-}
4+{-# LANGUAGE FlexibleInstances #-}
55{-# LANGUAGE FunctionalDependencies #-}
6−{-# LANGUAGE KindSignatures #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE OverloadedStrings #-}
9−{-# LANGUAGE PolyKinds #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE TupleSections #-}
6+{-# LANGUAGE KindSignatures #-}
7+{-# LANGUAGE MultiParamTypeClasses #-}
8+{-# LANGUAGE OverloadedStrings #-}
9+{-# LANGUAGE PolyKinds #-}
10+{-# LANGUAGE RankNTypes #-}
11+{-# LANGUAGE TupleSections #-}
1212{-# OPTIONS_HADDOCK not-home #-}
1313
14−module Servant.API.Stream where
14+module Servant.API.Stream (
15+ Stream,
16+ StreamGet,
17+ StreamPost,
18+ -- * Sources
19+ --
20+ -- | Both 'StreamGenerator' and 'ResultStream' are equivalent
21+ -- to some *source* in streaming libraries.
22+ StreamGenerator (..),
23+ ToStreamGenerator (..),
24+ ResultStream (..),
25+ FromResultStream (..),
26+ -- * Framing
27+ FramingRender (..),
28+ FramingUnrender (..),
29+ BoundaryStrategy (..),
30+ ByteStringParser (..),
31+ -- ** Strategies
32+ NoFraming,
33+ NewlineFraming,
34+ NetstringFraming,
35+ ) where
1536
1637import Control.Arrow
1738 (first)
1839import Data.ByteString.Lazy
1940 (ByteString, empty)
2041import qualified Data.ByteString.Lazy.Char8 as LB
42+import Data.Foldable
43+ (traverse_)
44+import Data.List.NonEmpty
45+ (NonEmpty (..))
2146import Data.Monoid
2247 ((<>))
2348import Data.Proxy
@@ -30,35 +55,82 @@ import GHC.TypeLits
3055 (Nat)
3156import Network.HTTP.Types.Method
3257 (StdMethod (..))
58+import System.IO.Unsafe
59+ (unsafeInterleaveIO)
3360import Text.Read
3461 (readMaybe)
3562
36−-- | A Stream endpoint for a given method emits a stream of encoded values at a given Content-Type, delimited by a framing strategy. Stream endpoints always return response code 200 on success. Type synonyms are provided for standard methods.
63+-- | A Stream endpoint for a given method emits a stream of encoded values at a
64+-- given Content-Type, delimited by a framing strategy. Stream endpoints always
65+-- return response code 200 on success. Type synonyms are provided for standard
66+-- methods.
3767data Stream (method :: k1) (status :: Nat) (framing :: *) (contentType :: *) (a :: *)
3868 deriving (Typeable, Generic)
3969
4070type StreamGet = Stream 'GET 200
4171type StreamPost = Stream 'POST 200
4272
43−-- | Stream endpoints may be implemented as producing a @StreamGenerator@ -- a function that itself takes two emit functions -- the first to be used on the first value the stream emits, and the second to be used on all subsequent values (to allow interspersed framing strategies such as comma separation).
44−newtype StreamGenerator a = StreamGenerator {getStreamGenerator :: (a -> IO ()) -> (a -> IO ()) -> IO ()}
73+-- | Stream endpoints may be implemented as producing a @StreamGenerator@ a
74+-- function that itself takes two emit functions the first to be used on the
75+-- first value the stream emits, and the second to be used on all subsequent
76+-- values (to allow interspersed framing strategies such as comma separation).
77+newtype StreamGenerator a = StreamGenerator { getStreamGenerator :: (a -> IO ()) -> (a -> IO ()) -> IO () }
4578
4679-- | ToStreamGenerator is intended to be implemented for types such as Conduit, Pipe, etc. By implementing this class, all such streaming abstractions can be used directly as endpoints.
4780class ToStreamGenerator a b | a -> b where
48− toStreamGenerator :: a -> StreamGenerator b
49−
50−instance ToStreamGenerator (StreamGenerator a) a
51− where toStreamGenerator x = x
52−
53−-- | Clients reading from streaming endpoints can be implemented as producing a @ResultStream@ that captures the setup, takedown, and incremental logic for a read, being an IO continuation that takes a producer of Just either values or errors that terminates with a Nothing.
54−newtype ResultStream a = ResultStream (forall b. (IO (Maybe (Either String a)) -> IO b) -> IO b)
55−
56−-- | BuildFromStream is intended to be implemented for types such as Conduit, Pipe, etc. By implementing this class, all such streaming abstractions can be used directly on the client side for talking to streaming endpoints.
57−class BuildFromStream a b where
58− buildFromStream :: ResultStream a -> b
59−
60−instance BuildFromStream a (ResultStream a)
61− where buildFromStream x = x
81+ toStreamGenerator :: a -> StreamGenerator b
82+
83+instance ToStreamGenerator (StreamGenerator a) a where
84+ toStreamGenerator x = x
85+
86+instance ToStreamGenerator (NonEmpty a) a where
87+ toStreamGenerator (x :| xs) = StreamGenerator $ \f g -> f x >> traverse_ g xs
88+
89+instance ToStreamGenerator [a] a where
90+ toStreamGenerator [] = StreamGenerator $ \_ _ -> return ()
91+ toStreamGenerator (x : xs) = StreamGenerator $ \f g -> f x >> traverse_ g xs
92+
93+-- | Clients reading from streaming endpoints can be implemented as producing a
94+-- @ResultStream@ that captures the setup, takedown, and incremental logic for
95+-- a read, being an IO continuation that takes a producer of Just either values
96+-- or errors that terminates with a Nothing.
97+newtype ResultStream a = ResultStream { runResultStream :: forall b. (IO (Maybe (Either String a)) -> IO b) -> IO b }
98+
99+-- | FromResultStream is intended to be implemented for types such as Conduit, Pipe, etc. By implementing this class, all such streaming abstractions can be used directly on the client side for talking to streaming endpoints.
100+class FromResultStream a b | b -> a where
101+ fromResultStream :: ResultStream a -> IO b
102+
103+instance FromResultStream a (ResultStream a) where
104+ fromResultStream = return
105+
106+-- | Uses 'unsafeInterleaveIO'
107+instance FromResultStream a [a] where
108+ fromResultStream x = runResultStream x lazyRead
109+
110+-- | Uses 'unsafeInterleaveIO'
111+instance FromResultStream a (NonEmpty a) where
112+ fromResultStream x = runResultStream x $ \r -> do
113+ e <- r
114+ case e of
115+ Nothing -> fail "Empty stream"
116+ Just (Left er) -> fail er
117+ Just (Right y) -> do
118+ ys <- lazyRead r
119+ return (y :| ys)
120+
121+lazyRead :: IO (Maybe (Either String a)) -> IO [a]
122+lazyRead r = go
123+ where
124+ go = unsafeInterleaveIO loop
125+
126+ loop = do
127+ e <- r
128+ case e of
129+ Nothing -> return []
130+ Just (Left er) -> fail er
131+ Just (Right y) -> do
132+ ys <- go
133+ return (y : ys)
62134
63135-- | The FramingRender class provides the logic for emitting a framing strategy. The strategy emits a header, followed by boundary-delimited data, and finally a termination character. For many strategies, some of these will just be empty bytestrings.
64136class FramingRender strategy a where
@@ -74,10 +146,10 @@ data BoundaryStrategy = BoundaryStrategyBracket (ByteString -> (ByteString,ByteS
74146 | BoundaryStrategyGeneral (ByteString -> ByteString)
75147
76148-- | A type of parser that can never fail, and has different parsing strategies (incremental, or EOF) depending if more input can be sent. The incremental parser should return `Nothing` if it would like to be sent a longer ByteString. If it returns a value, it also returns the remainder following that value.
77−data ByteStringParser a = ByteStringParser {
78− parseIncremental :: ByteString -> Maybe (a, ByteString),
79− parseEOF :: ByteString -> (a, ByteString)
80−}
149+data ByteStringParser a = ByteStringParser
150+ { parseIncremental :: ByteString -> Maybe (a, ByteString)
151+ , parseEOF :: ByteString -> (a, ByteString)
152+ }
81153
82154-- | The FramingUnrender class provides the logic for parsing a framing strategy. The outer @ByteStringParser@ strips the header from a stream of bytes, and yields a parser that can handle the remainder, stepwise. Each frame may be a ByteString, or a String indicating the error state for that frame. Such states are per-frame, so that protocols that can resume after errors are able to do so. Eventually this returns an empty ByteString to indicate termination.
83155class FramingUnrender strategy a where