Skip to content

Commit 8286303

Browse files
authored
smp-server: fix notification store key leak (#1907)
* smp-server: remove expired notification store keys * smp-server: remove delivered notification keys * tests: generate MsgId for ntf store test * smp-server: keep ntf store comments in place * smp-server: strict count of expired notifications
1 parent f795c44 commit 8286303

3 files changed

Lines changed: 79 additions & 20 deletions

File tree

‎src/Simplex/Messaging/Server.hs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt
366366
runDeliverNtfs ms ns' stats
367367
where
368368
runDeliverNtfs :: s -> NtfStore -> ServerStats -> IO ()
369-
runDeliverNtfs ms (NtfStore ns) stats = do
369+
runDeliverNtfs ms ns'@(NtfStore ns) stats = do
370370
ntfs <- M.assocs <$> readTVarIO ns
371371
unless (null ntfs) $
372372
getQueueNtfServices @(StoreQueue s) (queueStore ms) ntfs >>= \case
@@ -378,6 +378,7 @@ smpServer started cfg@ServerConfig {transports, transportConfig = tCfg, startOpt
378378
cIds <- IS.toList <$> readTVarIO subClients
379379
forM_ cIds $ \cId -> getServerClient cId srv >>= mapM_ (deliverQueueNtfs ntfs')
380380
atomically $ modifyTVar' ns (`M.withoutKeys` S.fromList (map fst deleted))
381+
deleteEmptyNtfs ns' ntfs
381382
where
382383
deliverQueueNtfs ntfs' c@Client {ntfSubscriptions} =
383384
whenM (currentClient readTVarIO c) $ do

‎src/Simplex/Messaging/Server/NtfStore.hs‎

Lines changed: 22 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@ module Simplex.Messaging.Server.NtfStore
1010
storeNtf,
1111
deleteNtfs,
1212
deleteExpiredNtfs,
13+
deleteEmptyNtfs,
1314
) where
1415

1516
import Control.Concurrent.STM
1617
import Control.Monad (foldM)
18+
import Data.Functor (($>))
1719
import Data.Int (Int64)
1820
import qualified Data.Map.Strict as M
1921
import Data.Time.Clock.System (SystemTime (..))
@@ -22,6 +24,7 @@ import Simplex.Messaging.Encoding.String
2224
import Simplex.Messaging.Protocol (EncNMsgMeta, MsgId, NotifierId)
2325
import Simplex.Messaging.TMap (TMap)
2426
import qualified Simplex.Messaging.TMap as TM
27+
import Simplex.Messaging.Util (whenM)
2528

2629
newtype NtfStore = NtfStore (TMap NotifierId (TVar [MsgNtf]))
2730

@@ -33,13 +36,11 @@ data MsgNtf = MsgNtf
3336
}
3437

3538
storeNtf :: NtfStore -> NotifierId -> MsgNtf -> IO ()
36-
storeNtf (NtfStore ns) nId ntf = do
37-
TM.lookupIO nId ns >>= atomically . maybe newNtfs (`modifyTVar'` (ntf :))
39+
storeNtf (NtfStore ns) nId ntf =
40+
atomically $ TM.lookup nId ns >>= maybe (TM.insertM nId (newTVar [ntf]) ns) (`modifyTVar'` (ntf :))
3841
-- TODO [ntfdb] coalesce messages here once the client is updated to process multiple messages
3942
-- for single notification.
4043
-- when (isJust prevNtf) $ incStat $ msgNtfReplaced stats
41-
where
42-
newNtfs = TM.lookup nId ns >>= maybe (TM.insertM nId (newTVar [ntf]) ns) (`modifyTVar'` (ntf :))
4344

4445
deleteNtfs :: NtfStore -> NotifierId -> IO Int
4546
deleteNtfs (NtfStore ns) nId = atomically (TM.lookupDelete nId ns) >>= maybe (pure 0) (fmap length . readTVarIO)
@@ -48,18 +49,23 @@ deleteExpiredNtfs :: NtfStore -> Int64 -> IO Int
4849
deleteExpiredNtfs (NtfStore ns) old =
4950
foldM (\expired -> fmap (expired +) . expireQueue) 0 . M.keys =<< readTVarIO ns
5051
where
51-
expireQueue nId = TM.lookupIO nId ns >>= maybe (pure 0) expire
52-
expire v = readTVarIO v >>= \case
53-
[] -> pure 0
54-
_ ->
55-
atomically $ readTVar v >>= \case
56-
[] -> pure 0
57-
-- check the last message first, it is the earliest
58-
ntfs | systemSeconds (ntfTs $ last $ ntfs) < old -> do
59-
let !ntfs' = filter (\MsgNtf {ntfTs = ts} -> systemSeconds ts >= old) ntfs
60-
writeTVar v ntfs'
61-
pure $! length ntfs - length ntfs'
62-
_ -> pure 0
52+
expireQueue nId = atomically $ TM.lookup nId ns >>= maybe (pure 0) (expire nId)
53+
expire nId v = readTVar v >>= \case
54+
[] -> TM.delete nId ns $> 0
55+
-- check the last message first, it is the earliest
56+
ntfs | systemSeconds (ntfTs $ last $ ntfs) < old -> do
57+
let !ntfs' = filter (\MsgNtf {ntfTs = ts} -> systemSeconds ts >= old) ntfs
58+
if null ntfs' then TM.delete nId ns else writeTVar v ntfs'
59+
pure $! length ntfs - length ntfs'
60+
_ -> pure 0
61+
62+
deleteEmptyNtfs :: NtfStore -> [(NotifierId, TVar [MsgNtf])] -> IO ()
63+
deleteEmptyNtfs (NtfStore ns) = mapM_ deleteEmpty
64+
where
65+
deleteEmpty (nId, v) =
66+
whenM (null <$> readTVarIO v) $
67+
atomically $
68+
TM.lookup nId ns >>= mapM_ (\v' -> whenM (null <$> readTVar v') $ TM.delete nId ns)
6369

6470
data NtfLogRecord = NLRv1 NotifierId MsgNtf
6571

‎tests/CoreTests/MsgStoreTests.hs‎

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,24 +24,25 @@ import Crypto.Random (ChaChaDRG)
2424
import Data.ByteString.Char8 (ByteString)
2525
import Data.Int (Int64)
2626
import qualified Data.Map.Strict as M
27-
import Data.Time.Clock.System (getSystemTime)
27+
import Data.Time.Clock.System (SystemTime (..), getSystemTime)
2828
import Simplex.Messaging.Crypto (pattern MaxLenBS)
2929
import qualified Simplex.Messaging.Crypto as C
30-
import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), QueueLinkData, RecipientId, SParty (..), noMsgFlags, randomMsgId)
30+
import Simplex.Messaging.Protocol (EncDataBytes (..), EntityId (..), ErrorType (..), LinkId, Message (..), NotifierId, QueueLinkData, RecipientId, SParty (..), noMsgFlags, randomMsgId)
3131
import Simplex.Messaging.Server.MsgStore.STM
3232
import Simplex.Messaging.Server.MsgStore.Types
33+
import Simplex.Messaging.Server.NtfStore
3334
import Simplex.Messaging.Server.QueueStore
3435
import Simplex.Messaging.Server.QueueStore.QueueInfo
3536
import Simplex.Messaging.Server.QueueStore.STM (STMQueueStore (..))
3637
import Simplex.Messaging.Server.QueueStore.Types
3738
import Simplex.Messaging.TMap (TMap)
39+
import qualified Simplex.Messaging.TMap as TM
3840
import Test.Hspec hiding (fit, it)
3941
import Util
4042

4143
#if defined(dbServerPostgres)
4244
import AgentTests.FunctionalAPITests (runRight)
4345
import Control.Concurrent (threadDelay)
44-
import Data.Time.Clock.System (SystemTime (..))
4546
import Database.PostgreSQL.Simple (Only (..))
4647
import qualified Database.PostgreSQL.Simple as DB
4748
import Simplex.Messaging.Agent.Store.Postgres.Common
@@ -63,6 +64,9 @@ msgStoreTests = do
6364
it "tryDelPeekMsg (ACK not from NSE) should reset message counts when queue is empty" $ withMsgStore testPostgresStoreConfig testResetMessageCounts
6465
it "should expire messages across commit batches" $ withMsgStore testPostgresStoreConfig testExpireMessagesInBatches
6566
#endif
67+
describe "Notification store" $ do
68+
it "should remove keys of expired notifications" testExpireNtfs
69+
it "should remove keys of delivered notifications" testDeleteEmptyNtfs
6670
where
6771
someMsgStoreTests :: MsgStoreClass s => (HasTestEnv => MsgStoreConfig s) -> Spec
6872
someMsgStoreTests cfg = do
@@ -281,6 +285,54 @@ testDeleteQueueMaps ms = do
281285
where
282286
expectAuth = either (`shouldBe` AUTH) (\_ -> expectationFailure "deleted queue is still found")
283287

288+
mkMsgNtf :: TVar ChaChaDRG -> Int64 -> IO MsgNtf
289+
mkMsgNtf g ts = do
290+
ntfMsgId <- atomically $ randomMsgId 24 g
291+
ntfNonce <- atomically $ C.randomCbNonce g
292+
pure MsgNtf {ntfMsgId, ntfTs = MkSystemTime ts 0, ntfNonce, ntfEncMeta = "meta"}
293+
294+
ntfCounts :: NtfStore -> IO [(NotifierId, Int)]
295+
ntfCounts (NtfStore ns) = M.assocs <$> (mapM (fmap length . readTVarIO) =<< readTVarIO ns)
296+
297+
testExpireNtfs :: IO ()
298+
testExpireNtfs = do
299+
g <- C.newRandom
300+
st@(NtfStore ns) <- NtfStore <$> TM.emptyIO
301+
now <- systemSeconds <$> getSystemTime
302+
let old = now - 100
303+
nId1 = EntityId "notifier 1"
304+
nId2 = EntityId "notifier 2"
305+
nId3 = EntityId "notifier 3"
306+
storeNtf st nId1 =<< mkMsgNtf g old
307+
storeNtf st nId2 =<< mkMsgNtf g old
308+
storeNtf st nId2 =<< mkMsgNtf g now
309+
atomically $ TM.insertM nId3 (newTVar []) ns
310+
ntfCounts st `shouldReturn` [(nId1, 1), (nId2, 2), (nId3, 0)]
311+
deleteExpiredNtfs st (now - 50) `shouldReturn` 2
312+
ntfCounts st `shouldReturn` [(nId2, 1)]
313+
storeNtf st nId1 =<< mkMsgNtf g now
314+
deleteExpiredNtfs st (now - 50) `shouldReturn` 0
315+
ntfCounts st `shouldReturn` [(nId1, 1), (nId2, 1)]
316+
317+
testDeleteEmptyNtfs :: IO ()
318+
testDeleteEmptyNtfs = do
319+
g <- C.newRandom
320+
st@(NtfStore ns) <- NtfStore <$> TM.emptyIO
321+
now <- systemSeconds <$> getSystemTime
322+
let nId1 = EntityId "notifier 1"
323+
nId2 = EntityId "notifier 2"
324+
nId3 = EntityId "notifier 3"
325+
nId4 = EntityId "notifier 4"
326+
forM_ ([nId1, nId2, nId3, nId4] :: [NotifierId]) $ \nId -> storeNtf st nId =<< mkMsgNtf g now
327+
ntfs <- M.assocs <$> readTVarIO ns
328+
let flush nId = forM_ (lookup nId ntfs) $ \v -> atomically $ writeTVar v []
329+
mapM_ flush ([nId1, nId2, nId4] :: [NotifierId])
330+
storeNtf st nId2 =<< mkMsgNtf g now
331+
deleteNtfs st nId4 `shouldReturn` 0
332+
storeNtf st nId4 =<< mkMsgNtf g now
333+
deleteEmptyNtfs st ntfs
334+
ntfCounts st `shouldReturn` [(nId2, 1), (nId3, 1), (nId4, 1)]
335+
284336
testLinkData :: QueueLinkData
285337
testLinkData = (EncDataBytes "fixed data", EncDataBytes "user data")
286338

0 commit comments

Comments
 (0)