Debian Codegraph @

Network/Wai/Application/Classic/EventSource.hs

raw
1 {-# LANGUAGE OverloadedStrings, CPP #-}
2
3 module Network.Wai.Application.Classic.EventSource (
4 bodyToEventSource
5 ) where
6
7 import Data.ByteString (ByteString)
8 import qualified Data.ByteString as BS
9 import Data.ByteString.Builder
10 import Data.ByteString.Char8 ()
11 import Data.Conduit
12 import qualified Data.Conduit.List as CL
13 import qualified Network.HTTP.Client as H
14 import qualified Network.HTTP.Client.Conduit as HC
15
16 lineBreak :: ByteString -> Int -> Maybe Int
17 lineBreak bs n = go
18 where
19 len = BS.length bs
20 go | n >= len = Nothing
21 | otherwise = case bs `BS.index` n of
22 13 -> go' (n+1)
23 10 -> Just (n+1)
24 _ -> Nothing
25 go' n' | n' >= len = Just n'
26 | otherwise = case bs `BS.index` n' of
27 10 -> Just (n'+1)
28 _ -> Just n'
29
30 -- splitDoubleLineBreak "aaa\n\nbbb" == ["aaa\n\n", "bbb"]
31 -- splitDoubleLineBreak "aaa\n\nbbb\n\n" == ["aaa\n\n", "bbb\n\n", ""]
32 -- splitDoubleLineBreak "aaa\r\n\rbbb\n\r\n" == ["aaa\r\n\r", "bbb\n\r\n", ""]
33 -- splitDoubleLineBreak "aaa" == ["aaa"]
34 -- splitDoubleLineBreak "" == [""]
35 splitDoubleLineBreak :: ByteString -> [ByteString]
36 splitDoubleLineBreak str = go str 0
37 where
38 go bs n | n < BS.length str =
39 case lineBreak bs n of
40 Nothing -> go bs (n+1)
41 Just n' ->
42 case lineBreak bs n' of
43 Nothing -> go bs (n+1)
44 Just n'' ->
45 let (xs,ys) = BS.splitAt n'' bs
46 in xs:go ys 0
47 | otherwise = [bs]
48
49 #if MIN_VERSION_conduit(1,3,0)
50 eventSourceConduit :: ConduitT ByteString (Flush Builder) IO ()
51 #else
52 eventSourceConduit :: Conduit ByteString IO (Flush Builder)
53 #endif
54 eventSourceConduit = CL.concatMapAccum f ""
55 where
56 f input rest = (last xs, concatMap addFlush $ init xs)
57 where
58 addFlush x = [Chunk (byteString x), Flush]
59 xs = splitDoubleLineBreak (rest `BS.append` input)
60
61 -- insert Flush if exists a double line-break
62 #if MIN_VERSION_conduit(1,3,0)
63 bodyToEventSource :: H.BodyReader -> ConduitT () (Flush Builder) IO ()
64 bodyToEventSource br = HC.bodyReaderSource br .| eventSourceConduit
65 #else
66 bodyToEventSource :: H.BodyReader -> Source IO (Flush Builder)
67 bodyToEventSource br = HC.bodyReaderSource br $= eventSourceConduit
68 #endif