packages feed

baikai-mcp-0.1.0.0: src/Baikai/Mcp/Internal/Sse.hs

-- | An incremental, bounded Server-Sent Events parser.
--
-- Chunks arrive from the network at arbitrary boundaries, so a line, a
-- field or a CRLF pair can straddle two chunks. The parser keeps the
-- partial line and refuses any line or event larger than its limit before
-- it buffers more, so a hostile stream cannot grow memory without bound.
-- Comment lines (those starting with @:@) are keep-alives and are ignored.
-- An incomplete event at end of stream is discarded, as the SSE
-- specification requires.
module Baikai.Mcp.Internal.Sse
  ( SseEvent (..),
    SseParser,
    newSseParser,
    feedSse,
  )
where

import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Char8 qualified as BS8
import GHC.Generics (Generic)

-- | One dispatched event.
data SseEvent = SseEvent
  { -- | The @event:@ field, empty when absent (which means @message@).
    eventName :: !ByteString,
    -- | The @data:@ lines joined with newlines.
    eventData :: !ByteString
  }
  deriving stock (Eq, Show, Generic)

data SseParser = SseParser
  { limit :: !Int,
    partial :: !ByteString,
    -- | The previous chunk ended with CR, so a leading LF belongs to it.
    skipLF :: !Bool,
    dataLines :: ![ByteString],
    dataSize :: !Int,
    name :: !ByteString
  }

-- | A parser refusing any line or event larger than the given byte count.
newSseParser :: Int -> SseParser
newSseParser n = SseParser {limit = n, partial = BS.empty, skipLF = False, dataLines = [], dataSize = 0, name = BS.empty}

-- | Feed one chunk. Returns the events completed by it, or a reason when
-- the size limit is exceeded.
feedSse :: SseParser -> ByteString -> Either String (SseParser, [SseEvent])
feedSse st0 chunk0
  | BS.null chunk0 = Right (st0, [])
  | otherwise = go st0 {skipLF = False} chunk' []
  where
    chunk'
      | st0.skipLF, Just ('\n', rest) <- BS8.uncons chunk0 = rest
      | otherwise = chunk0
    go st input acc
      | BS.null input = Right (st, reverse acc)
      | otherwise = case BS8.findIndex (\c -> c == '\n' || c == '\r') input of
          Nothing ->
            let buf = st.partial <> input
             in if BS.length buf > st.limit
                  then Left "server-sent event line exceeds the frame limit"
                  else Right (st {partial = buf, skipLF = False}, reverse acc)
          Just i -> do
            let line = st.partial <> BS.take i input
                terminator = BS8.index input i
                after = BS.drop (i + 1) input
                (rest, pendingLF) =
                  if terminator == '\r'
                    then case BS8.uncons after of
                      Just ('\n', r) -> (r, False)
                      Just _ -> (after, False)
                      Nothing -> (after, True)
                    else (after, False)
            if BS.length line > st.limit
              then Left "server-sent event line exceeds the frame limit"
              else do
                (st', ev) <- processLine st {partial = BS.empty} line
                go st' {skipLF = pendingLF} rest (maybe acc (: acc) ev)

processLine :: SseParser -> ByteString -> Either String (SseParser, Maybe SseEvent)
processLine st line
  | BS.null line =
      if null st.dataLines
        then Right (reset, Nothing)
        else Right (reset, Just (SseEvent st.name (BS.intercalate "\n" (reverse st.dataLines))))
  | BS8.head line == ':' = Right (st, Nothing)
  | otherwise =
      let (field, rest0) = BS8.break (== ':') line
          value = case BS8.uncons rest0 of
            Just (':', v) -> case BS8.uncons v of
              Just (' ', v') -> v'
              _ -> v
            _ -> BS.empty
       in case field of
            "data" ->
              let size = st.dataSize + BS.length value + 1
               in if size > st.limit
                    then Left "server-sent event exceeds the frame limit"
                    else Right (st {dataLines = value : st.dataLines, dataSize = size}, Nothing)
            "event" -> Right (st {name = value}, Nothing)
            _ -> Right (st, Nothing)
  where
    reset = st {dataLines = [], dataSize = 0, name = BS.empty}