haskoin-store 1.13.0 → 1.14.0
raw patch · 7 files changed
+253/−102 lines, 7 filesdep ~haskoin-corePVP ok
version bump matches the API change (PVP)
Dependency ranges changed: haskoin-core
API changes (from Hackage documentation)
+ Haskoin.Store.Web.Pieces: ahead :: Int -> [IO a] -> (a -> IO ()) -> IO ()
+ Haskoin.Store.Web.Pieces: data Piece
+ Haskoin.Store.Web.Pieces: piece :: IO Builder -> Piece
- Haskoin.Store.Web.Pieces: around :: Builder -> Builder -> [IO Builder] -> [IO Builder]
+ Haskoin.Store.Web.Pieces: around :: Builder -> Builder -> [Piece] -> [Piece]
- Haskoin.Store.Web.Pieces: listPieces :: (b -> Encoding) -> [IO [b]] -> IO [IO Builder]
+ Haskoin.Store.Web.Pieces: listPieces :: (b -> Encoding) -> [IO [b]] -> IO [Piece]
- Haskoin.Store.Web.Pieces: piecesResponse :: ResponseHeaders -> IO () -> [IO Builder] -> IO Response
+ Haskoin.Store.Web.Pieces: piecesResponse :: Int -> ResponseHeaders -> IO () -> [Piece] -> IO Response
Files
- CHANGELOG.md +30/−0
- bench/Main.hs +15/−7
- haskoin-store.cabal +7/−7
- src/Haskoin/Store/Web.hs +28/−20
- src/Haskoin/Store/Web/Pieces.hs +118/−44
- swagger.yaml +1/−1
- test/Haskoin/Store/Web/PiecesSpec.hs +54/−23
CHANGELOG.md view
@@ -4,6 +4,36 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html) +## [1.14.0] - 2026-11-14++Long answers are encoded on several cores, addresses are written faster,+and the load-test server works again.++### Changed+- **Long answers are encoded on several cores.** The answers that are+ sent in pieces, such as the full transactions of an address, an xpub or+ a block, and raw blocks, now encode up to eight pieces at once, as many+ as the server has cores. On 5,000 transactions of an address, with eight+ cores, a request took 77 ms where it took 176 ms. A server whose cores+ are all busy answers about as many requests as before. In the library,+ the pieces of `Haskoin.Store.Web.Pieces` are a `Piece`, made with+ `piece` from an action that gives bytes, and `piecesResponse` takes how+ many to read at once.+- **Addresses are written faster**, with haskoin-core 1.6.3, which this+ version needs. Every input and output of a transaction in JSON carries+ its address. For 20,000 of them, reading the address from its script+ takes 3 ms where it took 33, writing a legacy address 60 ms where it+ took 81, and a SegWit address 50 ms where it took 81. CashAddr was fast+ already. A whole answer of transactions takes some 30% less to build and+ encode.++### Fixed+- The load-test server, `haskoin-store-bench`, builds and syncs again. It+ lacked the `nodeRpc` setting of 1.11.0, and it found no peer: since+ haskoin-node 2.5 the mock peer has to be named, as the unit tests do.+ `scripts/bench-web.sh` measures two answers of 5,000 transactions too,+ and `BENCH_LOG=1` prints the log of the server.+ ## [1.13.0] - 2026-11-13 Transactions are handed over at once, a payment that a block replaced is
bench/Main.hs view
@@ -6,6 +6,9 @@ -- -- > haskoin-store-bench PORT BLOCKS [REDIS_URL] --+-- Set @BENCH_LOG=1@ to print the log of the store, such as to see why it+-- does not sync.+-- -- Every block holds a coinbase and ten transactions. The coinbase and one -- output of each transaction pay the "hot" address, so it gains eleven -- transactions per block. Nine outputs per block go to the first 100@@ -38,7 +41,7 @@ import Haskoin.Store.Database.Query qualified as Q import NQE import Network.Socket (SockAddr (..))-import System.Environment (getArgs)+import System.Environment (getArgs, lookupEnv) import System.Random (randomIO) import UnliftIO @@ -60,7 +63,9 @@ let net = bchRegTest blocks = chain ctx net nblocks requests <- newTVarIO []- withStore (storeConfig ctx net dir redis blocks requests) $ \store -> do+ logged <- maybe False (`notElem` ["", "0"]) <$> lookupEnv "BENCH_LOG"+ let withLog f = if logged then withLogger LevelDebug f else f quiet+ withLog $ \logger -> withStore (storeConfig ctx net dir redis blocks requests logger) $ \store -> do withSubscription store.pub $ \sub -> waitHeight store sub nblocks T.putStrLn $ "hot address: " <> addrText net (hotAddr ctx) T.putStrLn $ "xpub: " <> xPubExport net ctx (benchXPub ctx)@@ -87,12 +92,14 @@ waitHeight store sub n storeConfig ::- Ctx -> Network -> FilePath -> Maybe String -> [Block] -> TVar [Int] -> StoreConfig-storeConfig ctx net dir redis blocks requests =+ Ctx -> Network -> FilePath -> Maybe String -> [Block] -> TVar [Int] -> Logger -> StoreConfig+storeConfig ctx net dir redis blocks requests logger = StoreConfig { maxPeers = 20,- initPeers = [],- discover = True,+ -- the mock peer, by name: since haskoin-node 2.5 the seed of a regtest+ -- network is not an address that discovery takes+ initPeers = ["127.0.0.1:18444"],+ discover = False, db = dir, net = net, ctx = ctx,@@ -117,7 +124,7 @@ writeBufferSize = Nothing, maxWalSize = Nothing, blockCache = Just (1024 * 1024 * 1024),- logger = quiet+ logger = logger } where ad = NetworkAddress nodeNetwork (sockToHostAddress (SockAddrInet 0 0))@@ -146,6 +153,7 @@ healthCheckInterval = 30, accessLog = False, tls = Nothing,+ nodeRpc = Nothing, logger = quiet }
haskoin-store.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack name: haskoin-store-version: 1.13.0+version: 1.14.0 synopsis: Storage and index for Bitcoin and Bitcoin Cash description: An indexer for Bitcoin and Bitcoin Cash. It downloads blocks and mempool transactions from the peer-to-peer network, indexes them in RocksDB, and@@ -108,7 +108,7 @@ , file-embed >=0.0.16.0 && <0.1 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store-data >=2.0.1 && <2.1 , hedis >=0.16.4 && <0.17@@ -172,7 +172,7 @@ , file-embed >=0.0.16.0 && <0.1 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store-data >=2.0.1 && <2.1 , hedis >=0.16.4 && <0.17@@ -234,7 +234,7 @@ , filepath >=1.5.5.0 && <1.6 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store , haskoin-store-data >=2.0.1 && <2.1@@ -325,7 +325,7 @@ , file-embed >=0.0.16.0 && <0.1 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store , haskoin-store-data >=2.0.1 && <2.1@@ -391,7 +391,7 @@ , file-embed >=0.0.16.0 && <0.1 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store , haskoin-store-data >=2.0.1 && <2.1@@ -454,7 +454,7 @@ , file-embed >=0.0.16.0 && <0.1 , hashable >=1.5.1.0 && <1.6 , hashtables >=1.4.2 && <1.5- , haskoin-core >=1.6.2 && <1.7+ , haskoin-core >=1.6.3 && <1.7 , haskoin-node >=2.5.1 && <2.6 , haskoin-store , haskoin-store-data >=2.0.1 && <2.1
src/Haskoin/Store/Web.hs view
@@ -125,7 +125,7 @@ ) import Data.Aeson.Types (parseMaybe) import Data.ByteString.Base16 (decodeBase16, parseBase16)-import Data.ByteString.Builder (Builder, lazyByteString)+import Data.ByteString.Builder (lazyByteString) import Data.ByteString.Char8 qualified as C import Data.ByteString.Lazy qualified as L import Data.Bytes.Get@@ -214,7 +214,7 @@ import Haskoin.Store.Manager import Haskoin.Store.Web.Docs (swaggerPage, swaggerYaml) import Haskoin.Store.Web.Events-import Haskoin.Store.Web.Pieces (around, hexOf, listPieces, pieced, piecesResponse)+import Haskoin.Store.Web.Pieces (Piece, around, hexOf, listPieces, piece, pieced, piecesResponse) import Haskoin.Store.Web.Publish qualified as Publish import Haskoin.Store.Web.Router hiding (header) import Haskoin.Store.WebCommon@@ -327,7 +327,7 @@ writeTQueue, writeTVar, )-import UnliftIO.Concurrent (threadDelay)+import UnliftIO.Concurrent (getNumCapabilities, threadDelay) -- | Limits of the API. A value of @0@ means no limit. data WebLimits = WebLimits@@ -1149,7 +1149,7 @@ (WebMetrics -> StatTiming) -> [Text] -> (Req -> IO a) ->- (a -> IO [IO Builder]) ->+ (a -> IO [Piece]) -> Route pieces = pathPieces st plain :: (ApiResource a b, ToJSON b) => [Text] -> (Req -> IO a) -> (a -> IO b) -> Route@@ -1262,7 +1262,7 @@ (WebMetrics -> StatTiming) -> [Text] -> (Req -> IO a) ->- (a -> IO [IO Builder]) ->+ (a -> IO [Piece]) -> Route pathPieces st df ps parser action = route (renderStdMethod (resourceMethod proxy)) (capturePath proxy) ps $ \req ->@@ -1274,14 +1274,22 @@ -- | A response in pieces, timed. The timing counts the whole response, the -- time that the client takes to read it included.-inPieces :: WebState -> (WebMetrics -> StatTiming) -> ResponseHeaders -> IO [IO Builder] -> IO Response+inPieces :: WebState -> (WebMetrics -> StatTiming) -> ResponseHeaders -> IO [Piece] -> IO Response inPieces st df headers pieces = do began <- now let done = forM_ st.metrics $ \m -> now >>= \ended -> addTiming (df m) (ended - began)- (pieces >>= piecesResponse headers done) `onException` done+ n <- encoders+ (pieces >>= piecesResponse n headers done) `onException` done where now = round . (* 1000) <$> getPOSIXTime :: IO Int +-- | How many pieces of a response are read and encoded at once: one for+-- each core, so that a long answer is encoded on all of them, but no more+-- than eight, which bounds what a response holds to some nine pieces, and+-- leaves cores to other requests on a large machine.+encoders :: IO Int+encoders = min 8 <$> getNumCapabilities+ -- | The headers of a response in JSON. jsonType :: ResponseHeaders jsonType = [(hContentType, "application/json")]@@ -1338,12 +1346,12 @@ -- GET BlockRaw -- -- | Handler for @GET \/block\/:block\/raw@: a block by hash, serialized as in the peer-to-peer protocol.-handleBlockRaw :: WebState -> GetBlockRaw -> IO [IO Builder]+handleBlockRaw :: WebState -> GetBlockRaw -> IO [Piece] handleBlockRaw st (GetBlockRaw h) = rawResult <$> getRawBlock st h -- | The pieces of a block by hash, serialized, in hexadecimal. Responds -- with an error if not found.-getRawBlock :: WebState -> H.BlockHash -> IO [IO Builder]+getRawBlock :: WebState -> H.BlockHash -> IO [Piece] getRawBlock st h = st.query.getBlock h >>= maybe (raise st ThingNotFound) (return . rawBlock st.query) @@ -1351,18 +1359,18 @@ -- hexadecimal: its header and the number of its transactions, then its -- transactions as they are read. The first piece has transactions too, so -- that a response does not begin before something of them was read.-rawBlock :: StoreRead -> BlockData -> [IO Builder]+rawBlock :: StoreRead -> BlockData -> [Piece] rawBlock q b = around (hexOf b.header <> hexOf (VarInt (fromIntegral (length b.txs)))) mempty $- pieced pieceSize (fmap (foldMap (hexOf . transactionData) . catMaybes) . C.getTransactions q) b.txs+ map piece (pieced pieceSize (fmap (foldMap (hexOf . transactionData) . catMaybes) . C.getTransactions q) b.txs) -- | The pieces of the JSON of a 'RawResult', from those of the hexadecimal.-rawResult :: [IO Builder] -> [IO Builder]+rawResult :: [Piece] -> [Piece] rawResult = around "{\"result\":\"" "\"}" -- | The pieces of the JSON of a 'RawResultList', from those of the -- hexadecimal of each of its items.-rawResultList :: [[IO Builder]] -> [IO Builder]+rawResultList :: [[Piece]] -> [Piece] rawResultList items = around "[" "]" (concat [around (comma <> "\"") "\"" item | (comma, item) <- zip ("" : repeat ",") items]) @@ -1378,7 +1386,7 @@ (bestBlock st.query) >>= maybe (raise st ThingNotFound) (return . pruneTx notx) -- | Handler for @GET \/block\/best\/raw@: the best block, serialized.-handleBlockBestRaw :: WebState -> GetBlockBestRaw -> IO [IO Builder]+handleBlockBestRaw :: WebState -> GetBlockBestRaw -> IO [Piece] handleBlockBestRaw st _ = st.query.getBestBlock >>= \case Nothing -> raise st ThingNotFound@@ -1424,7 +1432,7 @@ >>= (\hs -> getBlocks st hs notx) . concat -- | Handler for @GET \/block\/height\/:height\/raw@: the blocks at a height, serialized.-handleBlockHeightRaw :: WebState -> GetBlockHeightRaw -> IO [IO Builder]+handleBlockHeightRaw :: WebState -> GetBlockHeightRaw -> IO [Piece] handleBlockHeightRaw st (GetBlockHeightRaw h) = fmap rawResultList $ mapM (getRawBlock st) =<< st.query.getBlocksAtHeight (fromIntegral h)@@ -1456,7 +1464,7 @@ Just b -> return $ pruneTx notx b -- | Handler for @GET \/block\/time\/:time\/raw@: the last block with a timestamp at or before a time, serialized.-handleBlockTimeRaw :: WebState -> GetBlockTimeRaw -> IO [IO Builder]+handleBlockTimeRaw :: WebState -> GetBlockTimeRaw -> IO [Piece] handleBlockTimeRaw st (GetBlockTimeRaw (TimeParam t)) = C.blockAtOrBefore st.query st.config.store.chain t >>= \case Nothing -> raise st ThingNotFound@@ -1464,7 +1472,7 @@ -- | Handler for @GET \/block\/mtp\/:time\/raw@: the first block with a median time -- past at or after a time, serialized.-handleBlockMTPRaw :: WebState -> GetBlockMTPRaw -> IO [IO Builder]+handleBlockMTPRaw :: WebState -> GetBlockMTPRaw -> IO [Piece] handleBlockMTPRaw st (GetBlockMTPRaw (TimeParam t)) = C.blockAtOrAfterMTP st.query st.config.store.chain t >>= \case Nothing -> raise st ThingNotFound@@ -1519,7 +1527,7 @@ handleTxsBlock st (GetTxsBlock h) = transactionPieces st.query <$> getTxsBlock st h -- | Handler for @GET \/transactions\/block\/:block\/raw@: the transactions of a block, serialized, in pieces.-handleTxsBlockRaw :: WebState -> GetTxsBlockRaw -> IO [IO Builder]+handleTxsBlockRaw :: WebState -> GetTxsBlockRaw -> IO [Piece] handleTxsBlockRaw st (GetTxsBlockRaw h) = listPieces hex . transactionPieces st.query =<< getTxsBlock st h where@@ -3047,7 +3055,7 @@ -- in it, and they are put where the empty list was. Should the encoding of -- haskoin-store-data come to end another way, the block is read and -- encoded whole, as it was before.-binfoBlockPieces :: WebState -> Bool -> BlockData -> IO [IO Builder]+binfoBlockPieces :: WebState -> Bool -> BlockData -> IO [Piece] binfoBlockPieces st numtxid b = do nhs <- fmap catMaybes $ st.query.getBlocksAtHeight (b.height + 1) >>= mapM (st.query.getBlock) let h x = H.headerHash x.header@@ -3083,7 +3091,7 @@ <$> listPieces (marshalEncoding own . toBinfoTxSimple numtxid) txs else do whole <- map (toBinfoTxSimple numtxid) . concat <$> sequence txs- return [return (fromEncoding (marshalEncoding own (toBinfoBlock b whole nxt)))]+ return [piece (return (fromEncoding (marshalEncoding own (toBinfoBlock b whole nxt))))] where net = st.config.store.net ctx = st.config.store.ctx
src/Haskoin/Store/Web/Pieces.hs view
@@ -25,8 +25,9 @@ -- byte left after 11 ms where it took 96 ms, and sixteen such requests at -- once took 197 MB of memory where they took 1,014 MB. The whole response -- took as long as before: most of that time goes into encoding JSON, which--- this does not change. A short answer gains nothing, and should stay with--- the routes that read first.+-- reading in pieces does not change, but encoding them on several cores+-- does (see below). A short answer gains nothing, and should stay with the+-- routes that read first. -- -- = Why it is safe --@@ -39,13 +40,33 @@ -- expected to fail. What the client names, such as a list of transaction -- hashes, may not be there, and is read whole before anything is answered. ----- While a piece is written the next one is read, so that neither the--- database nor the client waits for the other, and no more than two pieces--- are held. Nothing of the database is held between pieces, so a slow--- client costs two pieces of memory and no more. The price is that the--- pieces are not read from one view of the database: an item may change,--- or go, between two of them.+-- While a piece is written the next ones are read, so that neither the+-- database nor the client waits for the other. Nothing of the database is+-- held between pieces, so a slow client costs a few pieces of memory and no+-- more. The price is that the pieces are not read from one view of the+-- database: an item may change, or go, between two of them. --+-- = Encoding on several cores+--+-- Most of the time of a long answer goes into encoding its JSON, and one+-- thread doing it for a whole answer leaves the other cores idle. So each+-- piece is encoded, down to its bytes, in the thread that reads it, and+-- several pieces are read and encoded at once, as many as 'piecesResponse'+-- is told. What has to be done in order, such as the comma between the+-- items of two pieces, which depends on whether the pieces before had any,+-- is left for the writer, and is cheap: a 'Piece' is an action in two+-- steps, the first one that may run beside the others, and the second one+-- that runs in order. A response holds at most that many pieces, and one+-- more being written.+--+-- Measured with @scripts/bench-web.sh@ on 5,000 transactions of one+-- address, eight cores, eight pieces at once: one request at a time took+-- 77 ms where it took 176 ms, for 16% more CPU time. With eight requests at+-- once, enough to keep every core busy without it, as many were answered,+-- 5% fewer. So it is for a server with cores to spare, which is the usual+-- case: it shortens the wait, and does not make more answers out of the+-- same cores.+-- -- = The alternative -- -- Lazy input and output, a lazy 'Data.ByteString.Lazy.ByteString' whose@@ -55,8 +76,11 @@ module Haskoin.Store.Web.Pieces ( -- * Responses piecesResponse,+ ahead, -- * Pieces+ Piece,+ piece, pieced, listPieces, around,@@ -64,69 +88,119 @@ ) where +import Control.Exception (evaluate) import Data.Aeson.Encoding (Encoding, fromEncoding)-import Data.ByteString.Builder (Builder, lazyByteStringHex)+import Data.ByteString.Builder (Builder, lazyByteString, lazyByteStringHex, toLazyByteString)+import Data.ByteString.Lazy qualified as L import Data.Bytes.Put (runPutL) import Data.Bytes.Serial (Serial (..))-import Data.IORef (newIORef, readIORef, writeIORef)+import Data.IORef (modifyIORef', newIORef, readIORef, writeIORef)+import Data.List (intersperse)+import Data.Sequence (Seq (..), (|>)) import Network.HTTP.Types (ResponseHeaders, status200) import Network.Wai (Response, responseStream)-import UnliftIO (finally, wait, withAsync)+import UnliftIO (asyncWithUnmask, cancel, finally, mask_, wait) --- | The response made of pieces: the bytes of each, in order. A piece is--- an action that reads something and gives its bytes. The first piece is--- read before the response is made, and its errors are thrown here; the--- others are read while the response is written, each while the one before--- it is written. The action given runs when the response ends, however it--- ends. The response has no @Content-Length@.-piecesResponse :: ResponseHeaders -> IO () -> [IO Builder] -> IO Response-piecesResponse headers done pieces = do+-- | A piece of a response. Its outer action reads what the piece is made of+-- and encodes it to bytes, and may run at the same time as those of other+-- pieces. The action that it gives runs in order, right before the piece is+-- written, and gives the bytes to write. It should be cheap: it is there+-- for what depends on the pieces before, such as a comma.+newtype Piece = Piece (IO (IO Builder))++-- | A piece from an action that reads its bytes. They are encoded in the+-- thread that reads them, so the action that it gives only hands them over.+piece :: IO Builder -> Piece+piece act = Piece $ do+ bytes <- rendered =<< act+ return (return (lazyByteString bytes))++-- | The bytes of a builder, all of them made, so that the work of making+-- them is done where this is run.+rendered :: Builder -> IO L.ByteString+rendered b = do+ let bytes = toLazyByteString b+ _ <- evaluate (L.length bytes)+ return bytes++-- | The response made of pieces: the bytes of each, in order. The first+-- piece is read before the response is made, and its errors are thrown+-- here. The others are read while the response is written, up to the+-- number given at once, as 'ahead' does. The action given runs when the+-- response ends, however it ends. The response has no @Content-Length@.+piecesResponse :: Int -> ResponseHeaders -> IO () -> [Piece] -> IO Response+piecesResponse n headers done pieces = do (first, rest) <- case pieces of [] -> return (mempty, [])- piece : more -> (,more) <$> piece+ Piece p : more -> do+ bytes <- p >>= id+ return (bytes, more) return . responseStream status200 headers $ \write flush ->- let send bytes [] = write bytes- -- the thread that reads the next piece is let go before going on,- -- or it would keep its piece until the end of the response- send bytes (piece : more) = do- bytes' <- withAsync piece $ \next -> write bytes >> flush >> wait next- send bytes' more- in send first rest `finally` done+ let send (Piece p) = p+ out next = next >>= write >> flush+ in (write first >> flush >> ahead n (map send rest) out) `finally` done +-- | Run actions, up to the number given at once, and hand their results to+-- the last action in order, as each comes. A failure of one is thrown here,+-- in order too: the results before it are handed over first. Actions still+-- running when this ends, however it ends, are cancelled, and a result is+-- let go once it is handed over.+ahead :: Int -> [IO a] -> (a -> IO ()) -> IO ()+ahead n acts consume = do+ running <- newIORef Empty+ let start act = mask_ $ do+ a <- asyncWithUnmask (\unmask -> unmask act)+ modifyIORef' running (|> a)+ go pending =+ readIORef running >>= \case+ Empty -> return ()+ a :<| others -> do+ x <- wait a+ writeIORef running others+ case pending of+ [] -> consume x >> go []+ act : more -> start act >> consume x >> go more+ (first, later) = splitAt (max 1 n) acts+ (mapM_ start first >> go later) `finally` (readIORef running >>= mapM_ cancel)+ -- | Cut a list of keys into pieces of a size, each read with the action -- given: the pieces of items that are read by key. pieced :: Int -> ([k] -> IO b) -> [k] -> [IO b] pieced size fetch = map fetch . cut where cut [] = []- cut ks = let (piece, more) = splitAt (max 1 size) ks in piece : cut more+ cut ks = let (part, more) = splitAt (max 1 size) ks in part : cut more -- | The pieces of a JSON array from pieces of its items: the same bytes as -- the list of all the items encoded at once. A piece may have no items.--- The pieces have to be run in order, as 'piecesResponse' runs them: each--- has to know whether an item came before it, to put a comma.-listPieces :: (b -> Encoding) -> [IO [b]] -> IO [IO Builder]+-- The items of each piece are encoded where it is read; whether a comma+-- comes before them, which depends on whether an item came in the pieces+-- before, is settled in order, as 'piecesResponse' runs the pieces.+listPieces :: (b -> Encoding) -> [IO [b]] -> IO [Piece] listPieces enc pieces = do begun <- newIORef False- let bytes piece = do- items <- piece- was <- readIORef begun- writeIORef begun (was || not (null items))- return . mconcat $- [(if comma then "," else mempty) <> fromEncoding (enc item) | (comma, item) <- zip (was : repeat True) items]- return (around "[" "]" (map bytes pieces))+ let encoded part = Piece $ do+ items <- part+ bytes <- rendered (mconcat (intersperse "," (map (fromEncoding . enc) items)))+ return $ do+ was <- readIORef begun+ let has = not (null items)+ writeIORef begun (was || has)+ return ((if was && has then "," else mempty) <> lazyByteString bytes)+ return (around "[" "]" (map encoded pieces)) -- | Pieces with bytes before the first and after the last, without a piece -- more: the first piece stays the one that is read before the response.-around :: Builder -> Builder -> [IO Builder] -> [IO Builder]+around :: Builder -> Builder -> [Piece] -> [Piece] around open close = \case- [] -> [return (open <> close)]- [only] -> [(\b -> open <> b <> close) <$> only]- first : more -> ((open <>) <$> first) : ending more+ [] -> [piece (return (open <> close))]+ [only] -> [wrap open close only]+ first : more -> wrap open mempty first : ending more where ending [] = []- ending [final] = [(<> close) <$> final]- ending (piece : more) = piece : ending more+ ending [final] = [wrap mempty close final]+ ending (p : more) = p : ending more+ wrap before after (Piece p) = Piece (fmap (fmap (\b -> before <> b <> after)) p) -- | The serialization of a value, in hexadecimal. hexOf :: (Serial a) => a -> Builder
swagger.yaml view
@@ -11,7 +11,7 @@ - url: './' info:- version: &version 1.13.0+ version: &version 1.14.0 title: Haskoin contact: name: JP Rupp
test/Haskoin/Store/Web/PiecesSpec.hs view
@@ -2,11 +2,14 @@ module Haskoin.Store.Web.PiecesSpec (spec) where +import Control.Concurrent (threadDelay)+import Control.Monad (forM_) import Control.Exception (ErrorCall (..), throwIO, try) import Data.Aeson (encode, toEncoding) import Data.ByteString.Builder (Builder, toLazyByteString) import Data.ByteString.Lazy qualified as L-import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.List (sort)+import Data.IORef (IORef, atomicModifyIORef', modifyIORef', newIORef, readIORef) import Haskoin.Store.Web.Pieces import Network.Wai.Internal (Response (..)) import Test.Hspec hiding (around)@@ -15,52 +18,78 @@ spec = describe "a response in pieces" $ do it "has the bytes of its pieces, in order" $ do answer [] `shouldReturn` ("", True)- answer [return "a"] `shouldReturn` ("a", True)- answer (map return ["a", "", "bc", "d"]) `shouldReturn` ("abcd", True)+ answer [plain "a"] `shouldReturn` ("a", True)+ answer (map plain ["a", "", "bc", "d"]) `shouldReturn` ("abcd", True) it "has the bytes of a list encoded at once, for pieces of its items" $ do let lists = [[], [[]], [[1]], [[1, 2], [3]], [[], [1], [], [2, 3], []], [[1 .. 100], [101 .. 150]]] listed :: [[Int]] -> IO (L.ByteString, Bool) listed l = listPieces toEncoding (map return l) >>= answer mapM_ (\l -> listed l `shouldReturn` (encode (concat l), True)) lists+ it "has the same bytes when its pieces take turns to finish" $ do+ -- later pieces finish first, so that what is settled in order, the+ -- commas, is settled after all of them are encoded+ let slow n items = threadDelay (1000 * (5 - n `mod` 5)) >> return items+ l = [[], [1, 2], [], [3], [4 .. 9], [], [10 :: Int]]+ pieces <- listPieces toEncoding (zipWith slow [0 ..] l)+ answer pieces `shouldReturn` (encode (concat l), True) it "cuts keys into pieces of the size, and the last of what is left" $ do read' <- newIORef []- let fetch ks = modifyIORef' read' (<> [ks]) >> return ks+ let fetch ks = atomicModifyIORef' read' (\r -> (ks : r, ())) >> return ks pieces <- listPieces toEncoding (pieced 3 fetch [1 .. 8 :: Int]) answer pieces `shouldReturn` (encode [1 .. 8 :: Int], True)- readIORef read' `shouldReturn` [[1, 2, 3], [4, 5, 6], [7, 8]]+ -- pieces are read at the same time, in no fixed order+ sort <$> readIORef read' `shouldReturn` [[1, 2, 3], [4, 5, 6], [7, 8]] it "puts bytes around pieces without a piece more" $ do- let wrapped ps = around "<" ">" (map return ps)+ let wrapped ps = around "<" ">" (map plain ps) let cases = [[], ["a"], ["a", "b"], ["a", "b", "c"]]- mapM (fmap (toLazyByteString . mconcat) . sequence . wrapped) cases- `shouldReturn` ["<>", "<a>", "<ab>", "<abc>"]+ mapM (fmap fst . answer . wrapped) cases `shouldReturn` ["<>", "<a>", "<ab>", "<abc>"] map (length . wrapped) cases `shouldBe` [1, 1, 2, 3] it "throws what the first piece throws, before there is a response" $ do ended <- newIORef False- r <- try (piecesResponse [] (mark ended) [broken, return "b"])+ r <- try (piecesResponse 2 [] (mark ended) [piece broken, plain "b"]) either (\(ErrorCall e) -> e) (const "") r `shouldBe` "gone" it "ends short, and says that it ended, when a later piece throws" $ do ended <- newIORef False- res <- piecesResponse [] (mark ended) [return "[1", broken]+ res <- piecesResponse 2 [] (mark ended) [plain "[1", plain "2", piece broken, plain "3"] written <- newIORef mempty r <- try (body res (\b -> modifyIORef' written (<> b)) (return ())) either (\(ErrorCall e) -> e) (const "") r `shouldBe` "gone"- (toLazyByteString <$> readIORef written) `shouldReturn` "[1"+ (toLazyByteString <$> readIORef written) `shouldReturn` "[12" readIORef ended `shouldReturn` True- it "reads one piece ahead of the one that it writes, and no further" $ do+ it "reads as many pieces at once as it is told, and no more" $ do+ forM_ [1, 3] $ \n -> do+ now <- newIORef (0 :: Int)+ most <- newIORef 0+ let busy = do+ k <- atomicModifyIORef' now (\c -> (c + 1, c + 1))+ atomicModifyIORef' most (\m -> (max m k, ()))+ threadDelay 2000+ atomicModifyIORef' now (\c -> (c - 1, ()))+ return "x"+ res <- piecesResponse n [] (return ()) (map piece (replicate 10 busy))+ body res (const (return ())) (return ())+ readIORef most `shouldReturn` n+ it "reads no further ahead than it is told, of the piece that it writes" $ do events <- newIORef []- let note e = modifyIORef' events (<> [e])- piece n = note ("read " <> show n) >> return mempty- res <- piecesResponse [] (return ()) (map piece [1 .. 4 :: Int])+ let note e = atomicModifyIORef' events (\es -> (es <> [e], ()))+ read' n = note ("read " <> show n) >> return mempty+ res <- piecesResponse 2 [] (return ()) (map (piece . read') [1 .. 6 :: Int]) body res (const (return ())) (note "flush")- -- the next piece is read while one is written, so which of the two- -- comes first is not fixed; what is fixed is that by the flush of a- -- piece no piece past the next one has been asked for+ -- by the k-th flush, pieces up to k + 2 may have been read: the one+ -- written and the two after it seen <- readIORef events- filter (/= "flush") seen `shouldBe` ["read 1", "read 2", "read 3", "read 4"] let readsBy k = length (filter (/= "flush") (before k seen)) before k = map fst . takeWhile ((< k) . snd) . (zip <*> flushes)- flushes = scanl (\n e -> if e == "flush" then n + 1 else n) (0 :: Int)- map readsBy [1, 2, 3] `shouldSatisfy` and . zipWith (>=) [2, 3, 4]+ flushes = scanl (\c e -> if e == "flush" then c + 1 else c) (0 :: Int)+ map readsBy [1 .. 6] `shouldSatisfy` and . zipWith (>=) [3, 4, 5, 6, 6, 6]+ it "cancels the reads that are still running when a piece fails" $ do+ finished <- newIORef False+ let slow = threadDelay 200000 >> modifyIORef' finished (const True) >> return "late"+ res <- piecesResponse 3 [] (return ()) [plain "a", piece broken, piece slow]+ r <- try (body res (const (return ())) (return ()))+ either (\(ErrorCall e) -> e) (const "") r `shouldBe` "gone"+ threadDelay 300000+ readIORef finished `shouldReturn` False where broken :: IO Builder broken = throwIO (ErrorCall "gone")@@ -69,10 +98,12 @@ body (ResponseStream _ _ run) = run body _ = \_ _ -> expectationFailure "not a stream" -- the bytes of the response, and whether it said that it ended- answer :: [IO Builder] -> IO (L.ByteString, Bool)+ plain :: Builder -> Piece+ plain = piece . return+ answer :: [Piece] -> IO (L.ByteString, Bool) answer pieces = do ended <- newIORef False- res <- piecesResponse [] (mark ended) pieces+ res <- piecesResponse 3 [] (mark ended) pieces written <- newIORef mempty body res (\b -> modifyIORef' written (<> b)) (return ()) (,) . toLazyByteString <$> readIORef written <*> readIORef ended