使用管道的顺序二进制数据解码

Joh*_*iss 5 haskell protocol-buffers conduit

目标是使用具有以下类型签名的管道

protobufConduit :: MonadResource m => (ByteString -> a) -> Conduit ByteString m a
Run Code Online (Sandbox Code Playgroud)

管道应重复解析ByteString -> a通过TCP/IP(使用network-conduit包)接收的协议缓冲区(使用该功能).

有线消息格式是

{length (32 bits big endian)}{protobuf 1}{length}{protobuf 2}...
Run Code Online (Sandbox Code Playgroud)

(花括号不是协议的一方,仅用于分隔实体).

第一个想法是使用sequenceSink重复应用Sink能够解析一个ProtoBuf:

[...]
import qualified Data.Binary         as B
import qualified Data.Conduit.Binary as CB
import qualified Data.Conduit.Util   as CU

protobufConduit :: MonadResource m => (ByteString -> a) -> Conduit ByteString m a
protobufConduit protobufDecode =
    CU.sequenceSink () $ \() ->
        do lenBytes <- CB.take 4                                -- read protobuf length
           let len :: Word32
               len = B.decode lengthBytes                       -- decode ProtoBuf length
               intLen = fromIntegral len
           protobufBytes <- CB.take intLen                      -- read the ProtoBuf bytes
           return $ CU.Emit () [ protobufDecode protobufBytes ] -- emit decoded ProtoBuf
Run Code Online (Sandbox Code Playgroud)

它不起作用(仅适用于第一个协议缓冲区),因为似乎已经从源中读取了许多"剩余"字节,但是没有通过CB.take丢弃而消耗掉这些字节.

我发现无法将"其余部分推回源头".

我的概念完全错了吗?

PS:即使我在这里使用协议缓冲区,问题也与协议缓冲区无关.为了调试这个问题,我总是使用{length}{UTF8 encoded string}{length}{UTF8 encoded string}...和上面一个类似的导管(utf8StringConduit :: MonadResource m => Conduit ByteString m Text).

更新:

我只是尝试用()剩余的字节替换状态(上面的示例中没有状态),并CB.take通过调用首先消耗已经读取的字节(来自状态)的函数来替换调用,并且await仅在需要时调用(当状态为不够大).不幸的是,这也不起作用,因为只要Source没有剩余字节,sequenceSink就不会执行代码,但状态仍然包含剩余的字节:-(.

如果你应该对代码感兴趣(没有优化或非常好,但应该足以测试):

utf8StringConduit :: forall m. MonadResource m => Conduit ByteString m Text
utf8StringConduit =
    CU.sequenceSink [] $ \st ->
        do (lengthBytes, st') <- takeWithState BS.empty st 4
           let len :: Word32
               len = B.decode $ BSL.fromChunks [lengthBytes]
               intLength = fromIntegral len
           (textBytes, st'') <- takeWithState BS.empty st' intLength
           return $ CU.Emit st'' [ TE.decodeUtf8 $ textBytes ]

takeWithState :: Monad m
              => ByteString
              -> [ByteString]
              -> Int
              -> Pipe l ByteString o u m (ByteString, [ByteString])
takeWithState acc state 0 = return (acc, state)
takeWithState acc state neededLen =
    let stateLenSum = foldl' (+) 0 $ map BS.length state
     in if stateLenSum >= neededLen
           then do let (firstChunk:state') = state
                       (neededChunk, pushBack) = BS.splitAt neededLen firstChunk
                       acc' = acc `BS.append` neededChunk
                       neededLen' = neededLen - BS.length neededChunk
                       state'' = if BS.null pushBack
                                    then state'
                                    else pushBack:state'
                   takeWithState acc' state'' neededLen'
           else do aM <- await
                   case aM of
                     Just a -> takeWithState acc (state ++ [a]) neededLen
                     Nothing -> error "to be fixed later"
Run Code Online (Sandbox Code Playgroud)

Dav*_*ner 4

对于协议缓冲区解析和序列化,我们使用messageWithLengthPutMand messageWithLengthGetM(见下文),但我假设它对长度使用 varint 编码,这不是您需要的。我可能会尝试通过将messageWithLengthGet/Put 替换为类似的内容来调整我们下面的实现

myMessageWithLengthGetM = 
   do size <- getWord32be 
      getMessageWithSize size
Run Code Online (Sandbox Code Playgroud)

但我不知道如何getMessageWithSize使用协议缓冲区包中的可用函数来实现。另一方面,您可以getByteString“重新解析”字节串。

关于管道:您是否尝试过在不使用 的情况下实现管道Data.Conduit.Util?就像是

protobufConduit protobufDecode = loop
   where
      loop = 
         do len <- liftM convertLen (CB.take 4)
            bs <- CB.take len
            yield (protobufDecode bs)
            loop
Run Code Online (Sandbox Code Playgroud)

这是我们使用的代码:

pbufSerialize :: (ReflectDescriptor w, Wire w) => Conduit w IO ByteString
pbufSerialize = awaitForever f
    where f pb = M.mapM_ yield $ BSL.toChunks $ runPut (messageWithLengthPutM pb)

pbufParse :: (ReflectDescriptor w, Wire w, Show w) => Conduit ByteString IO w
pbufParse = new
    where
      new = read (runGet messageWithLengthGetM . BSL.fromChunks . (:[]))
      read parse =
          do mbs <- await
             case mbs of
               Just bs -> checkResult (parse bs)
               Nothing -> return ()
      checkResult result =
          case result of
            Failed _ errmsg -> fail errmsg
            Partial cont -> read (cont . Just . BSL.fromChunks . (:[]))
            Finished rest _ msg ->
                do yield msg
                   checkResult (runGet messageWithLengthGetM rest)
Run Code Online (Sandbox Code Playgroud)