管道 - 多次“尝试”进入一个来源

时间:2013-10-27 23:48:52

标签: networking haskell conduit

我正在尝试执行以下操作:

sourceIRC
  :: (MonadBaseControl IO m, MonadLogger m)
  => NetworkSettings
  -> Producer (ConnectionT m) Message
sourceIRC networkSettings = do
  withConnectionForever networkSettings $ \socket -> do
    bracket (liftBase $ Network.socketToHandle socket IO.ReadWriteMode)
            (\handle -> liftBase $ IO.hClose handle)
            (\handle -> do
               mvar <- newMVar False
               bracket (fork $ do
                          threadDelay 5000000
                          _ <- swapMVar mvar True
                          return ())
                       (killThread)
                       (\_ -> runConnectionT handle (sourceHandle handle))
               takeMVar mvar)

正如您所看到的,我正在尝试根据原始Producer创建withConnectionForever。该原语是类型:

withConnectionForever
  :: (MonadBaseControl IO m, MonadLogger m)
  => NetworkSettings
  -> (Network.Socket -> m Bool)
  -> m ()

您可以想象,我在编译时收到错误消息!它是:

Haskell/IRC.hs:128:54:
    Couldn't match expected type `ConnectionT m0 a0'
                with actual type `ConduitM i0 ByteString.ByteString m1 ()'
    In the return type of a call of `sourceHandle'
    In the second argument of `runConnectionT', namely
      `(sourceHandle handle)'
    In the expression: runConnectionT handle (sourceHandle handle)

现在,我知道调用withConnectionForever的类型显然不是一个管道,但我曾希望它可以成为一个,因为管道也是一个管道而且withConnectionForever使用免费的monad而不是硬编码的monad。我对消息试图传达的内容的理解是,这种情况并没有发生,我想知道为什么以及我能做些什么。

这里,为了完整性,是原语的来源:

withConnectionForever
  :: (MonadBaseControl IO m, MonadLogger m)
  => NetworkSettings
  -> (Network.Socket -> m Bool)
  -> m ()
withConnectionForever networkSettings action = do
  let loop nFailures = do
        maybeSocket <- newConnection networkSettings
        case maybeSocket of
          Nothing -> return ()
          Just socket -> do
            terminatedNormally <- action socket
            if terminatedNormally
              then loop 0
              else do
                exponentTwiddle <- liftBase $ Random.randomRIO (0, 100)
                let exponent =
                      1.25 + fromIntegral (exponentTwiddle - 50) / 100.0
                    delay = floor $ 1000000.0 *
                      ((0.5 ** (fromIntegral nFailures * negate exponent))
                       - 1.0 :: Double)
                $(logInfo) (Text.concat
                  ["Abnormal disconnection from the network ",
                   networkSettingsName networkSettings,
                   "; pausing attempts for ",
                   Text.pack $ show $ fromIntegral delay / 1000000.0,
                   " seconds..."])
                liftBase $ threadDelay delay
                loop (nFailures + 1)
  loop 0

我真的不想重写原语,除非它可以以微创方式完成,但我想这是在桌面上。

提前致谢!

1 个答案:

答案 0 :(得分:1)

要做的相关事情是

(\_ -> transPipe (runConnectionT handle) (sourceHandle handle))

而不是

(\_ -> runConnectionT handle (sourceHandle handle))

感谢您的时间! :d