From 988144e9e7f9f9c22e4f43d5fdcac603d750a217 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Sun, 26 Jul 2020 18:55:23 +0200 Subject: [PATCH 01/35] further relax constrains on RingMap key now needs to be explicitly given at insert, instead of deriving it from the value. This makes it possible to store values where a key cannot be extracted from (HasKeyID) contributes to #62, #32, #41 --- src/Hash2Pub/RingMap.hs | 155 +++++++++++++++++++++------------------- 1 file changed, 80 insertions(+), 75 deletions(-) diff --git a/src/Hash2Pub/RingMap.hs b/src/Hash2Pub/RingMap.hs index 529a68b..9c7f63b 100644 --- a/src/Hash2Pub/RingMap.hs +++ b/src/Hash2Pub/RingMap.hs @@ -10,31 +10,31 @@ import Data.Maybe (fromJust, isJust, isNothing, mapMaybe) -- | Class for all types that can be identified via a EpiChord key. -- Used for restricting the types a 'RingMap' can store -class (Eq a, Show a, Bounded k, Ord k) => HasKeyID a k where +class (Eq a, Show a, Bounded k, Ord k) => HasKeyID k a where getKeyID :: a -> k -- | generic data structure for holding elements with a key and modular lookup -newtype RingMap a k = RingMap { getRingMap :: (HasKeyID a k, Bounded k, Ord k) => Map.Map k (RingEntry a k) } +newtype RingMap k a = RingMap { getRingMap :: (Bounded k, Ord k) => Map.Map k (RingEntry k a) } -instance (HasKeyID a k, Bounded k, Ord k) => Eq (RingMap a k) where +instance (Bounded k, Ord k, Eq a) => Eq (RingMap k a) where a == b = getRingMap a == getRingMap b -instance (HasKeyID a k, Bounded k, Ord k, Show k) => Show (RingMap a k) where +instance (Bounded k, Ord k, Show k, Show a) => Show (RingMap k a) where show rmap = shows "RingMap " (show $ getRingMap rmap) -- | entry of a 'RingMap' that holds a value and can also -- wrap around the lookup direction at the edges of the name space. -data RingEntry a k = KeyEntry a - | ProxyEntry (k, ProxyDirection) (Maybe (RingEntry a k)) +data RingEntry k a = KeyEntry a + | ProxyEntry (k, ProxyDirection) (Maybe (RingEntry k a)) deriving (Show, Eq) -- | as a compromise, only KeyEntry components are ordered by their key -- while ProxyEntry components should never be tried to be ordered. -instance (HasKeyID a k, Eq k, Ord a, Bounded k, Ord k) => Ord (RingEntry a k) where +instance (HasKeyID k a, Eq k, Ord a, Bounded k, Ord k) => Ord (RingEntry k a) where a `compare` b = compare (extractID a) (extractID b) where - extractID :: (HasKeyID a k, Ord a, Bounded k, Ord k) => RingEntry a k -> k + extractID :: (HasKeyID k a, Ord a, Bounded k, Ord k) => RingEntry k a -> k extractID (KeyEntry e) = getKeyID e extractID ProxyEntry{} = error "proxy entries should never appear outside of the RingMap" @@ -49,51 +49,51 @@ instance Enum ProxyDirection where fromEnum Backwards = - 1 fromEnum Forwards = 1 --- | helper function for getting the a from a RingEntry a k -extractRingEntry :: (HasKeyID a k, Bounded k, Ord k) => RingEntry a k -> Maybe a +-- | helper function for getting the a from a RingEntry k a +extractRingEntry :: (Bounded k, Ord k) => RingEntry k a -> Maybe a extractRingEntry (KeyEntry entry) = Just entry extractRingEntry (ProxyEntry _ (Just (KeyEntry entry))) = Just entry extractRingEntry _ = Nothing -- | An empty 'RingMap' needs to be initialised with 2 proxy entries, -- linking the modular name space together by connecting @minBound@ and @maxBound@ -emptyRMap :: (HasKeyID a k, Bounded k, Ord k) => RingMap a k +emptyRMap :: (Bounded k, Ord k) => RingMap k a emptyRMap = RingMap . Map.fromList $ proxyEntry <$> [(maxBound, (minBound, Forwards)), (minBound, (maxBound, Backwards))] where proxyEntry (from,to) = (from, ProxyEntry to Nothing) -- | Maybe returns the entry stored at given key -rMapLookup :: (HasKeyID a k, Bounded k, Ord k) +rMapLookup :: (Bounded k, Ord k) => k -- ^lookup key - -> RingMap a k -- ^lookup cache + -> RingMap k a -- ^lookup cache -> Maybe a rMapLookup key rmap = extractRingEntry =<< Map.lookup key (getRingMap rmap) -- | returns number of present 'KeyEntry' in a properly initialised 'RingMap' -rMapSize :: (HasKeyID a k, Integral i, Bounded k, Ord k) - => RingMap a k +rMapSize :: (Integral i, Bounded k, Ord k) + => RingMap k a -> i rMapSize rmap = fromIntegral $ Map.size innerMap - oneIfEntry rmap minBound - oneIfEntry rmap maxBound where innerMap = getRingMap rmap - oneIfEntry :: (HasKeyID a k, Integral i, Bounded k, Ord k) => RingMap a k -> k -> i + oneIfEntry :: (Integral i, Bounded k, Ord k) => RingMap k a -> k -> i oneIfEntry rmap' nid | isNothing (rMapLookup nid rmap') = 1 | otherwise = 0 -- | a wrapper around lookup functions, making the lookup redirectable by a @ProxyEntry@ -- to simulate a modular ring -lookupWrapper :: (HasKeyID a k, Bounded k, Ord k, Num k) - => (k -> Map.Map k (RingEntry a k) -> Maybe (k, RingEntry a k)) - -> (k -> Map.Map k (RingEntry a k) -> Maybe (k, RingEntry a k)) +lookupWrapper :: (Bounded k, Ord k, Num k) + => (k -> Map.Map k (RingEntry k a) -> Maybe (k, RingEntry k a)) + -> (k -> Map.Map k (RingEntry k a) -> Maybe (k, RingEntry k a)) -> ProxyDirection -> k - -> RingMap a k - -> Maybe a + -> RingMap k a + -> Maybe (k, a) lookupWrapper f fRepeat direction key rmap = case f key $ getRingMap rmap of -- the proxy entry found holds a - Just (_, ProxyEntry _ (Just (KeyEntry entry))) -> Just entry + Just (foundKey, ProxyEntry _ (Just (KeyEntry entry))) -> Just (foundKey, entry) -- proxy entry holds another proxy entry, this should not happen Just (_, ProxyEntry _ (Just (ProxyEntry _ _))) -> Nothing -- proxy entry without own entry is a pointer on where to continue @@ -106,10 +106,10 @@ lookupWrapper f fRepeat direction key rmap = then lookupWrapper fRepeat fRepeat direction newKey rmap else Nothing -- normal entries are returned - Just (_, KeyEntry entry) -> Just entry + Just (foundKey, KeyEntry entry) -> Just (foundKey, entry) Nothing -> Nothing where - rMapNotEmpty :: (HasKeyID a k, Bounded k, Ord k) => RingMap a k -> Bool + rMapNotEmpty :: (Bounded k, Ord k) => RingMap k a -> Bool rMapNotEmpty rmap' = (Map.size (getRingMap rmap') > 2) -- there are more than the 2 ProxyEntries || isJust (rMapLookup minBound rmap') -- or one of the ProxyEntries holds a node || isJust (rMapLookup maxBound rmap') @@ -117,32 +117,34 @@ lookupWrapper f fRepeat direction key rmap = -- | find the successor node to a given key on a modular EpiChord ring. -- Note: The EpiChord definition of "successor" includes the node at the key itself, -- if existing. -rMapLookupSucc :: (HasKeyID a k, Bounded k, Ord k, Num k) +rMapLookupSucc :: (Bounded k, Ord k, Num k) => k -- ^lookup key - -> RingMap a k -- ^ring cache - -> Maybe a + -> RingMap k a -- ^ring cache + -> Maybe (k, a) rMapLookupSucc = lookupWrapper Map.lookupGE Map.lookupGE Forwards -- | find the predecessor node to a given key on a modular EpiChord ring. -rMapLookupPred :: (HasKeyID a k, Bounded k, Ord k, Num k) +rMapLookupPred :: (Bounded k, Ord k, Num k) => k -- ^lookup key - -> RingMap a k -- ^ring cache - -> Maybe a + -> RingMap k a -- ^ring cache + -> Maybe (k, a) rMapLookupPred = lookupWrapper Map.lookupLT Map.lookupLE Backwards -addRMapEntryWith :: (HasKeyID a k, Bounded k, Ord k) - => (RingEntry a k -> RingEntry a k -> RingEntry a k) - -> a - -> RingMap a k - -> RingMap a k -addRMapEntryWith combineFunc entry = RingMap - . Map.insertWith combineFunc (getKeyID entry) (KeyEntry entry) +addRMapEntryWith :: (Bounded k, Ord k) + => (RingEntry k a -> RingEntry k a -> RingEntry k a) + -> k -- ^ key + -> a -- ^ value + -> RingMap k a + -> RingMap k a +addRMapEntryWith combineFunc key entry = RingMap + . Map.insertWith combineFunc key (KeyEntry entry) . getRingMap -addRMapEntry :: (HasKeyID a k, Bounded k, Ord k) - => a - -> RingMap a k - -> RingMap a k +addRMapEntry :: (Bounded k, Ord k) + => k -- ^ key + -> a -- ^ value + -> RingMap k a + -> RingMap k a addRMapEntry = addRMapEntryWith insertCombineFunction where insertCombineFunction newVal oldVal = @@ -151,30 +153,30 @@ addRMapEntry = addRMapEntryWith insertCombineFunction KeyEntry _ -> newVal -addRMapEntries :: (Foldable t, HasKeyID a k, Bounded k, Ord k) - => t a - -> RingMap a k - -> RingMap a k -addRMapEntries entries rmap = foldr' addRMapEntry rmap entries +addRMapEntries :: (Foldable t, Bounded k, Ord k) + => t (k, a) + -> RingMap k a + -> RingMap k a +addRMapEntries entries rmap = foldr' (\(k, v) rmap' -> addRMapEntry k v rmap') rmap entries -setRMapEntries :: (Foldable t, HasKeyID a k, Bounded k, Ord k) - => t a - -> RingMap a k +setRMapEntries :: (Foldable t, Bounded k, Ord k) + => t (k, a) + -> RingMap k a setRMapEntries entries = addRMapEntries entries emptyRMap -deleteRMapEntry :: (HasKeyID a k, Bounded k, Ord k) +deleteRMapEntry :: (Bounded k, Ord k) => k - -> RingMap a k - -> RingMap a k + -> RingMap k a + -> RingMap k a deleteRMapEntry nid = RingMap . Map.update modifier nid . getRingMap where modifier (ProxyEntry idPointer _) = Just (ProxyEntry idPointer Nothing) modifier KeyEntry {} = Nothing -rMapToList :: (HasKeyID a k, Bounded k, Ord k) => RingMap a k -> [a] +rMapToList :: (Bounded k, Ord k) => RingMap k a -> [a] rMapToList = mapMaybe extractRingEntry . Map.elems . getRingMap -rMapFromList :: (HasKeyID a k, Bounded k, Ord k) => [a] -> RingMap a k +rMapFromList :: (Bounded k, Ord k) => [(k, a)] -> RingMap k a rMapFromList = setRMapEntries -- | takes up to i entries from a 'RingMap' by calling a getter function on a @@ -182,49 +184,52 @@ rMapFromList = setRMapEntries -- Stops once i entries have been taken or an entry has been encountered twice -- (meaning the ring has been traversed completely). -- Forms the basis for 'takeRMapSuccessors' and 'takeRMapPredecessors'. -takeRMapEntries_ :: (HasKeyID a k, Integral i, Bounded k, Ord k) - => (k -> RingMap a k -> Maybe a) - -> k - -> i - -> RingMap a k - -> [a] +takeRMapEntries_ :: (Integral i, Bounded k, Ord k) + => (k -> RingMap k a -> Maybe (k, a)) -- ^ parameterisable getter function to determine lookup direction + -> k -- ^ starting key + -> i -- ^ number of maximum values to take + -> RingMap k a + -> [a] -- ^ values taken -- TODO: might be more efficient with dlists takeRMapEntries_ getterFunc startAt num rmap = reverse $ case getterFunc startAt rmap of Nothing -> [] - Just anEntry -> takeEntriesUntil rmap getterFunc (getKeyID anEntry) (getKeyID anEntry) (num-1) [anEntry] + Just (foundKey, anEntry) -> takeEntriesUntil rmap getterFunc foundKey foundKey (num-1) [anEntry] where -- for some reason, just reusing the already-bound @rmap@ and @getterFunc@ -- variables leads to a type error, these need to be passed explicitly - takeEntriesUntil :: (HasKeyID a k, Integral i, Bounded k, Ord k) - => RingMap a k - -> (k -> RingMap a k -> Maybe a) -- getter function + takeEntriesUntil :: (Integral i, Bounded k, Ord k) + => RingMap k a + -> (k -> RingMap k a -> Maybe (k, a)) -- getter function -> k -> k -> i -> [a] -> [a] takeEntriesUntil rmap' getterFunc' havingReached previousEntry remaining takeAcc + -- length limit reached | remaining <= 0 = takeAcc - | getKeyID (fromJust $ getterFunc' previousEntry rmap') == havingReached = takeAcc - | otherwise = let (Just gotEntry) = getterFunc' previousEntry rmap' - in takeEntriesUntil rmap' getterFunc' havingReached (getKeyID gotEntry) (remaining-1) (gotEntry:takeAcc) + -- + | otherwise = case nextEntry of + Just (fKey, gotEntry) + | fKey == havingReached -> takeAcc + | otherwise -> takeEntriesUntil rmap' getterFunc' havingReached fKey (remaining - 1) (gotEntry:takeAcc) + Nothing -> takeAcc + where + nextEntry = getterFunc' previousEntry rmap' -takeRMapPredecessors :: (HasKeyID a k, Integral i, Bounded k, Ord k, Num k) + +takeRMapPredecessors :: (Integral i, Bounded k, Ord k, Num k) => k -> i - -> RingMap a k + -> RingMap k a -> [a] takeRMapPredecessors = takeRMapEntries_ rMapLookupPred -takeRMapSuccessors :: (HasKeyID a k, Integral i, Bounded k, Ord k, Num k) +takeRMapSuccessors :: (Integral i, Bounded k, Ord k, Num k) => k -> i - -> RingMap a k + -> RingMap k a -> [a] takeRMapSuccessors = takeRMapEntries_ rMapLookupSucc --- clean up cache entries: once now - entry > maxAge --- transfer difference now - entry to other node - - From 7878c67635d2e11ef2bcf81783b1ffe7e19cd8ca Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Mon, 27 Jul 2020 00:37:17 +0200 Subject: [PATCH 02/35] adjust rest of code to refactored RingMap --- src/Hash2Pub/DHTProtocol.hs | 21 ++++++++++++--------- src/Hash2Pub/FediChordTypes.hs | 25 ++++++++++++++----------- src/Hash2Pub/PostService.hs | 4 +++- src/Hash2Pub/RingMap.hs | 4 +++- 4 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/Hash2Pub/DHTProtocol.hs b/src/Hash2Pub/DHTProtocol.hs index d69d94c..546c10f 100644 --- a/src/Hash2Pub/DHTProtocol.hs +++ b/src/Hash2Pub/DHTProtocol.hs @@ -130,23 +130,25 @@ closestCachePredecessors remainingLookups lastID nCache -- Looks up the successor of the lookup key on a 'RingMap' representation of the -- predecessor list with the node itself added. If the result is the same as the node -- itself then it falls into the responsibility interval. -isInOwnResponsibilitySlice :: HasKeyID a NodeID => a -> LocalNodeState -> Bool -isInOwnResponsibilitySlice lookupTarget ownNs = (getKeyID <$> rMapLookupSucc (getKeyID lookupTarget :: NodeID) predecessorRMap) == pure (getNid ownNs) +isInOwnResponsibilitySlice :: HasKeyID NodeID a => a -> LocalNodeState -> Bool +isInOwnResponsibilitySlice lookupTarget ownNs = (fst <$> rMapLookupSucc (getKeyID lookupTarget :: NodeID) predecessorRMap) == pure (getNid ownNs) where predecessorList = predecessors ownNs -- add node itself to RingMap representation, to distinguish between -- responsibility of own node and predecessor - predecessorRMap = addRMapEntry (toRemoteNodeState ownNs) $ rMapFromList predecessorList + predecessorRMap = addRMapEntry (getKeyID ownRemote) ownRemote $ rMapFromList (keyValuePair <$> predecessorList) :: RingMap NodeID RemoteNodeState + ownRemote = toRemoteNodeState ownNs closestPredecessor = headMay predecessorList -isPossiblePredecessor :: HasKeyID a NodeID => a -> LocalNodeState -> Bool +isPossiblePredecessor :: HasKeyID NodeID a => a -> LocalNodeState -> Bool isPossiblePredecessor = isInOwnResponsibilitySlice -isPossibleSuccessor :: HasKeyID a NodeID => a -> LocalNodeState -> Bool -isPossibleSuccessor lookupTarget ownNs = (getKeyID <$> rMapLookupPred (getKeyID lookupTarget :: NodeID) successorRMap) == pure (getNid ownNs) +isPossibleSuccessor :: HasKeyID NodeID a => a -> LocalNodeState -> Bool +isPossibleSuccessor lookupTarget ownNs = (fst <$> rMapLookupPred (getKeyID lookupTarget :: NodeID) successorRMap) == pure (getNid ownNs) where successorList = successors ownNs - successorRMap = addRMapEntry (toRemoteNodeState ownNs) $ rMapFromList successorList + successorRMap = addRMapEntry (getKeyID ownRemote) ownRemote $ rMapFromList (keyValuePair <$> successorList) + ownRemote = toRemoteNodeState ownNs closestSuccessor = headMay successorList -- cache operations @@ -169,7 +171,8 @@ addCacheEntryPure now (RemoteCacheEntry ns ts) cache = let -- TODO: limit diffSeconds to some maximum value to prevent malicious nodes from inserting entries valid nearly until eternity timestamp' = if ts <= now then ts else now - newCache = addRMapEntryWith insertCombineFunction (CacheEntry False ns timestamp') cache + newEntry = CacheEntry False ns timestamp' + newCache = addRMapEntryWith insertCombineFunction (getKeyID newEntry) newEntry cache insertCombineFunction newVal@(KeyEntry (CacheEntry newValidationState newNode newTimestamp)) oldVal = case oldVal of ProxyEntry n _ -> ProxyEntry n (Just newVal) @@ -202,7 +205,7 @@ addNodeAsVerifiedPure :: POSIXTime -> RemoteNodeState -> NodeCache -> NodeCache -addNodeAsVerifiedPure now node = addRMapEntry (CacheEntry True node now) +addNodeAsVerifiedPure now node = addRMapEntry (getKeyID node) (CacheEntry True node now) diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index 7652f4f..6e0bef6 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -1,5 +1,6 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} +{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} @@ -26,8 +27,7 @@ module Hash2Pub.FediChordTypes ( , CacheEntry(..) , RingEntry(..) , RingMap(..) - , HasKeyID - , getKeyID + , HasKeyID(..) , rMapSize , rMapLookup , rMapLookupPred @@ -271,31 +271,31 @@ instance Typeable a => Show (TQueue a) where -- | convenience function that replaces the predecessors of a 'LocalNodeState' with the k closest nodes from the provided list setPredecessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState -setPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . rMapFromList . filter ((/=) (getNid ns) . getNid) $ preds} +setPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . rMapFromList . fmap keyValuePair . filter ((/=) (getNid ns) . getNid) $ preds} -- | convenience function that replaces the successors of a 'LocalNodeState' with the k closest nodes from the provided list setSuccessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState -setSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . rMapFromList . filter ((/=) (getNid ns) . getNid) $ succs} +setSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . rMapFromList . fmap keyValuePair . filter ((/=) (getNid ns) . getNid) $ succs} -- | sets the predecessors of a 'LocalNodeState' to the closest k nodes of the current predecessors and the provided list, combined addPredecessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState -addPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . addRMapEntries (filter ((/=) (getNid ns) . getNid) preds) . rMapFromList $ predecessors ns} +addPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . addRMapEntries (keyValuePair <$> filter ((/=) (getNid ns) . getNid) preds) . rMapFromList . fmap keyValuePair $ predecessors ns} -- | sets the successors of a 'LocalNodeState' to the closest k nodes of the current successors and the provided list, combined addSuccessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState -addSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . addRMapEntries (filter ((/=) (getNid ns) . getNid) succs) . rMapFromList $ successors ns} +addSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . addRMapEntries (keyValuePair <$> filter ((/=) (getNid ns) . getNid) succs) . rMapFromList . fmap keyValuePair $ successors ns} -instance HasKeyID RemoteNodeState NodeID where +instance HasKeyID NodeID RemoteNodeState where getKeyID = getNid -instance HasKeyID a k => HasKeyID (CacheEntry a) k where +instance HasKeyID k a => HasKeyID k (CacheEntry a) where getKeyID (CacheEntry _ obj _) = getKeyID obj instance HasKeyID NodeID NodeID where getKeyID = id type NodeCacheEntry = CacheEntry RemoteNodeState -type NodeCache = RingMap NodeCacheEntry NodeID +type NodeCache = RingMap NodeID NodeCacheEntry type LookupCacheEntry = CacheEntry (String, PortNumber) type LookupCache = Map.Map NodeID LookupCacheEntry @@ -319,12 +319,15 @@ cacheLookup = rMapLookup cacheLookupSucc :: NodeID -- ^lookup key -> NodeCache -- ^ring cache -> Maybe NodeCacheEntry -cacheLookupSucc = rMapLookupSucc +cacheLookupSucc key cache = snd <$> rMapLookupSucc key cache cacheLookupPred :: NodeID -- ^lookup key -> NodeCache -- ^ring cache -> Maybe NodeCacheEntry -cacheLookupPred = rMapLookupPred +cacheLookupPred key cache = snd <$> rMapLookupPred key cache + +-- clean up cache entries: once now - entry > maxAge +-- transfer difference now - entry to other node -- | return the @NodeState@ data from a cache entry without checking its validation status cacheGetNodeStateUnvalidated :: CacheEntry RemoteNodeState -> RemoteNodeState diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index e8b325b..21a7238 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -1,15 +1,16 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeOperators #-} -{-# LANGUAGE InstanceSigs #-} module Hash2Pub.PostService where import Control.Concurrent import qualified Data.ByteString.Lazy.UTF8 as BSU +import qualified Data.HashMap.Strict as HMap import Data.Maybe (fromMaybe) import Data.String (fromString) import qualified Data.Text as Txt @@ -18,6 +19,7 @@ import qualified Network.Wai.Handler.Warp as Warp import Servant import Hash2Pub.FediChord +import Hash2Pub.RingMap import Hash2Pub.ServiceTypes diff --git a/src/Hash2Pub/RingMap.hs b/src/Hash2Pub/RingMap.hs index 9c7f63b..016f9f1 100644 --- a/src/Hash2Pub/RingMap.hs +++ b/src/Hash2Pub/RingMap.hs @@ -5,13 +5,15 @@ module Hash2Pub.RingMap where import Data.Foldable (foldr') import qualified Data.Map.Strict as Map -import Data.Maybe (fromJust, isJust, isNothing, mapMaybe) +import Data.Maybe (isJust, isNothing, mapMaybe) -- | Class for all types that can be identified via a EpiChord key. -- Used for restricting the types a 'RingMap' can store class (Eq a, Show a, Bounded k, Ord k) => HasKeyID k a where getKeyID :: a -> k + keyValuePair :: a -> (k, a) + keyValuePair val = (getKeyID val, val) -- | generic data structure for holding elements with a key and modular lookup From 04423171fdbc307b9c0d05d9f3ec16f6453ec5f9 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Mon, 27 Jul 2020 13:20:15 +0200 Subject: [PATCH 03/35] define data types for post and subscription storage --- Hash2Pub.cabal | 2 +- src/Hash2Pub/FediChordTypes.hs | 2 +- src/Hash2Pub/PostService.hs | 22 ++++++++++++++++++++-- src/Hash2Pub/ServiceTypes.hs | 8 +++++++- 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Hash2Pub.cabal b/Hash2Pub.cabal index ebc9c7e..3ca520e 100644 --- a/Hash2Pub.cabal +++ b/Hash2Pub.cabal @@ -46,7 +46,7 @@ category: Network extra-source-files: CHANGELOG.md common deps - build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers + build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable ghc-options: -Wall diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index 6e0bef6..d764b71 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -413,7 +413,7 @@ data FediChordConf = FediChordConf class DHT d where -- | lookup the responsible host handling a given key string, - -- possibly from a lookup cache + -- possiblggy from a lookup cache lookupKey :: d -> String -> IO (Maybe (String, PortNumber)) -- | lookup the responsible host handling a given key string, -- but force the DHT to do a fresh lookup instead of returning a cached result. diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 21a7238..bc1dc23 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -9,16 +9,21 @@ module Hash2Pub.PostService where import Control.Concurrent +import Control.Concurrent.STM +import Control.Concurrent.STM.TChan +import Control.Concurrent.STM.TVar import qualified Data.ByteString.Lazy.UTF8 as BSU import qualified Data.HashMap.Strict as HMap +import qualified Data.HashSet as HSet import Data.Maybe (fromMaybe) import Data.String (fromString) import qualified Data.Text as Txt +import Data.Time.Clock.POSIX import qualified Network.Wai.Handler.Warp as Warp import Servant -import Hash2Pub.FediChord +import Hash2Pub.FediChordTypes import Hash2Pub.RingMap import Hash2Pub.ServiceTypes @@ -29,6 +34,13 @@ data PostService d = PostService -- queues, other data structures , baseDHT :: (DHT d) => d , serviceThread :: ThreadId + , subscribers :: TVar (RingMap NodeID TagSubscribers) + -- ^ for each tag store the subscribers + their queue + , ownSubscriptions :: TVar (HMap.HashMap NodeID POSIXTime) + -- ^ tags subscribed by the own node have an assigned lease time + , ownPosts :: TVar (HSet.HashSet Txt.Text) + -- ^ just store the existence of posts for saving memory, + -- always return the same placeholder } instance DHT d => Service PostService d where @@ -45,12 +57,18 @@ instance DHT d => Service PostService d where } getServicePort s = fromIntegral $ psPort s +type PostContent = Txt.Text +-- | For each handled tag, store its subscribers and provide a +-- broadcast 'TChan' for enqueuing posts +type RelayTags = RingMap NodeID (TagSubscribers, TChan PostContent) +-- | each subscriber is identified by its contact data "hostname" "port" +-- and holds a TChan duplicated from the broadcast TChan of the tag +type TagSubscribers = HMap.HashMap (String, Int) (TChan PostContent) -- | return a WAI application postServiceApplication :: Application postServiceApplication = serve exposedPostServiceAPI postServer -servicePort = 8081 -- | needed for guiding type inference exposedPostServiceAPI :: Proxy PostServiceAPI diff --git a/src/Hash2Pub/ServiceTypes.hs b/src/Hash2Pub/ServiceTypes.hs index ab06052..430dc74 100644 --- a/src/Hash2Pub/ServiceTypes.hs +++ b/src/Hash2Pub/ServiceTypes.hs @@ -1,9 +1,15 @@ {-# LANGUAGE MultiParamTypeClasses #-} module Hash2Pub.ServiceTypes where -import Hash2Pub.FediChord (DHT (..)) +import Data.Hashable (Hashable(..)) + +import Hash2Pub.FediChord (DHT (..), NodeID(..)) class Service s d where -- | run the service runService :: (Integral i) => d -> String -> i -> IO (s d) getServicePort :: (Integral i) => s d -> i + +instance Hashable NodeID where + hashWithSalt salt = hashWithSalt salt . getNodeID + hash = hash . getNodeID From daae9d0b38182985963f896018a46c2435e78a80 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Mon, 27 Jul 2020 21:39:33 +0200 Subject: [PATCH 04/35] process and enqueue incoming posts --- src/Hash2Pub/PostService.hs | 146 ++++++++++++++++++++++------------- src/Hash2Pub/ServiceTypes.hs | 4 +- 2 files changed, 94 insertions(+), 56 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index bc1dc23..fc3e5e8 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -11,16 +11,20 @@ module Hash2Pub.PostService where import Control.Concurrent import Control.Concurrent.STM import Control.Concurrent.STM.TChan +import Control.Concurrent.STM.TQueue import Control.Concurrent.STM.TVar -import qualified Data.ByteString.Lazy.UTF8 as BSU -import qualified Data.HashMap.Strict as HMap -import qualified Data.HashSet as HSet -import Data.Maybe (fromMaybe) -import Data.String (fromString) -import qualified Data.Text as Txt -import Data.Time.Clock.POSIX +import Control.Monad (forM_, forever) +import Control.Monad.IO.Class (liftIO) +import qualified Data.ByteString.Lazy.UTF8 as BSU +import qualified Data.HashMap.Strict as HMap +import qualified Data.HashSet as HSet +import Data.Maybe (fromMaybe) +import Data.String (fromString) +import qualified Data.Text.Lazy as Txt +import Data.Time.Clock.POSIX +import System.Random -import qualified Network.Wai.Handler.Warp as Warp +import qualified Network.Wai.Handler.Warp as Warp import Servant import Hash2Pub.FediChordTypes @@ -29,34 +33,23 @@ import Hash2Pub.ServiceTypes data PostService d = PostService - { psPort :: Warp.Port - , psHost :: String + { psPort :: Warp.Port + , psHost :: String -- queues, other data structures - , baseDHT :: (DHT d) => d - , serviceThread :: ThreadId - , subscribers :: TVar (RingMap NodeID TagSubscribers) + , baseDHT :: (DHT d) => d + , serviceThread :: TVar ThreadId + , subscribers :: TVar (RingMap NodeID TagSubscribers) -- ^ for each tag store the subscribers + their queue , ownSubscriptions :: TVar (HMap.HashMap NodeID POSIXTime) -- ^ tags subscribed by the own node have an assigned lease time - , ownPosts :: TVar (HSet.HashSet Txt.Text) + , ownPosts :: TVar (HSet.HashSet Txt.Text) -- ^ just store the existence of posts for saving memory, - -- always return the same placeholder + , relayInQueue :: TQueue (Hashtag, PostID, PostContent) + -- ^ Queue for processing incoming posts of own instance asynchronously } -instance DHT d => Service PostService d where - runService dht host port = do - let - port' = fromIntegral port - warpSettings = Warp.setPort port' . Warp.setHost (fromString host) $ Warp.defaultSettings - servThread <- forkIO $ Warp.runSettings warpSettings postServiceApplication - pure $ PostService { - psPort = port' - , psHost = host - , baseDHT = dht - , serviceThread = servThread - } - getServicePort s = fromIntegral $ psPort s - +type Hashtag = Txt.Text +type PostID = Txt.Text type PostContent = Txt.Text -- | For each handled tag, store its subscribers and provide a -- broadcast 'TChan' for enqueuing posts @@ -65,9 +58,40 @@ type RelayTags = RingMap NodeID (TagSubscribers, TChan PostContent) -- and holds a TChan duplicated from the broadcast TChan of the tag type TagSubscribers = HMap.HashMap (String, Int) (TChan PostContent) + +instance DHT d => Service PostService d where + -- | initialise 'PostService' data structures and run server + runService dht host port = do + -- create necessary TVars + threadVar <- newTVarIO =<< myThreadId -- own thread ID as placeholder + subscriberVar <- newTVarIO emptyRMap + ownSubsVar <- newTVarIO HMap.empty + ownPostVar <- newTVarIO HSet.empty + relayInQueue' <- newTQueueIO + let + thisService = PostService { + psPort = port' + , psHost = host + , baseDHT = dht + , serviceThread = threadVar + , subscribers = subscriberVar + , ownSubscriptions = ownSubsVar + , ownPosts = ownPostVar + , relayInQueue = relayInQueue' + } + port' = fromIntegral port + warpSettings = Warp.setPort port' . Warp.setHost (fromString host) $ Warp.defaultSettings + servThreadID <- forkIO $ Warp.runSettings warpSettings $ postServiceApplication thisService + -- update thread ID after fork + atomically $ writeTVar threadVar servThreadID + pure thisService + + getServicePort s = fromIntegral $ psPort s + + -- | return a WAI application -postServiceApplication :: Application -postServiceApplication = serve exposedPostServiceAPI postServer +postServiceApplication :: PostService d -> Application +postServiceApplication serv = serve exposedPostServiceAPI $ postServer serv -- | needed for guiding type inference @@ -78,7 +102,7 @@ exposedPostServiceAPI = Proxy -- ========= HTTP API and handlers ============= -type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PostCreated '[PlainText] Txt.Text +type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent -- ^ delivery endpoint of newly published posts of the relay's instance :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> Post '[PlainText] Txt.Text -- ^ endpoint for delivering the subscriptions and outstanding queue @@ -97,37 +121,51 @@ type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> Pos -- the Origin header to $hashtag -postServer :: Server PostServiceAPI -postServer = relayInbox - :<|> subscriptionDelivery - :<|> postFetch - :<|> postMultiFetch - :<|> tagDelivery - :<|> tagSubscribe - :<|> tagUnsubscribe +postServer :: PostService d -> Server PostServiceAPI +postServer service = relayInbox service + :<|> subscriptionDelivery service + :<|> postFetch service + :<|> postMultiFetch service + :<|> tagDelivery service + :<|> tagSubscribe service + :<|> tagUnsubscribe service -relayInbox :: Txt.Text -> Handler Txt.Text -relayInbox post = pure $ "Here be InboxDragons with " <> post +relayInbox :: PostService d -> Txt.Text -> Handler NoContent +relayInbox serv post = do + -- extract contained hashtags + let + containedTags = fmap Txt.tail . filter ((==) '#' . Txt.head) . Txt.words $ post + -- generate post ID + postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^128-1) :: IO Integer) + -- add ID to own posts + liftIO . atomically $ modifyTVar' (ownPosts serv) (HSet.insert postId) + -- enqueue a relay job for each tag + liftIO $ forM_ (containedTags :: [Txt.Text]) (\tag -> + atomically $ writeTQueue (relayInQueue serv) (tag, postId, post) + ) + pure NoContent -subscriptionDelivery :: Txt.Text -> Handler Txt.Text -subscriptionDelivery subList = pure $ "Here be Subscription List dragons: " <> subList -postFetch :: Txt.Text -> Handler Txt.Text -postFetch postID = pure $ "Here be a post with dragon ID " <> postID -postMultiFetch :: Txt.Text -> Handler Txt.Text -postMultiFetch postIDs = pure $ "Here be multiple post dragons: " +subscriptionDelivery :: PostService d -> Txt.Text -> Handler Txt.Text +subscriptionDelivery serv subList = pure $ "Here be Subscription List dragons: " <> subList + +postFetch :: PostService d -> Txt.Text -> Handler Txt.Text +postFetch serv postID = pure $ "Here be a post with dragon ID " <> postID + +postMultiFetch :: PostService d -> Txt.Text -> Handler Txt.Text +postMultiFetch serv postIDs = pure $ "Here be multiple post dragons: " <> (Txt.unwords . Txt.lines $ postIDs) -tagDelivery :: Txt.Text -> Txt.Text -> Handler Txt.Text -tagDelivery hashtag posts = pure $ "Here be #" <> hashtag <> " dragons with " <> posts +tagDelivery :: PostService d -> Txt.Text -> Txt.Text -> Handler Txt.Text +tagDelivery serv hashtag posts = pure $ "Here be #" <> hashtag <> " dragons with " <> posts -tagSubscribe :: Txt.Text -> Maybe Txt.Text -> Handler Integer -tagSubscribe hashtag origin = pure 42 +tagSubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Integer +tagSubscribe serv hashtag origin = pure 42 -tagUnsubscribe :: Txt.Text -> Maybe Txt.Text -> Handler Txt.Text -tagUnsubscribe hashtag origin = pure $ "Here be a dragon unsubscription from " <> fromMaybe "Nothing" origin <> " to " <> hashtag +tagUnsubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Text +tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription from " <> fromMaybe "Nothing" origin <> " to " <> hashtag -- | define how to convert all showable types to PlainText diff --git a/src/Hash2Pub/ServiceTypes.hs b/src/Hash2Pub/ServiceTypes.hs index 430dc74..5e2b37c 100644 --- a/src/Hash2Pub/ServiceTypes.hs +++ b/src/Hash2Pub/ServiceTypes.hs @@ -1,9 +1,9 @@ {-# LANGUAGE MultiParamTypeClasses #-} module Hash2Pub.ServiceTypes where -import Data.Hashable (Hashable(..)) +import Data.Hashable (Hashable (..)) -import Hash2Pub.FediChord (DHT (..), NodeID(..)) +import Hash2Pub.FediChord (DHT (..), NodeID (..)) class Service s d where -- | run the service From 736815ea831bc7fdecd0f9680f3218b70684b6ce Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Mon, 27 Jul 2020 21:49:42 +0200 Subject: [PATCH 05/35] normalise hastag unicode representation of incoming posts --- Hash2Pub.cabal | 2 +- src/Hash2Pub/PostService.hs | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Hash2Pub.cabal b/Hash2Pub.cabal index 3ca520e..56441ad 100644 --- a/Hash2Pub.cabal +++ b/Hash2Pub.cabal @@ -46,7 +46,7 @@ category: Network extra-source-files: CHANGELOG.md common deps - build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable + build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable, unicode-transforms ghc-options: -Wall diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index fc3e5e8..e44c8c6 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -21,6 +21,8 @@ import qualified Data.HashSet as HSet import Data.Maybe (fromMaybe) import Data.String (fromString) import qualified Data.Text.Lazy as Txt +import Data.Text.Normalize (NormalizationMode (NFC), + normalize) import Data.Time.Clock.POSIX import System.Random @@ -135,7 +137,7 @@ relayInbox :: PostService d -> Txt.Text -> Handler NoContent relayInbox serv post = do -- extract contained hashtags let - containedTags = fmap Txt.tail . filter ((==) '#' . Txt.head) . Txt.words $ post + containedTags = fmap (Txt.fromStrict . normalize NFC . Txt.toStrict . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post -- generate post ID postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^128-1) :: IO Integer) -- add ID to own posts From 3b657574061700d83ab671cbaa8e6ce360c97094 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Tue, 28 Jul 2020 02:12:03 +0200 Subject: [PATCH 06/35] worker thread for processing incoming posts in background, started together with web server --- src/Hash2Pub/PostService.hs | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index e44c8c6..8811080 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -9,6 +9,7 @@ module Hash2Pub.PostService where import Control.Concurrent +import Control.Concurrent.Async import Control.Concurrent.STM import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue @@ -83,7 +84,14 @@ instance DHT d => Service PostService d where } port' = fromIntegral port warpSettings = Warp.setPort port' . Warp.setHost (fromString host) $ Warp.defaultSettings - servThreadID <- forkIO $ Warp.runSettings warpSettings $ postServiceApplication thisService + -- Run 'concurrently_' from another thread to be able to return the + -- 'PostService'. + -- Terminating that parent thread will make all child threads terminate as well. + servThreadID <- forkIO $ + concurrently_ + -- web server + (Warp.runSettings warpSettings $ postServiceApplication thisService) + (processIncomingPosts thisService) -- update thread ID after fork atomically $ writeTVar threadVar servThreadID pure thisService @@ -175,3 +183,21 @@ tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription fro -- TODO: figure out how this overlapping stuff actually works https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#instance-overlap instance {-# OVERLAPPABLE #-} Show a => MimeRender PlainText a where mimeRender _ = BSU.fromString . show + + +-- ====== worker threads ====== + +-- | process the pending relays of incoming posts from the internal queue: +-- Look up responsible relay node for given hashtag and forward post to it +processIncomingPosts :: DHT d => PostService d -> IO () +processIncomingPosts serv = forever $ do + -- blocks until available + -- TODO: process multiple in parallel + (t, pID, pC) <- atomically . readTQueue $ relayInQueue serv + lookupRes <- lookupKey (baseDHT serv) (Txt.unpack t) + case lookupRes of + -- no vserver active => wait and retry + Nothing -> threadDelay $ 10 * 10^6 + Just (responsibleHost, responsiblePort) -> do + -- TODO: do actual HTTP requests + pure () From 970c94ff0d51ce90d2d8b4d244087fe3536e1c31 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Tue, 28 Jul 2020 21:39:15 +0200 Subject: [PATCH 07/35] set up subscription data structures and transfer subscription endpoint --- src/Hash2Pub/PostService.hs | 74 +++++++++++++++++++++++++++++++++---- 1 file changed, 67 insertions(+), 7 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 8811080..9be7d1b 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -41,7 +41,7 @@ data PostService d = PostService -- queues, other data structures , baseDHT :: (DHT d) => d , serviceThread :: TVar ThreadId - , subscribers :: TVar (RingMap NodeID TagSubscribers) + , subscribers :: TVar RelayTags -- ^ for each tag store the subscribers + their queue , ownSubscriptions :: TVar (HMap.HashMap NodeID POSIXTime) -- ^ tags subscribed by the own node have an assigned lease time @@ -56,10 +56,10 @@ type PostID = Txt.Text type PostContent = Txt.Text -- | For each handled tag, store its subscribers and provide a -- broadcast 'TChan' for enqueuing posts -type RelayTags = RingMap NodeID (TagSubscribers, TChan PostContent) +type RelayTags = RingMap NodeID (TagSubscribers, TChan PostID, Hashtag) -- | each subscriber is identified by its contact data "hostname" "port" -- and holds a TChan duplicated from the broadcast TChan of the tag -type TagSubscribers = HMap.HashMap (String, Int) (TChan PostContent) +type TagSubscribers = TVar (HMap.HashMap (String, Int) (TChan PostID)) instance DHT d => Service PostService d where @@ -114,7 +114,7 @@ exposedPostServiceAPI = Proxy type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent -- ^ delivery endpoint of newly published posts of the relay's instance - :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> Post '[PlainText] Txt.Text + :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> PostNoContent '[PlainText] NoContent -- ^ endpoint for delivering the subscriptions and outstanding queue :<|> "post" :> Capture "postid" Txt.Text :> Get '[PlainText] Txt.Text -- ^ fetch endpoint for posts, full post ID is http://$domain/post/$postid @@ -145,7 +145,7 @@ relayInbox :: PostService d -> Txt.Text -> Handler NoContent relayInbox serv post = do -- extract contained hashtags let - containedTags = fmap (Txt.fromStrict . normalize NFC . Txt.toStrict . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post + containedTags = fmap (normaliseTag . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post -- generate post ID postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^128-1) :: IO Integer) -- add ID to own posts @@ -158,8 +158,25 @@ relayInbox serv post = do -subscriptionDelivery :: PostService d -> Txt.Text -> Handler Txt.Text -subscriptionDelivery serv subList = pure $ "Here be Subscription List dragons: " <> subList +subscriptionDelivery :: PostService d -> Txt.Text -> Handler NoContent +subscriptionDelivery serv subList = do + let + tagSubs = Txt.lines subList + liftIO $ forM_ tagSubs $ processTag (subscribers serv) + pure NoContent + -- TODO: check and only accept tags in own (future?) responsibility + where + processTag :: TVar RelayTags -> Txt.Text -> IO () + processTag subscriberSTM tagData = do + let + tag:subText:posts:_ = Txt.splitOn "," tagData + sub = read . Txt.unpack $ subText :: (String, Int) + postList = Txt.words posts + enqueueSubscriptions subscriberSTM (normaliseTag tag) sub postList + + + + postFetch :: PostService d -> Txt.Text -> Handler Txt.Text postFetch serv postID = pure $ "Here be a post with dragon ID " <> postID @@ -178,6 +195,49 @@ tagUnsubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Tex tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription from " <> fromMaybe "Nothing" origin <> " to " <> hashtag +-- ======= data structure manipulations ========= + +-- | Write all pending posts of a subscriber-tag-combination to its queue. +-- Sets up all necessary data structures if they are still missing. +enqueueSubscriptions :: TVar RelayTags -- tag-subscriber map + -> Hashtag -- hashtag of pending posts + -> (String, Int) -- subscriber's connection information + -> [PostID] -- pending posts + -> IO () +enqueueSubscriptions tagMapSTM tag subscriber posts = do + -- get the tag output queue and, if necessary, create it + subChan <- atomically setupSubscriberChannel + forM_ posts (atomically . writeTChan subChan) + where + setupSubscriberChannel :: STM (TChan PostID) + setupSubscriberChannel = do + tagMap <- readTVar tagMapSTM + case rMapLookup (genKeyID . Txt.unpack $ tag) tagMap of + Nothing -> do + -- if no collision/ tag doesn't exist yet, just initialize a + -- new subscriber map + broadcastChan <- newBroadcastTChan + tagOutChan <- dupTChan broadcastChan + newSubMapSTM <- newTVar $ HMap.singleton subscriber tagOutChan + writeTVar tagMapSTM $ addRMapEntry (genKeyID . Txt.unpack $ tag) (newSubMapSTM, broadcastChan, tag) tagMap + pure tagOutChan + Just (foundSubMapSTM, broadcastChan, _) -> do + -- otherwise use the existing subscriber map + foundSubMap <- readTVar foundSubMapSTM + case HMap.lookup subscriber foundSubMap of + Nothing -> do + -- for new subscribers, create new output channel + tagOutChan <- dupTChan broadcastChan + writeTVar foundSubMapSTM $ HMap.insert subscriber tagOutChan foundSubMap + pure tagOutChan + -- existing subscriber's channels are just returned + Just tagOutChan -> pure tagOutChan + + +-- normalise the unicode representation of a string to NFC +normaliseTag :: Txt.Text -> Txt.Text +normaliseTag = Txt.fromStrict . normalize NFC . Txt.toStrict + -- | define how to convert all showable types to PlainText -- No idea what I'm doing with these overlappable instances though ¯\_(ツ)_/¯ -- TODO: figure out how this overlapping stuff actually works https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#instance-overlap From 63bc06a88e3e6827c92a4ea51f4ec447de000dc5 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Tue, 28 Jul 2020 23:45:21 +0200 Subject: [PATCH 08/35] implement post fetch (with placeholder content) --- src/Hash2Pub/PostService.hs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 9be7d1b..ef22e29 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -108,7 +108,10 @@ postServiceApplication serv = serve exposedPostServiceAPI $ postServer serv exposedPostServiceAPI :: Proxy PostServiceAPI exposedPostServiceAPI = Proxy +-- ========= constants =========== +placeholderPost :: Txt.Text +placeholderPost = Txt.take 5120 . Txt.repeat $ 'O' -- size 5KiB -- ========= HTTP API and handlers ============= @@ -175,11 +178,13 @@ subscriptionDelivery serv subList = do enqueueSubscriptions subscriberSTM (normaliseTag tag) sub postList - - - postFetch :: PostService d -> Txt.Text -> Handler Txt.Text -postFetch serv postID = pure $ "Here be a post with dragon ID " <> postID +postFetch serv postID = do + postSet <- liftIO . readTVarIO . ownPosts $ serv + if HSet.member postID postSet + -- decision: always return the same placeholder post + then pure placeholderPost + else throwError $ err404 { errBody = "No post found with this ID" } postMultiFetch :: PostService d -> Txt.Text -> Handler Txt.Text postMultiFetch serv postIDs = pure $ "Here be multiple post dragons: " From bd70e2dff02ea98b7d892d3a97d92f6df84fd4fe Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 29 Jul 2020 00:06:16 +0200 Subject: [PATCH 09/35] implement multiple post fetch (with placeholder content) --- src/Hash2Pub/PostService.hs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index ef22e29..169d2b7 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -14,7 +14,7 @@ import Control.Concurrent.STM import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue import Control.Concurrent.STM.TVar -import Control.Monad (forM_, forever) +import Control.Monad (foldM, forM_, forever) import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Lazy.UTF8 as BSU import qualified Data.HashMap.Strict as HMap @@ -150,7 +150,7 @@ relayInbox serv post = do let containedTags = fmap (normaliseTag . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post -- generate post ID - postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^128-1) :: IO Integer) + postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^(128::Integer)-1) :: IO Integer) -- add ID to own posts liftIO . atomically $ modifyTVar' (ownPosts serv) (HSet.insert postId) -- enqueue a relay job for each tag @@ -186,9 +186,17 @@ postFetch serv postID = do then pure placeholderPost else throwError $ err404 { errBody = "No post found with this ID" } + postMultiFetch :: PostService d -> Txt.Text -> Handler Txt.Text -postMultiFetch serv postIDs = pure $ "Here be multiple post dragons: " - <> (Txt.unwords . Txt.lines $ postIDs) +postMultiFetch serv postIDs = do + let idList = Txt.lines postIDs + postSet <- liftIO . readTVarIO . ownPosts $ serv + -- look up existence of all given post IDs, fail if even one is missing + foldM (\response postID -> + if HSet.member postID postSet + then pure $ placeholderPost <> "\n" <> response + else throwError $ err404 { errBody = "No post found with this ID" } + ) "" idList tagDelivery :: PostService d -> Txt.Text -> Txt.Text -> Handler Txt.Text tagDelivery serv hashtag posts = pure $ "Here be #" <> hashtag <> " dragons with " <> posts From ad52a017aa18c92188ddf89a3edc8e16340d1132 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 29 Jul 2020 22:15:14 +0200 Subject: [PATCH 10/35] add relay inbox endpoint --- src/Hash2Pub/PostService.hs | 74 ++++++++++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 18 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 169d2b7..059ebe5 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -56,10 +56,11 @@ type PostID = Txt.Text type PostContent = Txt.Text -- | For each handled tag, store its subscribers and provide a -- broadcast 'TChan' for enqueuing posts -type RelayTags = RingMap NodeID (TagSubscribers, TChan PostID, Hashtag) +type RelayTags = RingMap NodeID (TagSubscribersSTM, TChan PostID, Hashtag) +type TagSubscribersSTM = TVar TagSubscribers -- | each subscriber is identified by its contact data "hostname" "port" -- and holds a TChan duplicated from the broadcast TChan of the tag -type TagSubscribers = TVar (HMap.HashMap (String, Int) (TChan PostID)) +type TagSubscribers = (HMap.HashMap (String, Int) (TChan PostID)) instance DHT d => Service PostService d where @@ -115,7 +116,7 @@ placeholderPost = Txt.take 5120 . Txt.repeat $ 'O' -- size 5KiB -- ========= HTTP API and handlers ============= -type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent +type PostServiceAPI = "relay" :> "inbox" :> Capture "hashtag" Txt.Text :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent -- ^ delivery endpoint of newly published posts of the relay's instance :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> PostNoContent '[PlainText] NoContent -- ^ endpoint for delivering the subscriptions and outstanding queue @@ -123,6 +124,8 @@ type PostServiceAPI = "relay" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> Put -- ^ fetch endpoint for posts, full post ID is http://$domain/post/$postid :<|> "posts" :> ReqBody '[PlainText] Txt.Text :> Post '[PlainText] Txt.Text -- ^ endpoint for fetching multiple posts at once + :<|> "posts" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent + -- ^ delivery endpoint of newly published posts of the relay's instance :<|> "tags" :> Capture "hashtag" Txt.Text :> ReqBody '[PlainText] Txt.Text :> PostCreated '[PlainText] Txt.Text -- ^ delivery endpoint for posts of $tag at subscribing instance :<|> "tags" :> Capture "hashtag" Txt.Text :> "subscribe" :> Header "Origin" Txt.Text :> Get '[PlainText] Integer @@ -139,28 +142,28 @@ postServer service = relayInbox service :<|> subscriptionDelivery service :<|> postFetch service :<|> postMultiFetch service + :<|> postInbox service :<|> tagDelivery service :<|> tagSubscribe service :<|> tagUnsubscribe service -relayInbox :: PostService d -> Txt.Text -> Handler NoContent -relayInbox serv post = do - -- extract contained hashtags +relayInbox :: PostService d -> Hashtag -> Txt.Text -> Handler NoContent +relayInbox serv tag posts = do let - containedTags = fmap (normaliseTag . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post - -- generate post ID - postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^(128::Integer)-1) :: IO Integer) - -- add ID to own posts - liftIO . atomically $ modifyTVar' (ownPosts serv) (HSet.insert postId) - -- enqueue a relay job for each tag - liftIO $ forM_ (containedTags :: [Txt.Text]) (\tag -> - atomically $ writeTQueue (relayInQueue serv) (tag, postId, post) - ) + -- skip checking whether the post actually contains the tag, just drop full post + postIDs = head . Txt.splitOn "," <$> Txt.lines posts + broadcastChan <- liftIO $ atomically $ getTagBroadcastChannel serv tag + -- if tag is not in own responsibility, return a 410 Gone + maybe + (throwError $ err410 { errBody = "Relay is not responsible for this tag"}) + -- otherwise enqueue posts into broadcast queue of the tag + (\queue -> + liftIO $ forM_ postIDs (atomically . writeTChan queue) + ) + broadcastChan pure NoContent - - subscriptionDelivery :: PostService d -> Txt.Text -> Handler NoContent subscriptionDelivery serv subList = do let @@ -198,6 +201,23 @@ postMultiFetch serv postIDs = do else throwError $ err404 { errBody = "No post found with this ID" } ) "" idList + +postInbox :: PostService d -> Txt.Text -> Handler NoContent +postInbox serv post = do + -- extract contained hashtags + let + containedTags = fmap (normaliseTag . Txt.tail) . filter ((==) '#' . Txt.head) . Txt.words $ post + -- generate post ID + postId <- liftIO $ Txt.pack . show <$> (randomRIO (0, 2^(128::Integer)-1) :: IO Integer) + -- add ID to own posts + liftIO . atomically $ modifyTVar' (ownPosts serv) (HSet.insert postId) + -- enqueue a relay job for each tag + liftIO $ forM_ (containedTags :: [Txt.Text]) (\tag -> + atomically $ writeTQueue (relayInQueue serv) (tag, postId, post) + ) + pure NoContent + + tagDelivery :: PostService d -> Txt.Text -> Txt.Text -> Handler Txt.Text tagDelivery serv hashtag posts = pure $ "Here be #" <> hashtag <> " dragons with " <> posts @@ -225,7 +245,7 @@ enqueueSubscriptions tagMapSTM tag subscriber posts = do setupSubscriberChannel :: STM (TChan PostID) setupSubscriberChannel = do tagMap <- readTVar tagMapSTM - case rMapLookup (genKeyID . Txt.unpack $ tag) tagMap of + case lookupRelayTags tag tagMap of Nothing -> do -- if no collision/ tag doesn't exist yet, just initialize a -- new subscriber map @@ -247,6 +267,24 @@ enqueueSubscriptions tagMapSTM tag subscriber posts = do Just tagOutChan -> pure tagOutChan +-- | returns the broadcast channel of a hashtag if there are any subscribers to it +getTagBroadcastChannel :: PostService d -> Hashtag -> STM (Maybe (TChan PostID)) +getTagBroadcastChannel serv tag = do + tagMap <- readTVar $ subscribers serv + case lookupRelayTags tag tagMap of + Nothing -> pure Nothing + Just (subscriberSTM, broadcastChan, _) -> do + subscriberMap <- readTVar subscriberSTM + if HMap.null subscriberMap + then pure Nothing + else pure (Just broadcastChan) + + +-- | look up the subscription data of a tag +lookupRelayTags :: Hashtag -> RelayTags -> Maybe (TagSubscribersSTM, TChan PostID, Hashtag) +lookupRelayTags tag = rMapLookup (genKeyID . Txt.unpack $ tag) + + -- normalise the unicode representation of a string to NFC normaliseTag :: Txt.Text -> Txt.Text normaliseTag = Txt.fromStrict . normalize NFC . Txt.toStrict From da47f8062fc155f3d4b163b4fb9770969f423c23 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 29 Jul 2020 23:06:07 +0200 Subject: [PATCH 11/35] add lease time to subscription entries --- src/Hash2Pub/PostService.hs | 67 ++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 30 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 059ebe5..81b00a3 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -60,7 +60,8 @@ type RelayTags = RingMap NodeID (TagSubscribersSTM, TChan PostID, Hashtag) type TagSubscribersSTM = TVar TagSubscribers -- | each subscriber is identified by its contact data "hostname" "port" -- and holds a TChan duplicated from the broadcast TChan of the tag -type TagSubscribers = (HMap.HashMap (String, Int) (TChan PostID)) +-- + an expiration timestamp +type TagSubscribers = (HMap.HashMap (String, Int) (TChan PostID, POSIXTime)) instance DHT d => Service PostService d where @@ -175,10 +176,12 @@ subscriptionDelivery serv subList = do processTag :: TVar RelayTags -> Txt.Text -> IO () processTag subscriberSTM tagData = do let - tag:subText:posts:_ = Txt.splitOn "," tagData + tag:subText:lease:posts:_ = Txt.splitOn "," tagData + -- ignore checking of lease time + leaseTime = fromIntegral (read . Txt.unpack $ lease :: Integer) sub = read . Txt.unpack $ subText :: (String, Int) postList = Txt.words posts - enqueueSubscriptions subscriberSTM (normaliseTag tag) sub postList + enqueueSubscription subscriberSTM (normaliseTag tag) sub postList leaseTime postFetch :: PostService d -> Txt.Text -> Handler Txt.Text @@ -232,39 +235,43 @@ tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription fro -- | Write all pending posts of a subscriber-tag-combination to its queue. -- Sets up all necessary data structures if they are still missing. -enqueueSubscriptions :: TVar RelayTags -- tag-subscriber map +enqueueSubscription :: TVar RelayTags -- tag-subscriber map -> Hashtag -- hashtag of pending posts -> (String, Int) -- subscriber's connection information -> [PostID] -- pending posts + -> POSIXTime -- lease expiry time -> IO () -enqueueSubscriptions tagMapSTM tag subscriber posts = do +enqueueSubscription tagMapSTM tag subscriber posts leaseTime = do -- get the tag output queue and, if necessary, create it - subChan <- atomically setupSubscriberChannel + subChan <- atomically $ setupSubscriberChannel tagMapSTM tag subscriber leaseTime forM_ posts (atomically . writeTChan subChan) - where - setupSubscriberChannel :: STM (TChan PostID) - setupSubscriberChannel = do - tagMap <- readTVar tagMapSTM - case lookupRelayTags tag tagMap of - Nothing -> do - -- if no collision/ tag doesn't exist yet, just initialize a - -- new subscriber map - broadcastChan <- newBroadcastTChan - tagOutChan <- dupTChan broadcastChan - newSubMapSTM <- newTVar $ HMap.singleton subscriber tagOutChan - writeTVar tagMapSTM $ addRMapEntry (genKeyID . Txt.unpack $ tag) (newSubMapSTM, broadcastChan, tag) tagMap - pure tagOutChan - Just (foundSubMapSTM, broadcastChan, _) -> do - -- otherwise use the existing subscriber map - foundSubMap <- readTVar foundSubMapSTM - case HMap.lookup subscriber foundSubMap of - Nothing -> do - -- for new subscribers, create new output channel - tagOutChan <- dupTChan broadcastChan - writeTVar foundSubMapSTM $ HMap.insert subscriber tagOutChan foundSubMap - pure tagOutChan - -- existing subscriber's channels are just returned - Just tagOutChan -> pure tagOutChan + + +-- | STM operation to return the outgoing post queue of a tag to a specified subscriber. +-- If the queue doesn't exist yet, all necessary data structures are set up accordingly. +setupSubscriberChannel :: TVar RelayTags -> Hashtag -> (String, Int) -> POSIXTime -> STM (TChan PostID) +setupSubscriberChannel tagMapSTM tag subscriber leaseTime = do + tagMap <- readTVar tagMapSTM + case lookupRelayTags tag tagMap of + Nothing -> do + -- if no collision/ tag doesn't exist yet, just initialize a + -- new subscriber map + broadcastChan <- newBroadcastTChan + tagOutChan <- dupTChan broadcastChan + newSubMapSTM <- newTVar $ HMap.singleton subscriber (tagOutChan, leaseTime) + writeTVar tagMapSTM $ addRMapEntry (genKeyID . Txt.unpack $ tag) (newSubMapSTM, broadcastChan, tag) tagMap + pure tagOutChan + Just (foundSubMapSTM, broadcastChan, _) -> do + -- otherwise use the existing subscriber map + foundSubMap <- readTVar foundSubMapSTM + case HMap.lookup subscriber foundSubMap of + Nothing -> do + -- for new subscribers, create new output channel + tagOutChan <- dupTChan broadcastChan + writeTVar foundSubMapSTM $ HMap.insert subscriber (tagOutChan, leaseTime) foundSubMap + pure tagOutChan + -- existing subscriber's channels are just returned + Just (tagOutChan, _) -> pure tagOutChan -- | returns the broadcast channel of a hashtag if there are any subscribers to it From 98ca0ff13e2996aa45d7bcfab695143689ae8650 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 30 Jul 2020 01:21:56 +0200 Subject: [PATCH 12/35] service config, integrate service launch into DHT launch TODO: hold a reference from DHT to service --- Hash2Pub.cabal | 2 +- app/Main.hs | 20 +++++++++++++++----- src/Hash2Pub/FediChord.hs | 11 +++++++++-- src/Hash2Pub/FediChordTypes.hs | 25 +++++++++++++++++++++++++ src/Hash2Pub/PostService.hs | 15 ++++++--------- src/Hash2Pub/ServiceTypes.hs | 15 --------------- 6 files changed, 56 insertions(+), 32 deletions(-) delete mode 100644 src/Hash2Pub/ServiceTypes.hs diff --git a/Hash2Pub.cabal b/Hash2Pub.cabal index 56441ad..54cb29d 100644 --- a/Hash2Pub.cabal +++ b/Hash2Pub.cabal @@ -55,7 +55,7 @@ library import: deps -- Modules exported by the library. - exposed-modules: Hash2Pub.FediChord, Hash2Pub.FediChordTypes, Hash2Pub.DHTProtocol, Hash2Pub.ASN1Coding, Hash2Pub.ProtocolTypes, Hash2Pub.PostService, Hash2Pub.ServiceTypes, Hash2Pub.RingMap + exposed-modules: Hash2Pub.FediChord, Hash2Pub.FediChordTypes, Hash2Pub.DHTProtocol, Hash2Pub.ASN1Coding, Hash2Pub.ProtocolTypes, Hash2Pub.PostService, Hash2Pub.RingMap -- Modules included in this library but not exported. other-modules: Hash2Pub.Utils diff --git a/app/Main.hs b/app/Main.hs index 8887ee8..98961c0 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -10,15 +10,17 @@ import Data.IP (IPv6, toHostAddress6) import System.Environment import Hash2Pub.FediChord +import Hash2Pub.FediChordTypes +import Hash2Pub.PostService (PostService (..)) main :: IO () main = do -- ToDo: parse and pass config -- probably use `tomland` for that - conf <- readConfig + (fConf, sConf) <- readConfig -- TODO: first initialise 'RealNode', then the vservers -- ToDo: load persisted caches, bootstrapping nodes … - (serverSock, thisNode) <- fediChordInit conf + (serverSock, thisNode) <- fediChordInit fConf (runService sConf :: DHT d => d -> IO (PostService d)) -- currently no masking is necessary, as there is nothing to clean up nodeCacheWriterThread <- forkIO $ nodeCacheWriter thisNode -- try joining the DHT using one of the provided bootstrapping nodes @@ -41,10 +43,11 @@ main = do pure () -readConfig :: IO FediChordConf +readConfig :: IO (FediChordConf, ServiceConf) readConfig = do - confDomainString : ipString : portString : bootstrapHost : bootstrapPortString : _ <- getArgs - pure $ FediChordConf { + confDomainString : ipString : portString : bootstrapHost : bootstrapPortString : servicePortString : speedup : _ <- getArgs + let + fConf = FediChordConf { confDomain = confDomainString , confIP = toHostAddress6 . read $ ipString , confDhtPort = read portString @@ -53,3 +56,10 @@ readConfig = do , confBootstrapSamplingInterval = 180 , confMaxLookupCacheAge = 300 } + sConf = ServiceConf { + confSubscriptionExpiryTime = 2*3600 `div` read speedup + , confServicePort = read servicePortString + , confServiceHost = confDomainString + } + pure (fConf, sConf) + diff --git a/src/Hash2Pub/FediChord.hs b/src/Hash2Pub/FediChord.hs index 26a373c..7a5abb0 100644 --- a/src/Hash2Pub/FediChord.hs +++ b/src/Hash2Pub/FediChord.hs @@ -95,16 +95,23 @@ import Debug.Trace (trace) -- | initialise data structures, compute own IDs and bind to listening socket -- ToDo: load persisted state, thus this function already operates in IO -fediChordInit :: FediChordConf -> IO (Socket, LocalNodeStateSTM) -fediChordInit initConf = do +--fediChordInit :: (DHT d, Service s d) +-- => FediChordConf +-- -> (d -> s d) -- ^ runner function for service +-- -> IO (Socket, LocalNodeStateSTM) +fediChordInit initConf serviceRunner = do emptyLookupCache <- newTVarIO Map.empty let realNode = RealNode { vservers = [] , nodeConfig = initConf , bootstrapNodes = confBootstrapNodes initConf , lookupCacheSTM = emptyLookupCache + --, service = undefined } realNodeSTM <- newTVarIO realNode + -- launch service and set the reference in the RealNode + serv <- serviceRunner realNodeSTM + --atomically . writeTVar $ realNode { service = serv } initialState <- nodeStateInit realNodeSTM initialStateSTM <- newTVarIO initialState serverSock <- mkServerSocket (getIpAddr initialState) (getDhtPort initialState) diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index d764b71..604519e 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -58,11 +58,14 @@ module Hash2Pub.FediChordTypes ( , bsAsIpAddr , FediChordConf(..) , DHT(..) + , Service(..) + , ServiceConf(..) ) where import Control.Exception import Data.Foldable (foldr') import Data.Function (on) +import qualified Data.Hashable as Hashable import Data.List (delete, nub, sortBy) import qualified Data.Map.Strict as Map import Data.Maybe (fromJust, fromMaybe, isJust, @@ -144,6 +147,7 @@ a `localCompare` b -- | Data for managing the virtual server nodes of this real node. -- Also contains shared data and config values. -- TODO: more data structures for k-choices bookkeeping +--data RealNode s = RealNode data RealNode = RealNode { vservers :: [LocalNodeStateSTM] -- ^ references to all active versers @@ -155,6 +159,7 @@ data RealNode = RealNode -- ^ a global cache of looked up keys and their associated nodes } +--type RealNodeSTM s = TVar (RealNode s) type RealNodeSTM = TVar RealNode -- | represents a node and all its important state @@ -411,6 +416,26 @@ data FediChordConf = FediChordConf } deriving (Show, Eq) +-- ====== Service Types ============ + +class Service s d where + -- | run the service + runService :: ServiceConf -> d -> IO (s d) + getServicePort' :: (Integral i) => s d -> i + +instance Hashable.Hashable NodeID where + hashWithSalt salt = Hashable.hashWithSalt salt . getNodeID + hash = Hashable.hash . getNodeID + +data ServiceConf = ServiceConf + { confSubscriptionExpiryTime :: Integer + -- ^ subscription lease expiration in seconds + , confServicePort :: Int + -- ^ listening port for service + , confServiceHost :: String + -- ^ hostname of service + } + class DHT d where -- | lookup the responsible host handling a given key string, -- possiblggy from a lookup cache diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 81b00a3..264bccb 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -32,12 +32,10 @@ import Servant import Hash2Pub.FediChordTypes import Hash2Pub.RingMap -import Hash2Pub.ServiceTypes data PostService d = PostService - { psPort :: Warp.Port - , psHost :: String + { serviceConf :: ServiceConf -- queues, other data structures , baseDHT :: (DHT d) => d , serviceThread :: TVar ThreadId @@ -66,7 +64,7 @@ type TagSubscribers = (HMap.HashMap (String, Int) (TChan PostID, POSIXTime)) instance DHT d => Service PostService d where -- | initialise 'PostService' data structures and run server - runService dht host port = do + runService conf dht = do -- create necessary TVars threadVar <- newTVarIO =<< myThreadId -- own thread ID as placeholder subscriberVar <- newTVarIO emptyRMap @@ -75,8 +73,7 @@ instance DHT d => Service PostService d where relayInQueue' <- newTQueueIO let thisService = PostService { - psPort = port' - , psHost = host + serviceConf = conf , baseDHT = dht , serviceThread = threadVar , subscribers = subscriberVar @@ -84,8 +81,8 @@ instance DHT d => Service PostService d where , ownPosts = ownPostVar , relayInQueue = relayInQueue' } - port' = fromIntegral port - warpSettings = Warp.setPort port' . Warp.setHost (fromString host) $ Warp.defaultSettings + port' = fromIntegral (confServicePort conf) + warpSettings = Warp.setPort port' . Warp.setHost (fromString . confServiceHost $ conf) $ Warp.defaultSettings -- Run 'concurrently_' from another thread to be able to return the -- 'PostService'. -- Terminating that parent thread will make all child threads terminate as well. @@ -98,7 +95,7 @@ instance DHT d => Service PostService d where atomically $ writeTVar threadVar servThreadID pure thisService - getServicePort s = fromIntegral $ psPort s + getServicePort' = fromIntegral . confServicePort . serviceConf -- | return a WAI application diff --git a/src/Hash2Pub/ServiceTypes.hs b/src/Hash2Pub/ServiceTypes.hs deleted file mode 100644 index 5e2b37c..0000000 --- a/src/Hash2Pub/ServiceTypes.hs +++ /dev/null @@ -1,15 +0,0 @@ -{-# LANGUAGE MultiParamTypeClasses #-} -module Hash2Pub.ServiceTypes where - -import Data.Hashable (Hashable (..)) - -import Hash2Pub.FediChord (DHT (..), NodeID (..)) - -class Service s d where - -- | run the service - runService :: (Integral i) => d -> String -> i -> IO (s d) - getServicePort :: (Integral i) => s d -> i - -instance Hashable NodeID where - hashWithSalt salt = hashWithSalt salt . getNodeID - hash = hash . getNodeID From 4bf80911432da8db7b1d5bc9278885310c1517c7 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 30 Jul 2020 01:30:42 +0200 Subject: [PATCH 13/35] fix type signature of fediChordInit --- src/Hash2Pub/FediChord.hs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Hash2Pub/FediChord.hs b/src/Hash2Pub/FediChord.hs index 7a5abb0..70c9ff7 100644 --- a/src/Hash2Pub/FediChord.hs +++ b/src/Hash2Pub/FediChord.hs @@ -95,10 +95,10 @@ import Debug.Trace (trace) -- | initialise data structures, compute own IDs and bind to listening socket -- ToDo: load persisted state, thus this function already operates in IO ---fediChordInit :: (DHT d, Service s d) --- => FediChordConf --- -> (d -> s d) -- ^ runner function for service --- -> IO (Socket, LocalNodeStateSTM) +fediChordInit :: (Service s RealNodeSTM) + => FediChordConf + -> (RealNodeSTM -> IO (s RealNodeSTM)) -- ^ runner function for service + -> IO (Socket, LocalNodeStateSTM) fediChordInit initConf serviceRunner = do emptyLookupCache <- newTVarIO Map.empty let realNode = RealNode { From 5ffe1b074e723f8ffaa29716baf066fe08f79a7d Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 30 Jul 2020 02:19:26 +0200 Subject: [PATCH 14/35] add reference from RealNode to Service This required to make both RealNode(STM) and LocalNodeState(STM) parameterisable polymorphic types --- src/Hash2Pub/DHTProtocol.hs | 44 +++++++++++++------------- src/Hash2Pub/FediChord.hs | 57 ++++++++++++++++------------------ src/Hash2Pub/FediChordTypes.hs | 30 +++++++++--------- src/Hash2Pub/PostService.hs | 2 ++ test/FediChordSpec.hs | 2 +- 5 files changed, 68 insertions(+), 67 deletions(-) diff --git a/src/Hash2Pub/DHTProtocol.hs b/src/Hash2Pub/DHTProtocol.hs index 546c10f..f962d58 100644 --- a/src/Hash2Pub/DHTProtocol.hs +++ b/src/Hash2Pub/DHTProtocol.hs @@ -92,7 +92,7 @@ import Debug.Trace (trace) -- TODO: evaluate more fine-grained argument passing to allow granular locking -- | look up an ID to either claim responsibility for it or return the closest l nodes from the local cache -queryLocalCache :: LocalNodeState -> NodeCache -> Int -> NodeID -> QueryResponse +queryLocalCache :: LocalNodeState s -> NodeCache -> Int -> NodeID -> QueryResponse queryLocalCache ownState nCache lBestNodes targetID -- as target ID falls between own ID and first predecessor, it is handled by this node -- This only makes sense if the node is part of the DHT by having joined. @@ -130,7 +130,7 @@ closestCachePredecessors remainingLookups lastID nCache -- Looks up the successor of the lookup key on a 'RingMap' representation of the -- predecessor list with the node itself added. If the result is the same as the node -- itself then it falls into the responsibility interval. -isInOwnResponsibilitySlice :: HasKeyID NodeID a => a -> LocalNodeState -> Bool +isInOwnResponsibilitySlice :: HasKeyID NodeID a => a -> LocalNodeState s -> Bool isInOwnResponsibilitySlice lookupTarget ownNs = (fst <$> rMapLookupSucc (getKeyID lookupTarget :: NodeID) predecessorRMap) == pure (getNid ownNs) where predecessorList = predecessors ownNs @@ -140,10 +140,10 @@ isInOwnResponsibilitySlice lookupTarget ownNs = (fst <$> rMapLookupSucc (getKeyI ownRemote = toRemoteNodeState ownNs closestPredecessor = headMay predecessorList -isPossiblePredecessor :: HasKeyID NodeID a => a -> LocalNodeState -> Bool +isPossiblePredecessor :: HasKeyID NodeID a => a -> LocalNodeState s -> Bool isPossiblePredecessor = isInOwnResponsibilitySlice -isPossibleSuccessor :: HasKeyID NodeID a => a -> LocalNodeState -> Bool +isPossibleSuccessor :: HasKeyID NodeID a => a -> LocalNodeState s -> Bool isPossibleSuccessor lookupTarget ownNs = (fst <$> rMapLookupPred (getKeyID lookupTarget :: NodeID) successorRMap) == pure (getNid ownNs) where successorList = successors ownNs @@ -224,7 +224,7 @@ markCacheEntryAsVerified timestamp nid = RingMap . Map.adjust adjustFunc nid . g -- | uses the successor and predecessor list of a node as an indicator for whether a -- node has properly joined the DHT -isJoined :: LocalNodeState -> Bool +isJoined :: LocalNodeState s -> Bool isJoined ns = not . all null $ [successors ns, predecessors ns] -- | the size limit to be used when serialising messages for sending @@ -248,7 +248,7 @@ ackRequest _ _ = Map.empty -- | Dispatch incoming requests to the dedicated handling and response function, and enqueue -- the response to be sent. -handleIncomingRequest :: LocalNodeStateSTM -- ^ the handling node +handleIncomingRequest :: LocalNodeStateSTM s -- ^ the handling node -> TQueue (BS.ByteString, SockAddr) -- ^ send queue -> Set.Set FediChordMessage -- ^ all parts of the request to handle -> SockAddr -- ^ source address of the request @@ -287,7 +287,7 @@ handleIncomingRequest nsSTM sendQ msgSet sourceAddr = do -- | execute a key ID lookup on local cache and respond with the result -respondQueryID :: LocalNodeStateSTM -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) +respondQueryID :: LocalNodeStateSTM s -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) respondQueryID nsSTM msgSet = do putStrLn "responding to a QueryID request" -- this message cannot be split reasonably, so just @@ -328,7 +328,7 @@ respondQueryID nsSTM msgSet = do -- | Respond to a Leave request by removing the leaving node from local data structures -- and confirming with response. -- TODO: copy over key data from leaver and confirm -respondLeave :: LocalNodeStateSTM -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) +respondLeave :: LocalNodeStateSTM s -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) respondLeave nsSTM msgSet = do -- combine payload of all parts let (requestPreds, requestSuccs) = foldr' (\msg (predAcc, succAcc) -> @@ -359,7 +359,7 @@ respondLeave nsSTM msgSet = do pure $ serialiseMessage sendMessageSize responseMsg -- | respond to stabilise requests by returning successor and predecessor list -respondStabilise :: LocalNodeStateSTM -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) +respondStabilise :: LocalNodeStateSTM s -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) respondStabilise nsSTM msgSet = do nsSnap <- readTVarIO nsSTM let @@ -381,7 +381,7 @@ respondStabilise nsSTM msgSet = do -- | respond to Ping request by returning all active vserver NodeStates -respondPing :: LocalNodeStateSTM -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) +respondPing :: LocalNodeStateSTM s -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) respondPing nsSTM msgSet = do -- TODO: respond with all active VS when implementing k-choices nsSnap <- readTVarIO nsSTM @@ -400,7 +400,7 @@ respondPing nsSTM msgSet = do -- this modifies node state, so locking and IO seems to be necessary. -- Still try to keep as much code as possible pure -respondJoin :: LocalNodeStateSTM -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) +respondJoin :: LocalNodeStateSTM s -> Set.Set FediChordMessage -> IO (Map.Map Integer BS.ByteString) respondJoin nsSTM msgSet = do -- atomically read and modify the node state according to the parsed request responseMsg <- atomically $ do @@ -451,8 +451,8 @@ respondJoin nsSTM msgSet = do -- | send a join request and return the joined 'LocalNodeState' including neighbours requestJoin :: NodeState a => a -- ^ currently responsible node to be contacted - -> LocalNodeStateSTM -- ^ joining NodeState - -> IO (Either String LocalNodeStateSTM) -- ^ node after join with all its new information + -> LocalNodeStateSTM s -- ^ joining NodeState + -> IO (Either String (LocalNodeStateSTM s)) -- ^ node after join with all its new information requestJoin toJoinOn ownStateSTM = do ownState <- readTVarIO ownStateSTM prn <- readTVarIO $ parentRealNode ownState @@ -500,7 +500,7 @@ requestJoin toJoinOn ownStateSTM = do -- | Send a 'QueryID' 'Request' for getting the node that handles a certain key ID. -requestQueryID :: LocalNodeState -- ^ NodeState of the querying node +requestQueryID :: LocalNodeState s -- ^ NodeState of the querying node -> NodeID -- ^ target key ID to look up -> IO RemoteNodeState -- ^ the node responsible for handling that key -- 1. do a local lookup for the l closest nodes @@ -515,7 +515,7 @@ requestQueryID ns targetID = do queryIdLookupLoop firstCacheSnapshot ns 50 targetID -- | like 'requestQueryID, but allows passing of a custom cache, e.g. for joining -queryIdLookupLoop :: NodeCache -> LocalNodeState -> Int -> NodeID -> IO RemoteNodeState +queryIdLookupLoop :: NodeCache -> LocalNodeState s -> Int -> NodeID -> IO RemoteNodeState -- return node itself as default fallback value against infinite recursion. -- TODO: consider using an Either instead of a default value queryIdLookupLoop _ ns 0 _ = pure $ toRemoteNodeState ns @@ -541,7 +541,7 @@ queryIdLookupLoop cacheSnapshot ns maxAttempts targetID = do sendQueryIdMessages :: (Integral i) => NodeID -- ^ target key ID to look up - -> LocalNodeState -- ^ node state of the node doing the query + -> LocalNodeState s -- ^ node state of the node doing the query -> Maybe i -- ^ optionally provide an explicit @l@ parameter of number of nodes to be returned -> [RemoteNodeState] -- ^ nodes to query -> IO QueryResponse -- ^ accumulated response @@ -579,7 +579,7 @@ sendQueryIdMessages targetID ns lParam targets = do -- | Create a QueryID message to be supplied to 'sendRequestTo' lookupMessage :: Integral i => NodeID -- ^ target ID - -> LocalNodeState -- ^ sender node state + -> LocalNodeState s -- ^ sender node state -> Maybe i -- ^ optionally provide a different l parameter -> (Integer -> FediChordMessage) lookupMessage targetID ns lParam = \rID -> Request rID (toRemoteNodeState ns) 1 True QueryID (Just $ pl ns targetID) @@ -589,7 +589,7 @@ lookupMessage targetID ns lParam = \rID -> Request rID (toRemoteNodeState ns) 1 -- | Send a stabilise request to provided 'RemoteNode' and, if successful, -- return parsed neighbour lists -requestStabilise :: LocalNodeState -- ^ sending node +requestStabilise :: LocalNodeState s -- ^ sending node -> RemoteNodeState -- ^ neighbour node to send to -> IO (Either String ([RemoteNodeState], [RemoteNodeState])) -- ^ (predecessors, successors) of responding node requestStabilise ns neighbour = do @@ -624,7 +624,7 @@ requestStabilise ns neighbour = do ) responses -requestPing :: LocalNodeState -- ^ sending node +requestPing :: LocalNodeState s -- ^ sending node -> RemoteNodeState -- ^ node to be PINGed -> IO (Either String [RemoteNodeState]) -- ^ all active vServers of the pinged node requestPing ns target = do @@ -723,7 +723,7 @@ sendRequestTo timeoutMillis numAttempts msgIncomplete sock = do -- | enqueue a list of RemoteCacheEntries to be added to the global NodeCache queueAddEntries :: Foldable c => c RemoteCacheEntry - -> LocalNodeState + -> LocalNodeState s -> IO () queueAddEntries entries ns = do now <- getPOSIXTime @@ -733,14 +733,14 @@ queueAddEntries entries ns = do -- | enque a list of node IDs to be deleted from the global NodeCache queueDeleteEntries :: Foldable c => c NodeID - -> LocalNodeState + -> LocalNodeState s -> IO () queueDeleteEntries ids ns = forM_ ids $ atomically . writeTQueue (cacheWriteQueue ns) . deleteCacheEntry -- | enque a single node ID to be deleted from the global NodeCache queueDeleteEntry :: NodeID - -> LocalNodeState + -> LocalNodeState s -> IO () queueDeleteEntry toDelete = queueDeleteEntries $ Identity toDelete diff --git a/src/Hash2Pub/FediChord.hs b/src/Hash2Pub/FediChord.hs index 70c9ff7..914ea57 100644 --- a/src/Hash2Pub/FediChord.hs +++ b/src/Hash2Pub/FediChord.hs @@ -78,7 +78,6 @@ import Data.Maybe (catMaybes, fromJust, fromMaybe, isJust, isNothing, mapMaybe) import qualified Data.Set as Set import Data.Time.Clock.POSIX -import Data.Typeable (Typeable (..), typeOf) import Data.Word import qualified Network.ByteOrder as NetworkBytes import Network.Socket hiding (recv, recvFrom, send, @@ -95,10 +94,10 @@ import Debug.Trace (trace) -- | initialise data structures, compute own IDs and bind to listening socket -- ToDo: load persisted state, thus this function already operates in IO -fediChordInit :: (Service s RealNodeSTM) +fediChordInit :: (Service s (RealNodeSTM s)) => FediChordConf - -> (RealNodeSTM -> IO (s RealNodeSTM)) -- ^ runner function for service - -> IO (Socket, LocalNodeStateSTM) + -> (RealNodeSTM s -> IO (s (RealNodeSTM s))) -- ^ runner function for service + -> IO (Socket, LocalNodeStateSTM s) fediChordInit initConf serviceRunner = do emptyLookupCache <- newTVarIO Map.empty let realNode = RealNode { @@ -119,7 +118,7 @@ fediChordInit initConf serviceRunner = do -- | initialises the 'NodeState' for this local node. -- Separated from 'fediChordInit' to be usable in tests. -nodeStateInit :: RealNodeSTM -> IO LocalNodeState +nodeStateInit :: RealNodeSTM s -> IO (LocalNodeState s) nodeStateInit realNodeSTM = do realNode <- readTVarIO realNodeSTM cacheSTM <- newTVarIO initCache @@ -151,9 +150,9 @@ nodeStateInit realNodeSTM = do -- | Join a new node into the DHT, using a provided bootstrap node as initial cache seed -- for resolving the new node's position. -fediChordBootstrapJoin :: LocalNodeStateSTM -- ^ the local 'NodeState' +fediChordBootstrapJoin :: LocalNodeStateSTM s -- ^ the local 'NodeState' -> (String, PortNumber) -- ^ domain and port of a bootstrapping node - -> IO (Either String LocalNodeStateSTM) -- ^ the joined 'NodeState' after a + -> IO (Either String (LocalNodeStateSTM s)) -- ^ the joined 'NodeState' after a -- successful join, otherwise an error message fediChordBootstrapJoin nsSTM bootstrapNode = do -- can be invoked multiple times with all known bootstrapping nodes until successfully joined @@ -169,7 +168,7 @@ fediChordBootstrapJoin nsSTM bootstrapNode = do -- Periodically lookup own ID through a random bootstrapping node to discover and merge separated DHT clusters. -- Unjoined try joining instead. -convergenceSampleThread :: LocalNodeStateSTM -> IO () +convergenceSampleThread :: LocalNodeStateSTM s -> IO () convergenceSampleThread nsSTM = forever $ do nsSnap <- readTVarIO nsSTM parentNode <- readTVarIO $ parentRealNode nsSnap @@ -200,7 +199,7 @@ convergenceSampleThread nsSTM = forever $ do -- | Try joining the DHT through any of the bootstrapping nodes until it succeeds. -tryBootstrapJoining :: LocalNodeStateSTM -> IO (Either String LocalNodeStateSTM) +tryBootstrapJoining :: LocalNodeStateSTM s -> IO (Either String (LocalNodeStateSTM s)) tryBootstrapJoining nsSTM = do bss <- atomically $ do nsSnap <- readTVar nsSTM @@ -217,7 +216,7 @@ tryBootstrapJoining nsSTM = do -- | Look up a key just based on the responses of a single bootstrapping node. -bootstrapQueryId :: LocalNodeStateSTM -> (String, PortNumber) -> NodeID -> IO (Either String RemoteNodeState) +bootstrapQueryId :: LocalNodeStateSTM s -> (String, PortNumber) -> NodeID -> IO (Either String RemoteNodeState) bootstrapQueryId nsSTM (bootstrapHost, bootstrapPort) targetID = do ns <- readTVarIO nsSTM srcAddr <- confIP . nodeConfig <$> readTVarIO (parentRealNode ns) @@ -248,8 +247,8 @@ bootstrapQueryId nsSTM (bootstrapHost, bootstrapPort) targetID = do -- | join a node to the DHT using the global node cache -- node's position. -fediChordJoin :: LocalNodeStateSTM -- ^ the local 'NodeState' - -> IO (Either String LocalNodeStateSTM) -- ^ the joined 'NodeState' after a +fediChordJoin :: LocalNodeStateSTM s -- ^ the local 'NodeState' + -> IO (Either String (LocalNodeStateSTM s)) -- ^ the joined 'NodeState' after a -- successful join, otherwise an error message fediChordJoin nsSTM = do ns <- readTVarIO nsSTM @@ -265,7 +264,7 @@ fediChordJoin nsSTM = do -- | Wait for new cache entries to appear and then try joining on them. -- Exits after successful joining. -joinOnNewEntriesThread :: LocalNodeStateSTM -> IO () +joinOnNewEntriesThread :: LocalNodeStateSTM s -> IO () joinOnNewEntriesThread nsSTM = loop where loop = do @@ -278,8 +277,7 @@ joinOnNewEntriesThread nsSTM = loop result -> pure (result, cache) case lookupResult of -- already joined - FOUND _ -> do - print =<< readTVarIO nsSTM + FOUND _ -> pure () -- otherwise try joining FORWARD _ -> do @@ -295,7 +293,7 @@ joinOnNewEntriesThread nsSTM = loop -- | cache updater thread that waits for incoming NodeCache update instructions on -- the node's cacheWriteQueue and then modifies the NodeCache as the single writer. -nodeCacheWriter :: LocalNodeStateSTM -> IO () +nodeCacheWriter :: LocalNodeStateSTM s -> IO () nodeCacheWriter nsSTM = forever $ atomically $ do ns <- readTVar nsSTM @@ -309,7 +307,7 @@ maxEntryAge = 600 -- | Periodically iterate through cache, clean up expired entries and verify unverified ones -nodeCacheVerifyThread :: LocalNodeStateSTM -> IO () +nodeCacheVerifyThread :: LocalNodeStateSTM s -> IO () nodeCacheVerifyThread nsSTM = forever $ do putStrLn "cache verify run: begin" -- get cache @@ -370,7 +368,7 @@ nodeCacheVerifyThread nsSTM = forever $ do -- | Checks the invariant of at least @jEntries@ per cache slice. -- If this invariant does not hold, the middle of the slice is returned for -- making lookups to that ID -checkCacheSliceInvariants :: LocalNodeState +checkCacheSliceInvariants :: LocalNodeState s -> NodeCache -> [NodeID] -- ^ list of middle IDs of slices not -- ^ fulfilling the invariant @@ -426,12 +424,11 @@ checkCacheSliceInvariants ns -- | Periodically send @StabiliseRequest' s to the closest neighbour nodes, until -- one responds, and get their neighbours for maintaining the own neighbour lists. -- If necessary, request new neighbours. -stabiliseThread :: LocalNodeStateSTM -> IO () +stabiliseThread :: LocalNodeStateSTM s -> IO () stabiliseThread nsSTM = forever $ do ns <- readTVarIO nsSTM putStrLn "stabilise run: begin" - print ns -- iterate through the same snapshot, collect potential new neighbours -- and nodes to be deleted, and modify these changes only at the end of @@ -489,8 +486,8 @@ stabiliseThread nsSTM = forever $ do -- with the n+1-th neighbour. -- On success, return 2 lists: The failed nodes and the potential neighbours -- returned by the queried node. - stabiliseClosestResponder :: LocalNodeState -- ^ own node - -> (LocalNodeState -> [RemoteNodeState]) -- ^ getter function for either predecessors or successors + stabiliseClosestResponder :: LocalNodeState s -- ^ own node + -> (LocalNodeState s -> [RemoteNodeState]) -- ^ getter function for either predecessors or successors -> Int -- ^ index of neighbour to query -> [RemoteNodeState] -- ^ delete accumulator -> IO (Either String ([RemoteNodeState], [RemoteNodeState])) -- ^ (nodes to be deleted, successfully pinged potential neighbours) @@ -514,7 +511,7 @@ stabiliseThread nsSTM = forever $ do currentNeighbour ns neighbourGetter = atMay $ neighbourGetter ns - checkReachability :: LocalNodeState -- ^ this node + checkReachability :: LocalNodeState s -- ^ this node -> RemoteNodeState -- ^ node to Ping for reachability -> IO (Maybe RemoteNodeState) -- ^ if the Pinged node handles the requested node state then that one checkReachability ns toCheck = do @@ -543,10 +540,10 @@ sendThread sock sendQ = forever $ do sendAllTo sock packet addr -- | Sets up and manages the main server threads of FediChord -fediMainThreads :: Socket -> LocalNodeStateSTM -> IO () +fediMainThreads :: Socket -> LocalNodeStateSTM s -> IO () fediMainThreads sock nsSTM = do ns <- readTVarIO nsSTM - putStrLn $ "launching threads, ns: " <> show ns + putStrLn $ "launching threads" sendQ <- newTQueueIO recvQ <- newTQueueIO -- concurrently launch all handler threads, if one of them throws an exception @@ -588,7 +585,7 @@ requestMapPurge mapVar = forever $ do -- and pass them to their specific handling function. fediMessageHandler :: TQueue (BS.ByteString, SockAddr) -- ^ send queue -> TQueue (BS.ByteString, SockAddr) -- ^ receive queue - -> LocalNodeStateSTM -- ^ acting NodeState + -> LocalNodeStateSTM s -- ^ acting NodeState -> IO () fediMessageHandler sendQ recvQ nsSTM = do -- Read node state just once, assuming that all relevant data for this function does @@ -653,14 +650,14 @@ fediMessageHandler sendQ recvQ nsSTM = do -- ==== interface to service layer ==== -instance DHT RealNodeSTM where +instance DHT (RealNodeSTM s) where lookupKey nodeSTM keystring = getKeyResponsibility nodeSTM $ genKeyID keystring forceLookupKey nodeSTM keystring = updateLookupCache nodeSTM $ genKeyID keystring -- | Returns the hostname and port of the host responsible for a key. -- Information is provided from a cache, only on a cache miss a new DHT lookup -- is triggered. -getKeyResponsibility :: RealNodeSTM -> NodeID -> IO (Maybe (String, PortNumber)) +getKeyResponsibility :: RealNodeSTM s -> NodeID -> IO (Maybe (String, PortNumber)) getKeyResponsibility nodeSTM lookupKey = do node <- readTVarIO nodeSTM cache <- readTVarIO $ lookupCacheSTM node @@ -676,7 +673,7 @@ getKeyResponsibility nodeSTM lookupKey = do -- | Triggers a new DHT lookup for a key, updates the lookup cache and returns the -- new entry. -- If no vserver is active in the DHT, 'Nothing' is returned. -updateLookupCache :: RealNodeSTM -> NodeID -> IO (Maybe (String, PortNumber)) +updateLookupCache :: RealNodeSTM s -> NodeID -> IO (Maybe (String, PortNumber)) updateLookupCache nodeSTM lookupKey = do (node, lookupSource) <- atomically $ do node <- readTVar nodeSTM @@ -703,7 +700,7 @@ updateLookupCache nodeSTM lookupKey = do -- | Periodically clean the lookup cache from expired entries. -lookupCacheCleanup :: RealNodeSTM -> IO () +lookupCacheCleanup :: RealNodeSTM s -> IO () lookupCacheCleanup nodeSTM = do node <- readTVarIO nodeSTM forever $ do diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index 604519e..5b8ef17 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -147,9 +147,8 @@ a `localCompare` b -- | Data for managing the virtual server nodes of this real node. -- Also contains shared data and config values. -- TODO: more data structures for k-choices bookkeeping ---data RealNode s = RealNode -data RealNode = RealNode - { vservers :: [LocalNodeStateSTM] +data RealNode s = RealNode + { vservers :: [LocalNodeStateSTM s] -- ^ references to all active versers , nodeConfig :: FediChordConf -- ^ holds the initial configuration read at program start @@ -157,10 +156,10 @@ data RealNode = RealNode -- ^ nodes to be used as bootstrapping points, new ones learned during operation , lookupCacheSTM :: TVar LookupCache -- ^ a global cache of looked up keys and their associated nodes + , nodeService :: s (RealNodeSTM s) } ---type RealNodeSTM s = TVar (RealNode s) -type RealNodeSTM = TVar RealNode +type RealNodeSTM s = TVar (RealNode s) -- | represents a node and all its important state data RemoteNodeState = RemoteNodeState @@ -182,7 +181,7 @@ instance Ord RemoteNodeState where a `compare` b = nid a `compare` nid b -- | represents a node and encapsulates all data and parameters that are not present for remote nodes -data LocalNodeState = LocalNodeState +data LocalNodeState s = LocalNodeState { nodeState :: RemoteNodeState -- ^ represents common data present both in remote and local node representations , nodeCacheSTM :: TVar NodeCache @@ -201,13 +200,13 @@ data LocalNodeState = LocalNodeState -- ^ number of parallel sent queries , jEntriesPerSlice :: Int -- ^ number of desired entries per cache slice - , parentRealNode :: RealNodeSTM + , parentRealNode :: RealNodeSTM s -- ^ the parent node managing this vserver instance } deriving (Show, Eq) -- | for concurrent access, LocalNodeState is wrapped in a TVar -type LocalNodeStateSTM = TVar LocalNodeState +type LocalNodeStateSTM s = TVar (LocalNodeState s) -- | class for various NodeState representations, providing -- getters and setters for common values @@ -244,14 +243,14 @@ instance NodeState RemoteNodeState where toRemoteNodeState = id -- | helper function for setting values on the 'RemoteNodeState' contained in the 'LocalNodeState' -propagateNodeStateSet_ :: (RemoteNodeState -> RemoteNodeState) -> LocalNodeState -> LocalNodeState +propagateNodeStateSet_ :: (RemoteNodeState -> RemoteNodeState) -> LocalNodeState s -> LocalNodeState s propagateNodeStateSet_ func ns = let newNs = func $ nodeState ns in ns {nodeState = newNs} -instance NodeState LocalNodeState where +instance NodeState (LocalNodeState s) where getNid = getNid . nodeState getDomain = getDomain . nodeState getIpAddr = getIpAddr . nodeState @@ -273,21 +272,24 @@ instance Typeable a => Show (TVar a) where instance Typeable a => Show (TQueue a) where show x = show (typeOf x) +instance Typeable a => Show (TChan a) where + show x = show (typeOf x) + -- | convenience function that replaces the predecessors of a 'LocalNodeState' with the k closest nodes from the provided list -setPredecessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState +setPredecessors :: [RemoteNodeState] -> LocalNodeState s -> LocalNodeState s setPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . rMapFromList . fmap keyValuePair . filter ((/=) (getNid ns) . getNid) $ preds} -- | convenience function that replaces the successors of a 'LocalNodeState' with the k closest nodes from the provided list -setSuccessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState +setSuccessors :: [RemoteNodeState] -> LocalNodeState s -> LocalNodeState s setSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . rMapFromList . fmap keyValuePair . filter ((/=) (getNid ns) . getNid) $ succs} -- | sets the predecessors of a 'LocalNodeState' to the closest k nodes of the current predecessors and the provided list, combined -addPredecessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState +addPredecessors :: [RemoteNodeState] -> LocalNodeState s -> LocalNodeState s addPredecessors preds ns = ns {predecessors = takeRMapPredecessors (getNid ns) (kNeighbours ns) . addRMapEntries (keyValuePair <$> filter ((/=) (getNid ns) . getNid) preds) . rMapFromList . fmap keyValuePair $ predecessors ns} -- | sets the successors of a 'LocalNodeState' to the closest k nodes of the current successors and the provided list, combined -addSuccessors :: [RemoteNodeState] -> LocalNodeState -> LocalNodeState +addSuccessors :: [RemoteNodeState] -> LocalNodeState s -> LocalNodeState s addSuccessors succs ns = ns {successors = takeRMapSuccessors (getNid ns) (kNeighbours ns) . addRMapEntries (keyValuePair <$> filter ((/=) (getNid ns) . getNid) succs) . rMapFromList . fmap keyValuePair $ successors ns} instance HasKeyID NodeID RemoteNodeState where diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 264bccb..d5dd30d 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -25,6 +25,7 @@ import qualified Data.Text.Lazy as Txt import Data.Text.Normalize (NormalizationMode (NFC), normalize) import Data.Time.Clock.POSIX +import Data.Typeable (Typeable) import System.Random import qualified Network.Wai.Handler.Warp as Warp @@ -48,6 +49,7 @@ data PostService d = PostService , relayInQueue :: TQueue (Hashtag, PostID, PostContent) -- ^ Queue for processing incoming posts of own instance asynchronously } + deriving (Typeable) type Hashtag = Txt.Text type PostID = Txt.Text diff --git a/test/FediChordSpec.hs b/test/FediChordSpec.hs index 1cace7a..bcc2eaf 100644 --- a/test/FediChordSpec.hs +++ b/test/FediChordSpec.hs @@ -292,7 +292,7 @@ exampleNodeState = RemoteNodeState { , vServerID = 0 } -exampleLocalNode :: IO LocalNodeState +exampleLocalNode :: IO (LocalNodeState s) exampleLocalNode = nodeStateInit =<< (newTVarIO $ RealNode { vservers = [] , nodeConfig = exampleFediConf From e3c7faa80bbecbfda11901e45e9d673b62122eb0 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Fri, 31 Jul 2020 16:54:19 +0200 Subject: [PATCH 15/35] properly initialise RealNode with service and vserver data, set up reference --- src/Hash2Pub/FediChord.hs | 13 ++++++++----- src/Hash2Pub/FediChordTypes.hs | 2 +- src/Hash2Pub/PostService.hs | 2 +- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/Hash2Pub/FediChord.hs b/src/Hash2Pub/FediChord.hs index 914ea57..858b38e 100644 --- a/src/Hash2Pub/FediChord.hs +++ b/src/Hash2Pub/FediChord.hs @@ -105,20 +105,23 @@ fediChordInit initConf serviceRunner = do , nodeConfig = initConf , bootstrapNodes = confBootstrapNodes initConf , lookupCacheSTM = emptyLookupCache - --, service = undefined + , nodeService = undefined } realNodeSTM <- newTVarIO realNode -- launch service and set the reference in the RealNode serv <- serviceRunner realNodeSTM - --atomically . writeTVar $ realNode { service = serv } + atomically . modifyTVar' realNodeSTM $ \rn -> rn { nodeService = serv } + -- initialise a single vserver initialState <- nodeStateInit realNodeSTM initialStateSTM <- newTVarIO initialState + -- add vserver to list at RealNode + atomically . modifyTVar' realNodeSTM $ \rn -> rn { vservers = initialStateSTM:vservers rn } serverSock <- mkServerSocket (getIpAddr initialState) (getDhtPort initialState) pure (serverSock, initialStateSTM) -- | initialises the 'NodeState' for this local node. -- Separated from 'fediChordInit' to be usable in tests. -nodeStateInit :: RealNodeSTM s -> IO (LocalNodeState s) +nodeStateInit :: Service s (RealNodeSTM s) => RealNodeSTM s -> IO (LocalNodeState s) nodeStateInit realNodeSTM = do realNode <- readTVarIO realNodeSTM cacheSTM <- newTVarIO initCache @@ -131,7 +134,7 @@ nodeStateInit realNodeSTM = do , ipAddr = confIP conf , nid = genNodeID (confIP conf) (confDomain conf) $ fromInteger vsID , dhtPort = toEnum $ confDhtPort conf - , servicePort = 0 + , servicePort = getListeningPortFromService $ nodeService realNode , vServerID = vsID } initialState = LocalNodeState { @@ -543,7 +546,7 @@ sendThread sock sendQ = forever $ do fediMainThreads :: Socket -> LocalNodeStateSTM s -> IO () fediMainThreads sock nsSTM = do ns <- readTVarIO nsSTM - putStrLn $ "launching threads" + putStrLn "launching threads" sendQ <- newTQueueIO recvQ <- newTQueueIO -- concurrently launch all handler threads, if one of them throws an exception diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index 5b8ef17..e73e7f5 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -423,7 +423,7 @@ data FediChordConf = FediChordConf class Service s d where -- | run the service runService :: ServiceConf -> d -> IO (s d) - getServicePort' :: (Integral i) => s d -> i + getListeningPortFromService :: (Integral i) => s d -> i instance Hashable.Hashable NodeID where hashWithSalt salt = Hashable.hashWithSalt salt . getNodeID diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index d5dd30d..ae122e2 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -97,7 +97,7 @@ instance DHT d => Service PostService d where atomically $ writeTVar threadVar servThreadID pure thisService - getServicePort' = fromIntegral . confServicePort . serviceConf + getListeningPortFromService = fromIntegral . confServicePort . serviceConf -- | return a WAI application From 50044673a65d0ba0afcc4abc104fa19a70b67757 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Fri, 31 Jul 2020 17:46:33 +0200 Subject: [PATCH 16/35] server endpoint for tag-post delivery --- src/Hash2Pub/PostService.hs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index ae122e2..cab4350 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -19,7 +19,7 @@ import Control.Monad.IO.Class (liftIO) import qualified Data.ByteString.Lazy.UTF8 as BSU import qualified Data.HashMap.Strict as HMap import qualified Data.HashSet as HSet -import Data.Maybe (fromMaybe) +import Data.Maybe (fromMaybe, isJust) import Data.String (fromString) import qualified Data.Text.Lazy as Txt import Data.Text.Normalize (NormalizationMode (NFC), @@ -48,6 +48,7 @@ data PostService d = PostService -- ^ just store the existence of posts for saving memory, , relayInQueue :: TQueue (Hashtag, PostID, PostContent) -- ^ Queue for processing incoming posts of own instance asynchronously + , postFetchQueue :: TQueue PostID } deriving (Typeable) @@ -73,6 +74,7 @@ instance DHT d => Service PostService d where ownSubsVar <- newTVarIO HMap.empty ownPostVar <- newTVarIO HSet.empty relayInQueue' <- newTQueueIO + postFetchQueue' <- newTQueueIO let thisService = PostService { serviceConf = conf @@ -82,6 +84,7 @@ instance DHT d => Service PostService d where , ownSubscriptions = ownSubsVar , ownPosts = ownPostVar , relayInQueue = relayInQueue' + , postFetchQueue = postFetchQueue' } port' = fromIntegral (confServicePort conf) warpSettings = Warp.setPort port' . Warp.setHost (fromString . confServiceHost $ conf) $ Warp.defaultSettings @@ -221,7 +224,15 @@ postInbox serv post = do tagDelivery :: PostService d -> Txt.Text -> Txt.Text -> Handler Txt.Text -tagDelivery serv hashtag posts = pure $ "Here be #" <> hashtag <> " dragons with " <> posts +tagDelivery serv hashtag posts = do + let postIDs = Txt.lines posts + subscriptions <- liftIO . readTVarIO . ownSubscriptions $ serv + if isJust (HMap.lookup (genKeyID . Txt.unpack $ hashtag) subscriptions) + then -- TODO: increase a counter/ statistics for received posts of this tag + liftIO $ forM_ postIDs $ atomically . writeTQueue (postFetchQueue serv) + else -- silently drop posts from unsubscribed tags + pure () + pure $ "Received a postID for tag " <> hashtag tagSubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Integer tagSubscribe serv hashtag origin = pure 42 @@ -251,7 +262,7 @@ enqueueSubscription tagMapSTM tag subscriber posts leaseTime = do setupSubscriberChannel :: TVar RelayTags -> Hashtag -> (String, Int) -> POSIXTime -> STM (TChan PostID) setupSubscriberChannel tagMapSTM tag subscriber leaseTime = do tagMap <- readTVar tagMapSTM - case lookupRelayTags tag tagMap of + case lookupTagSubscriptions tag tagMap of Nothing -> do -- if no collision/ tag doesn't exist yet, just initialize a -- new subscriber map @@ -277,7 +288,7 @@ setupSubscriberChannel tagMapSTM tag subscriber leaseTime = do getTagBroadcastChannel :: PostService d -> Hashtag -> STM (Maybe (TChan PostID)) getTagBroadcastChannel serv tag = do tagMap <- readTVar $ subscribers serv - case lookupRelayTags tag tagMap of + case lookupTagSubscriptions tag tagMap of Nothing -> pure Nothing Just (subscriberSTM, broadcastChan, _) -> do subscriberMap <- readTVar subscriberSTM @@ -287,8 +298,8 @@ getTagBroadcastChannel serv tag = do -- | look up the subscription data of a tag -lookupRelayTags :: Hashtag -> RelayTags -> Maybe (TagSubscribersSTM, TChan PostID, Hashtag) -lookupRelayTags tag = rMapLookup (genKeyID . Txt.unpack $ tag) +lookupTagSubscriptions :: Hashtag -> RingMap NodeID a -> Maybe a +lookupTagSubscriptions tag = rMapLookup (genKeyID . Txt.unpack $ tag) -- normalise the unicode representation of a string to NFC From 7d7fa3b52a745d57cefc4fb7f24aac798e39bce4 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Fri, 31 Jul 2020 17:49:52 +0200 Subject: [PATCH 17/35] fix haddock parsing --- src/Hash2Pub/PostService.hs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index cab4350..dc2164a 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -120,23 +120,23 @@ placeholderPost = Txt.take 5120 . Txt.repeat $ 'O' -- size 5KiB -- ========= HTTP API and handlers ============= type PostServiceAPI = "relay" :> "inbox" :> Capture "hashtag" Txt.Text :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent - -- ^ delivery endpoint of newly published posts of the relay's instance + -- delivery endpoint of newly published posts of the relay's instance :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> PostNoContent '[PlainText] NoContent - -- ^ endpoint for delivering the subscriptions and outstanding queue + -- endpoint for delivering the subscriptions and outstanding queue :<|> "post" :> Capture "postid" Txt.Text :> Get '[PlainText] Txt.Text - -- ^ fetch endpoint for posts, full post ID is http://$domain/post/$postid + -- fetch endpoint for posts, full post ID is http://$domain/post/$postid :<|> "posts" :> ReqBody '[PlainText] Txt.Text :> Post '[PlainText] Txt.Text - -- ^ endpoint for fetching multiple posts at once + -- endpoint for fetching multiple posts at once :<|> "posts" :> "inbox" :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent - -- ^ delivery endpoint of newly published posts of the relay's instance + -- delivery endpoint of newly published posts of the relay's instance :<|> "tags" :> Capture "hashtag" Txt.Text :> ReqBody '[PlainText] Txt.Text :> PostCreated '[PlainText] Txt.Text - -- ^ delivery endpoint for posts of $tag at subscribing instance + -- delivery endpoint for posts of $tag at subscribing instance :<|> "tags" :> Capture "hashtag" Txt.Text :> "subscribe" :> Header "Origin" Txt.Text :> Get '[PlainText] Integer - -- ^ endpoint for subscribing the instance specified in + -- endpoint for subscribing the instance specified in -- the Origin header to $hashtag. -- Returns subscription lease time in seconds. :<|> "tags" :> Capture "hashtag" Txt.Text :> "unsubscribe" :> Header "Origin" Txt.Text :> Get '[PlainText] Txt.Text - -- ^ endpoint for unsubscribing the instance specified in + -- endpoint for unsubscribing the instance specified in -- the Origin header to $hashtag From 7280f251b5015fed7e76e1c01dcf19145f77cf83 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Sat, 1 Aug 2020 11:00:29 +0200 Subject: [PATCH 18/35] server endpoint for tag subscription --- Hash2Pub.cabal | 2 +- app/Main.hs | 2 +- src/Hash2Pub/FediChordTypes.hs | 2 +- src/Hash2Pub/PostService.hs | 19 ++++++++++++++++--- 4 files changed, 19 insertions(+), 6 deletions(-) diff --git a/Hash2Pub.cabal b/Hash2Pub.cabal index 54cb29d..251c60d 100644 --- a/Hash2Pub.cabal +++ b/Hash2Pub.cabal @@ -46,7 +46,7 @@ category: Network extra-source-files: CHANGELOG.md common deps - build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable, unicode-transforms + build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable, unicode-transforms, http-client ghc-options: -Wall diff --git a/app/Main.hs b/app/Main.hs index 98961c0..3bdb4d4 100644 --- a/app/Main.hs +++ b/app/Main.hs @@ -57,7 +57,7 @@ readConfig = do , confMaxLookupCacheAge = 300 } sConf = ServiceConf { - confSubscriptionExpiryTime = 2*3600 `div` read speedup + confSubscriptionExpiryTime = fromIntegral $ 2*3600 `div` (read speedup :: Integer) , confServicePort = read servicePortString , confServiceHost = confDomainString } diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index e73e7f5..91b3822 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -430,7 +430,7 @@ instance Hashable.Hashable NodeID where hash = Hashable.hash . getNodeID data ServiceConf = ServiceConf - { confSubscriptionExpiryTime :: Integer + { confSubscriptionExpiryTime :: POSIXTime -- ^ subscription lease expiration in seconds , confServicePort :: Int -- ^ listening port for service diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index dc2164a..d56eb4c 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -16,7 +16,8 @@ import Control.Concurrent.STM.TQueue import Control.Concurrent.STM.TVar import Control.Monad (foldM, forM_, forever) import Control.Monad.IO.Class (liftIO) -import qualified Data.ByteString.Lazy.UTF8 as BSU +import qualified Data.ByteString.Lazy.UTF8 as BSUL +import qualified Data.ByteString.UTF8 as BSU import qualified Data.HashMap.Strict as HMap import qualified Data.HashSet as HSet import Data.Maybe (fromMaybe, isJust) @@ -26,6 +27,7 @@ import Data.Text.Normalize (NormalizationMode (NFC), normalize) import Data.Time.Clock.POSIX import Data.Typeable (Typeable) +import qualified Network.HTTP.Client as HTTP import System.Random import qualified Network.Wai.Handler.Warp as Warp @@ -235,7 +237,18 @@ tagDelivery serv hashtag posts = do pure $ "Received a postID for tag " <> hashtag tagSubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Integer -tagSubscribe serv hashtag origin = pure 42 +tagSubscribe serv hashtag origin = do + originURL <- maybe + (throwError $ err400 { errBody = "Missing Origin header" }) + pure + origin + req <- HTTP.parseUrlThrow (Txt.unpack originURL) + now <- liftIO getPOSIXTime + let leaseTime = now + confSubscriptionExpiryTime (serviceConf serv) + -- setup subscription entry + _ <- liftIO . atomically $ setupSubscriberChannel (subscribers serv) hashtag (BSU.toString $ HTTP.host req, HTTP.port req) leaseTime + pure $ round leaseTime + tagUnsubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Text tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription from " <> fromMaybe "Nothing" origin <> " to " <> hashtag @@ -310,7 +323,7 @@ normaliseTag = Txt.fromStrict . normalize NFC . Txt.toStrict -- No idea what I'm doing with these overlappable instances though ¯\_(ツ)_/¯ -- TODO: figure out how this overlapping stuff actually works https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/glasgow_exts.html#instance-overlap instance {-# OVERLAPPABLE #-} Show a => MimeRender PlainText a where - mimeRender _ = BSU.fromString . show + mimeRender _ = BSUL.fromString . show -- ====== worker threads ====== From 89706f688a332f2966d8c48a12c9a2e983424310 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Sat, 1 Aug 2020 11:18:16 +0200 Subject: [PATCH 19/35] server endpoint for tag unsubscription --- src/Hash2Pub/PostService.hs | 29 +++++++++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index d56eb4c..838b2c8 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -251,8 +251,14 @@ tagSubscribe serv hashtag origin = do tagUnsubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Text -tagUnsubscribe serv hashtag origin = pure $ "Here be a dragon unsubscription from " <> fromMaybe "Nothing" origin <> " to " <> hashtag - +tagUnsubscribe serv hashtag origin = do + originURL <- maybe + (throwError $ err400 { errBody = "Missing Origin header" }) + pure + origin + req <- HTTP.parseUrlThrow (Txt.unpack originURL) + liftIO . atomically $ deleteSubscription (subscribers serv) hashtag (BSU.toString $ HTTP.host req, HTTP.port req) + pure "bye bye" -- ======= data structure manipulations ========= @@ -297,6 +303,25 @@ setupSubscriberChannel tagMapSTM tag subscriber leaseTime = do Just (tagOutChan, _) -> pure tagOutChan +-- | deletes a subscription from the passed subscriber map +deleteSubscription :: TVar RelayTags -> Hashtag -> (String, Int) -> STM () +deleteSubscription tagMapSTM tag subscriber = do + tagMap <- readTVar tagMapSTM + case lookupTagSubscriptions tag tagMap of + -- no subscribers to that tag, just return + Nothing -> pure () + Just (foundSubMapSTM, _, _) -> do + foundSubMap <- readTVar foundSubMapSTM + let newSubMap = HMap.delete subscriber foundSubMap + -- if there are no subscriptions for the tag anymore, remove its + -- data sttructure altogether + if HMap.null newSubMap + then writeTVar tagMapSTM $ deleteRMapEntry (genKeyID . Txt.unpack $ tag) tagMap + -- otherwise just remove the subscription of that node + else writeTVar foundSubMapSTM newSubMap + + + -- | returns the broadcast channel of a hashtag if there are any subscribers to it getTagBroadcastChannel :: PostService d -> Hashtag -> STM (Maybe (TChan PostID)) getTagBroadcastChannel serv tag = do From 8faa9dc0164162d1f2b5ba558faf36a7defee250 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Sat, 1 Aug 2020 18:58:30 +0200 Subject: [PATCH 20/35] fix test by providing a MockService --- test/FediChordSpec.hs | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/FediChordSpec.hs b/test/FediChordSpec.hs index bcc2eaf..ed1f3c8 100644 --- a/test/FediChordSpec.hs +++ b/test/FediChordSpec.hs @@ -1,4 +1,6 @@ -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE FlexibleInstances #-} +{-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedStrings #-} module FediChordSpec where import Control.Concurrent.STM.TVar @@ -292,12 +294,15 @@ exampleNodeState = RemoteNodeState { , vServerID = 0 } -exampleLocalNode :: IO (LocalNodeState s) -exampleLocalNode = nodeStateInit =<< (newTVarIO $ RealNode { +exampleLocalNode :: IO (LocalNodeState MockService) +exampleLocalNode = do + realNode <- newTVarIO $ RealNode { vservers = [] , nodeConfig = exampleFediConf , bootstrapNodes = confBootstrapNodes exampleFediConf - }) + , nodeService = MockService + } + nodeStateInit realNode exampleFediConf :: FediChordConf @@ -313,3 +318,9 @@ exampleVs :: (Integral i) => i exampleVs = 4 exampleIp :: HostAddress6 exampleIp = tupleToHostAddress6 (0x2001, 0x16b8, 0x755a, 0xb110, 0x7d6a, 0x12ab, 0xf0c5, 0x386e) + +data MockService d = MockService + +instance DHT d => Service MockService d where + runService _ _ = pure MockService + getListeningPortFromService = const 1337 From 20e51ecca43b4453fbea7902c83e00fccf92576e Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Sun, 2 Aug 2020 14:58:53 +0200 Subject: [PATCH 21/35] define API client functions --- src/Hash2Pub/PostService.hs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 838b2c8..76dab47 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -29,9 +29,12 @@ import Data.Time.Clock.POSIX import Data.Typeable (Typeable) import qualified Network.HTTP.Client as HTTP import System.Random +import Text.Read (readEither) import qualified Network.Wai.Handler.Warp as Warp import Servant +import Servant.Client +import Servant.Server import Hash2Pub.FediChordTypes import Hash2Pub.RingMap @@ -260,6 +263,14 @@ tagUnsubscribe serv hashtag origin = do liftIO . atomically $ deleteSubscription (subscribers serv) hashtag (BSU.toString $ HTTP.host req, HTTP.port req) pure "bye bye" +-- client/ request functions + +clientAPI :: Proxy PostServiceAPI +clientAPI = Proxy + + +relayInboxClient :<|> subscriptionDeliveryClient :<|> postFetchClient :<|> postMultiFetchClient :<|> postInboxClient :<|> tagDeliveryClient :<|> tagSubscribeClient :<|> tagUnsubscribeClient = client clientAPI + -- ======= data structure manipulations ========= -- | Write all pending posts of a subscriber-tag-combination to its queue. @@ -350,6 +361,8 @@ normaliseTag = Txt.fromStrict . normalize NFC . Txt.toStrict instance {-# OVERLAPPABLE #-} Show a => MimeRender PlainText a where mimeRender _ = BSUL.fromString . show +instance {-# OVERLAPPABLE #-} Read a => MimeUnrender PlainText a where + mimeUnrender _ = readEither . BSUL.toString -- ====== worker threads ====== From 7036867ae002db82e0ec39341c4dca52676f6960 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Mon, 3 Aug 2020 22:50:48 +0200 Subject: [PATCH 22/35] implemented first Servant client query --- src/Hash2Pub/PostService.hs | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 76dab47..e9144df 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -271,6 +271,18 @@ clientAPI = Proxy relayInboxClient :<|> subscriptionDeliveryClient :<|> postFetchClient :<|> postMultiFetchClient :<|> postInboxClient :<|> tagDeliveryClient :<|> tagSubscribeClient :<|> tagUnsubscribeClient = client clientAPI + + +-- currently this is unused code +getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI +getClients hostname' port' httpMan = hoistClient clientAPI + (fmap (either (error . show) id) + . flip runClientM clientEnv + ) + (client clientAPI) + where + clientEnv = mkClientEnv httpMan (BaseUrl Http hostname' port' "") + -- ======= data structure manipulations ========= -- | Write all pending posts of a subscriber-tag-combination to its queue. @@ -372,11 +384,14 @@ processIncomingPosts :: DHT d => PostService d -> IO () processIncomingPosts serv = forever $ do -- blocks until available -- TODO: process multiple in parallel - (t, pID, pC) <- atomically . readTQueue $ relayInQueue serv - lookupRes <- lookupKey (baseDHT serv) (Txt.unpack t) + (tag, pID, pContent) <- atomically . readTQueue $ relayInQueue serv + lookupRes <- lookupKey (baseDHT serv) (Txt.unpack tag) case lookupRes of -- no vserver active => wait and retry Nothing -> threadDelay $ 10 * 10^6 Just (responsibleHost, responsiblePort) -> do - -- TODO: do actual HTTP requests - pure () + httpMan <- HTTP.newManager HTTP.defaultManagerSettings + resp <- runClientM (relayInboxClient tag (pID <> "," <> pContent)) (mkClientEnv httpMan (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) + case resp of + Left err -> putStrLn $ "Error: " <> show err + Right yay -> putStrLn $ "Yay! " <> show yay From 96c1963a4f350f617820d96afae2d44d7ffdd749 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Tue, 11 Aug 2020 00:07:45 +0200 Subject: [PATCH 23/35] actually check own responsibility for tags before accepting posts --- src/Hash2Pub/DHTProtocol.hs | 1 + src/Hash2Pub/FediChord.hs | 19 +++++++++++ src/Hash2Pub/FediChordTypes.hs | 2 ++ src/Hash2Pub/PostService.hs | 61 +++++++++++++++++++++++++--------- src/Hash2Pub/RingMap.hs | 58 +++++++++++++++++++------------- 5 files changed, 102 insertions(+), 39 deletions(-) diff --git a/src/Hash2Pub/DHTProtocol.hs b/src/Hash2Pub/DHTProtocol.hs index f962d58..a071132 100644 --- a/src/Hash2Pub/DHTProtocol.hs +++ b/src/Hash2Pub/DHTProtocol.hs @@ -34,6 +34,7 @@ module Hash2Pub.DHTProtocol , ackRequest , isPossibleSuccessor , isPossiblePredecessor + , isInOwnResponsibilitySlice , isJoined , closestCachePredecessors ) diff --git a/src/Hash2Pub/FediChord.hs b/src/Hash2Pub/FediChord.hs index 858b38e..7911f3c 100644 --- a/src/Hash2Pub/FediChord.hs +++ b/src/Hash2Pub/FediChord.hs @@ -656,6 +656,25 @@ fediMessageHandler sendQ recvQ nsSTM = do instance DHT (RealNodeSTM s) where lookupKey nodeSTM keystring = getKeyResponsibility nodeSTM $ genKeyID keystring forceLookupKey nodeSTM keystring = updateLookupCache nodeSTM $ genKeyID keystring + -- potential better implementation: put all neighbours of all vservers and the vservers on a ringMap, look the key up and see whether it results in a LocalNodeState + isResponsibleFor nodeSTM key = do + node <- readTVarIO nodeSTM + foldM (\responsible vsSTM -> do + vs <- readTVarIO vsSTM + pure $ responsible || isInOwnResponsibilitySlice key vs + ) + False + $ vservers node + isResponsibleForSTM nodeSTM key = do + node <- readTVar nodeSTM + foldM (\responsible vsSTM -> do + vs <- readTVar vsSTM + pure $ responsible || isInOwnResponsibilitySlice key vs + ) + False + $ vservers node + + -- | Returns the hostname and port of the host responsible for a key. -- Information is provided from a cache, only on a cache miss a new DHT lookup diff --git a/src/Hash2Pub/FediChordTypes.hs b/src/Hash2Pub/FediChordTypes.hs index 91b3822..20d65fe 100644 --- a/src/Hash2Pub/FediChordTypes.hs +++ b/src/Hash2Pub/FediChordTypes.hs @@ -446,3 +446,5 @@ class DHT d where -- but force the DHT to do a fresh lookup instead of returning a cached result. -- Also invalidates old cache entries. forceLookupKey :: d -> String -> IO (Maybe (String, PortNumber)) + isResponsibleFor :: d -> NodeID -> IO Bool + isResponsibleForSTM :: d -> NodeID -> STM Bool diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index e9144df..8f47227 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -12,10 +12,13 @@ import Control.Concurrent import Control.Concurrent.Async import Control.Concurrent.STM import Control.Concurrent.STM.TChan +import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue import Control.Concurrent.STM.TVar -import Control.Monad (foldM, forM_, forever) +import Control.Exception (Exception (..)) +import Control.Monad (foldM, forM, forM_, forever) import Control.Monad.IO.Class (liftIO) +import Control.Monad.STM import qualified Data.ByteString.Lazy.UTF8 as BSUL import qualified Data.ByteString.UTF8 as BSU import qualified Data.HashMap.Strict as HMap @@ -109,7 +112,7 @@ instance DHT d => Service PostService d where -- | return a WAI application -postServiceApplication :: PostService d -> Application +postServiceApplication :: DHT d => PostService d -> Application postServiceApplication serv = serve exposedPostServiceAPI $ postServer serv @@ -126,7 +129,7 @@ placeholderPost = Txt.take 5120 . Txt.repeat $ 'O' -- size 5KiB type PostServiceAPI = "relay" :> "inbox" :> Capture "hashtag" Txt.Text :> ReqBody '[PlainText] Txt.Text :> PutCreated '[PlainText] NoContent -- delivery endpoint of newly published posts of the relay's instance - :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> PostNoContent '[PlainText] NoContent + :<|> "relay" :> "subscribers" :> ReqBody '[PlainText] Txt.Text :> PostNoContent '[PlainText] Txt.Text -- endpoint for delivering the subscriptions and outstanding queue :<|> "post" :> Capture "postid" Txt.Text :> Get '[PlainText] Txt.Text -- fetch endpoint for posts, full post ID is http://$domain/post/$postid @@ -145,7 +148,7 @@ type PostServiceAPI = "relay" :> "inbox" :> Capture "hashtag" Txt.Text :> ReqBod -- the Origin header to $hashtag -postServer :: PostService d -> Server PostServiceAPI +postServer :: DHT d => PostService d -> Server PostServiceAPI postServer service = relayInbox service :<|> subscriptionDelivery service :<|> postFetch service @@ -156,15 +159,21 @@ postServer service = relayInbox service :<|> tagUnsubscribe service -relayInbox :: PostService d -> Hashtag -> Txt.Text -> Handler NoContent +relayInbox :: DHT d => PostService d -> Hashtag -> Txt.Text -> Handler NoContent relayInbox serv tag posts = do let -- skip checking whether the post actually contains the tag, just drop full post postIDs = head . Txt.splitOn "," <$> Txt.lines posts - broadcastChan <- liftIO $ atomically $ getTagBroadcastChannel serv tag -- if tag is not in own responsibility, return a 410 Gone - maybe + responsible <- liftIO $ isResponsibleFor (baseDHT serv) (genKeyID . Txt.unpack $ tag) + if responsible + then pure () + else (throwError $ err410 { errBody = "Relay is not responsible for this tag"}) + broadcastChan <- liftIO $ atomically $ getTagBroadcastChannel serv tag + maybe + -- if noone subscribed to the tag, nothing needs to be done + (pure ()) -- otherwise enqueue posts into broadcast queue of the tag (\queue -> liftIO $ forM_ postIDs (atomically . writeTChan queue) @@ -172,15 +181,35 @@ relayInbox serv tag posts = do broadcastChan pure NoContent -subscriptionDelivery :: PostService d -> Txt.Text -> Handler NoContent +-- exception to be thrown when a tag is not in the responsibility of a relay +newtype UnhandledTagException = UnhandledTagException String + deriving (Show, Typeable) + +instance Exception UnhandledTagException + +subscriptionDelivery :: DHT d => PostService d -> Txt.Text -> Handler Txt.Text subscriptionDelivery serv subList = do let tagSubs = Txt.lines subList - liftIO $ forM_ tagSubs $ processTag (subscribers serv) - pure NoContent + -- In favor of having the convenience of rolling back the transaction once a + -- not-handled tag occurs, this results in a single large transaction. + -- Hopefully the performance isn't too bad. + res <- liftIO . atomically $ (foldM (\_ tag' -> do + responsible <- isResponsibleForSTM (baseDHT serv) (genKeyID . Txt.unpack $ tag') + if responsible + then processTag (subscribers serv) tag' + else throwSTM $ UnhandledTagException (Txt.unpack tag' <> " not handled by this relay") + pure $ Right () + ) (pure ()) tagSubs + `catchSTM` (\e -> pure . Left $ show (e :: UnhandledTagException)) + -- TODO: potentially log this + :: STM (Either String ())) + case res of + Left err -> throwError err410 {errBody = BSUL.fromString err} + Right _ -> pure "" -- TODO: check and only accept tags in own (future?) responsibility where - processTag :: TVar RelayTags -> Txt.Text -> IO () + processTag :: TVar RelayTags -> Txt.Text -> STM () processTag subscriberSTM tagData = do let tag:subText:lease:posts:_ = Txt.splitOn "," tagData @@ -292,11 +321,11 @@ enqueueSubscription :: TVar RelayTags -- tag-subscriber map -> (String, Int) -- subscriber's connection information -> [PostID] -- pending posts -> POSIXTime -- lease expiry time - -> IO () + -> STM () enqueueSubscription tagMapSTM tag subscriber posts leaseTime = do -- get the tag output queue and, if necessary, create it - subChan <- atomically $ setupSubscriberChannel tagMapSTM tag subscriber leaseTime - forM_ posts (atomically . writeTChan subChan) + subChan <- setupSubscriberChannel tagMapSTM tag subscriber leaseTime + forM_ posts (writeTChan subChan) -- | STM operation to return the outgoing post queue of a tag to a specified subscriber. @@ -391,7 +420,7 @@ processIncomingPosts serv = forever $ do Nothing -> threadDelay $ 10 * 10^6 Just (responsibleHost, responsiblePort) -> do httpMan <- HTTP.newManager HTTP.defaultManagerSettings - resp <- runClientM (relayInboxClient tag (pID <> "," <> pContent)) (mkClientEnv httpMan (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) + resp <- runClientM (relayInboxClient tag $ pID <> "," <> pContent) (mkClientEnv httpMan (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) case resp of - Left err -> putStrLn $ "Error: " <> show err + Left err -> putStrLn $ "Error: " <> show err Right yay -> putStrLn $ "Yay! " <> show yay diff --git a/src/Hash2Pub/RingMap.hs b/src/Hash2Pub/RingMap.hs index 016f9f1..9b439e9 100644 --- a/src/Hash2Pub/RingMap.hs +++ b/src/Hash2Pub/RingMap.hs @@ -196,29 +196,28 @@ takeRMapEntries_ :: (Integral i, Bounded k, Ord k) takeRMapEntries_ getterFunc startAt num rmap = reverse $ case getterFunc startAt rmap of Nothing -> [] - Just (foundKey, anEntry) -> takeEntriesUntil rmap getterFunc foundKey foundKey (num-1) [anEntry] - where - -- for some reason, just reusing the already-bound @rmap@ and @getterFunc@ - -- variables leads to a type error, these need to be passed explicitly - takeEntriesUntil :: (Integral i, Bounded k, Ord k) - => RingMap k a - -> (k -> RingMap k a -> Maybe (k, a)) -- getter function - -> k - -> k - -> i - -> [a] - -> [a] - takeEntriesUntil rmap' getterFunc' havingReached previousEntry remaining takeAcc - -- length limit reached - | remaining <= 0 = takeAcc - -- - | otherwise = case nextEntry of - Just (fKey, gotEntry) - | fKey == havingReached -> takeAcc - | otherwise -> takeEntriesUntil rmap' getterFunc' havingReached fKey (remaining - 1) (gotEntry:takeAcc) - Nothing -> takeAcc - where - nextEntry = getterFunc' previousEntry rmap' + Just (foundKey, anEntry) -> takeEntriesUntil_ rmap getterFunc foundKey foundKey (Just $ num-1) [anEntry] + + +takeEntriesUntil_ :: (Integral i, Bounded k, Ord k) + => RingMap k a + -> (k -> RingMap k a -> Maybe (k, a)) -- getter function + -> k -- limit value + -> k -- start value + -> Maybe i -- possible number limit + -> [a] + -> [a] +takeEntriesUntil_ rmap' getterFunc' havingReached previousEntry (Just remaining) takeAcc + -- length limit reached + | remaining <= 0 = takeAcc +takeEntriesUntil_ rmap' getterFunc' havingReached previousEntry numLimit takeAcc = + case nextEntry of + Just (fKey, gotEntry) + | fKey == havingReached -> takeAcc + | otherwise -> takeEntriesUntil_ rmap' getterFunc' havingReached fKey (fmap pred numLimit) (gotEntry:takeAcc) + Nothing -> takeAcc + where + nextEntry = getterFunc' previousEntry rmap' takeRMapPredecessors :: (Integral i, Bounded k, Ord k, Num k) @@ -235,3 +234,16 @@ takeRMapSuccessors :: (Integral i, Bounded k, Ord k, Num k) -> [a] takeRMapSuccessors = takeRMapEntries_ rMapLookupSucc +takeRMapPredecessorsFromTo :: (Bounded k, Ord k, Num k) + => k -- start value for taking + -> k -- stop value for taking + -> RingMap k a + -> [a] +takeRMapPredecessorsFromTo fromVal toVal rmap = takeEntriesUntil_ rmap rMapLookupPred toVal fromVal Nothing [] + +takeRMapSuccesorsFromTo :: (Bounded k, Ord k, Num k) + => k -- start value for taking + -> k -- stop value for taking + -> RingMap k a + -> [a] +takeRMapSuccesorsFromTo fromVal toVal rmap = takeEntriesUntil_ rmap rMapLookupSucc toVal fromVal Nothing [] From 1258f673da285148c23dd66c43aaffa970f1e4cd Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 12 Aug 2020 12:07:41 +0200 Subject: [PATCH 24/35] flush responsibility cache and retry in post queue delivery --- src/Hash2Pub/PostService.hs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 8f47227..ab3f317 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -301,6 +301,20 @@ clientAPI = Proxy relayInboxClient :<|> subscriptionDeliveryClient :<|> postFetchClient :<|> postMultiFetchClient :<|> postInboxClient :<|> tagDeliveryClient :<|> tagSubscribeClient :<|> tagUnsubscribeClient = client clientAPI +---- | Deliver the subscriber list of all hashtags in the interval [fromTag, toTag] +---- and their outstanding delivery queue to another instance. +---- If the transfer succeeds, the transfered subscribers are removed from the local list. +--clientDeliverSubscriptions :: PostService +-- -> Hashtag -- ^ fromTag +-- -> Hashtag -- ^ toTag +-- -> (String, Int) -- ^ hostname and port of instance to deliver to +-- -> IO (Either String ()) -- Either signals success or failure +--clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do +-- -- collect tag intearval +-- intervalTags <- takeRMapSuccesorsFromTo (genKeyID $ Txt.unpack fromTag) (genKeyID $ Txt.unpack fromTag) =<< readTVarIO $ subscribers serv +-- -- extract subscribers and posts +-- -- send subscribers +-- -- on failure return a Left, otherwise flush remaining queues atomically, schedule all newly arrived posts to still be relayed and delete subscription entry -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI @@ -407,7 +421,7 @@ instance {-# OVERLAPPABLE #-} Read a => MimeUnrender PlainText a where -- ====== worker threads ====== --- | process the pending relays of incoming posts from the internal queue: +-- | process the pending relay inbox of incoming posts from the internal queue: -- Look up responsible relay node for given hashtag and forward post to it processIncomingPosts :: DHT d => PostService d -> IO () processIncomingPosts serv = forever $ do @@ -422,5 +436,11 @@ processIncomingPosts serv = forever $ do httpMan <- HTTP.newManager HTTP.defaultManagerSettings resp <- runClientM (relayInboxClient tag $ pID <> "," <> pContent) (mkClientEnv httpMan (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) case resp of - Left err -> putStrLn $ "Error: " <> show err + Left err -> do + putStrLn $ "Error: " <> show err + -- 410 error indicates outdated responsibility mapping + -- Simplification: just invalidate the mapping entry on all errors, force a re-lookup and re-queue the post + -- TODO: keep track of maximum retries + _ <- forceLookupKey (baseDHT serv) (Txt.unpack tag) + atomically . writeTQueue (relayInQueue serv) $ (tag, pID, pContent) Right yay -> putStrLn $ "Yay! " <> show yay From 1d808b6776c048c06fbf3f202db1a591df843578 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 12 Aug 2020 12:16:20 +0200 Subject: [PATCH 25/35] fix typo --- src/Hash2Pub/RingMap.hs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Hash2Pub/RingMap.hs b/src/Hash2Pub/RingMap.hs index 9b439e9..e99f8b2 100644 --- a/src/Hash2Pub/RingMap.hs +++ b/src/Hash2Pub/RingMap.hs @@ -241,9 +241,9 @@ takeRMapPredecessorsFromTo :: (Bounded k, Ord k, Num k) -> [a] takeRMapPredecessorsFromTo fromVal toVal rmap = takeEntriesUntil_ rmap rMapLookupPred toVal fromVal Nothing [] -takeRMapSuccesorsFromTo :: (Bounded k, Ord k, Num k) +takeRMapSuccessorsFromTo :: (Bounded k, Ord k, Num k) => k -- start value for taking -> k -- stop value for taking -> RingMap k a -> [a] -takeRMapSuccesorsFromTo fromVal toVal rmap = takeEntriesUntil_ rmap rMapLookupSucc toVal fromVal Nothing [] +takeRMapSuccessorsFromTo fromVal toVal rmap = takeEntriesUntil_ rmap rMapLookupSucc toVal fromVal Nothing [] From 2e88a4079b0c36888fe924c8aa72592f93926e89 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 12 Aug 2020 14:07:19 +0200 Subject: [PATCH 26/35] extract and build subscriber payload for sending --- src/Hash2Pub/PostService.hs | 55 +++++++++++++++++++++++++++---------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index ab3f317..11562d4 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -301,20 +301,47 @@ clientAPI = Proxy relayInboxClient :<|> subscriptionDeliveryClient :<|> postFetchClient :<|> postMultiFetchClient :<|> postInboxClient :<|> tagDeliveryClient :<|> tagSubscribeClient :<|> tagUnsubscribeClient = client clientAPI ----- | Deliver the subscriber list of all hashtags in the interval [fromTag, toTag] ----- and their outstanding delivery queue to another instance. ----- If the transfer succeeds, the transfered subscribers are removed from the local list. ---clientDeliverSubscriptions :: PostService --- -> Hashtag -- ^ fromTag --- -> Hashtag -- ^ toTag --- -> (String, Int) -- ^ hostname and port of instance to deliver to --- -> IO (Either String ()) -- Either signals success or failure ---clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do --- -- collect tag intearval --- intervalTags <- takeRMapSuccesorsFromTo (genKeyID $ Txt.unpack fromTag) (genKeyID $ Txt.unpack fromTag) =<< readTVarIO $ subscribers serv --- -- extract subscribers and posts --- -- send subscribers --- -- on failure return a Left, otherwise flush remaining queues atomically, schedule all newly arrived posts to still be relayed and delete subscription entry +-- | Deliver the subscriber list of all hashtags in the interval [fromTag, toTag] +-- and their outstanding delivery queue to another instance. +-- If the transfer succeeds, the transfered subscribers are removed from the local list. +clientDeliverSubscriptions :: PostService d + -> Hashtag -- ^ fromTag + -> Hashtag -- ^ toTag + -> (String, Int) -- ^ hostname and port of instance to deliver to + -> IO (Either String ()) -- Either signals success or failure +clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do + -- collect tag intearval + intervalTags <- takeRMapSuccessorsFromTo (genKeyID $ Txt.unpack fromTag) (genKeyID $ Txt.unpack fromTag) <$> readTVarIO (subscribers serv) + -- returns a [ (TagSubscribersSTM, TChan PostID, Hashtag) ] + -- extract subscribers and posts + -- no need for extracting as a single atomic operation, as newly incoming posts are supposed to be rejected because of already having re-positioned on the DHT + subscriberData <- foldM (\response (subSTM, _, tag) -> do + subMap <- readTVarIO subSTM + thisTagsData <- foldM (\tagResponse (subscriber, (subChan, lease)) -> do + -- duplicate the pending queue to work on a copy, in case of a delivery error + pending <- atomically $ do + queueCopy <- cloneTChan subChan + channelGetAll queueCopy + if null pending + then pure tagResponse + else pure $ tag <> "," <> Txt.pack (show subscriber) <> "," <> Txt.pack (show lease) <> "," <> Txt.unwords pending <> "\n" + ) + "" + (HMap.toList subMap) + pure $ thisTagsData <> response + ) + "" + intervalTags + -- send subscribers + -- on failure return a Left, otherwise flush remaining queues atomically, schedule all newly arrived posts to still be relayed and delete subscription entry + pure . Right $ () + where + channelGetAll :: TChan a -> STM [a] + channelGetAll chan = channelGetAll' chan [] + channelGetAll' :: TChan a -> [a] -> STM [a] + channelGetAll' chan acc = do + haveRead <- tryReadTChan chan + maybe (pure acc) (\x -> channelGetAll' chan (x:acc)) haveRead -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI From c1ce386b6599931b9e45268c18674457fd4f6ab0 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Wed, 12 Aug 2020 15:23:10 +0200 Subject: [PATCH 27/35] send prepared subscriptions and clean up on success --- src/Hash2Pub/PostService.hs | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 11562d4..17d585b 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -311,7 +311,7 @@ clientDeliverSubscriptions :: PostService d -> IO (Either String ()) -- Either signals success or failure clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do -- collect tag intearval - intervalTags <- takeRMapSuccessorsFromTo (genKeyID $ Txt.unpack fromTag) (genKeyID $ Txt.unpack fromTag) <$> readTVarIO (subscribers serv) + intervalTags <- takeRMapSuccessorsFromTo (genKeyID $ Txt.unpack fromTag) (genKeyID $ Txt.unpack toTag) <$> readTVarIO (subscribers serv) -- returns a [ (TagSubscribersSTM, TChan PostID, Hashtag) ] -- extract subscribers and posts -- no need for extracting as a single atomic operation, as newly incoming posts are supposed to be rejected because of already having re-positioned on the DHT @@ -333,8 +333,16 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do "" intervalTags -- send subscribers - -- on failure return a Left, otherwise flush remaining queues atomically, schedule all newly arrived posts to still be relayed and delete subscription entry - pure . Right $ () + httpMan <- HTTP.newManager HTTP.defaultManagerSettings + resp <- runClientM (subscriptionDeliveryClient subscriberData) (mkClientEnv httpMan (BaseUrl Http toHost (fromIntegral toPort) "")) + -- on failure return a Left, otherwise delete subscription entry + case resp of + Left err -> pure . Left . show $ err + Right _ -> do + atomically $ + modifyTVar' (subscribers serv) $ \tagMap -> + foldr deleteRMapEntry tagMap ((\(_, _, t) -> genKeyID . Txt.unpack $ t) <$> intervalTags) + pure . Right $ () where channelGetAll :: TChan a -> STM [a] channelGetAll chan = channelGetAll' chan [] From 580410e0b4c78150bedfe51d3e5c27a24d02b550 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 13:07:50 +0200 Subject: [PATCH 28/35] simple post fetch worker thread --- Hash2Pub.cabal | 2 +- src/Hash2Pub/PostService.hs | 32 +++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/Hash2Pub.cabal b/Hash2Pub.cabal index 251c60d..5ffff0d 100644 --- a/Hash2Pub.cabal +++ b/Hash2Pub.cabal @@ -46,7 +46,7 @@ category: Network extra-source-files: CHANGELOG.md common deps - build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable, unicode-transforms, http-client + build-depends: base ^>=4.12.0.0, containers ^>=0.6.0.1, bytestring, utf8-string ^>=1.0.1.1, network ^>=2.8.0.1, time ^>=1.8.0.2, cmdargs ^>= 0.10, cryptonite ^>= 0.25, memory, async, stm, asn1-encoding, asn1-types, asn1-parse, publicsuffix, network-byte-order, safe, iproute, mtl, random, servant, servant-server, servant-client, warp, text, unordered-containers, hashable, unicode-transforms, http-client, http-types ghc-options: -Wall diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 17d585b..47a4059 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -1,4 +1,4 @@ -{-# LANGUAGE DataKinds #-} +{-# laNGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} @@ -15,7 +15,7 @@ import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TChan import Control.Concurrent.STM.TQueue import Control.Concurrent.STM.TVar -import Control.Exception (Exception (..)) +import Control.Exception (Exception (..), try) import Control.Monad (foldM, forM, forM_, forever) import Control.Monad.IO.Class (liftIO) import Control.Monad.STM @@ -31,6 +31,7 @@ import Data.Text.Normalize (NormalizationMode (NFC), import Data.Time.Clock.POSIX import Data.Typeable (Typeable) import qualified Network.HTTP.Client as HTTP +import qualified Network.HTTP.Types as HTTPT import System.Random import Text.Read (readEither) @@ -341,7 +342,7 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do Right _ -> do atomically $ modifyTVar' (subscribers serv) $ \tagMap -> - foldr deleteRMapEntry tagMap ((\(_, _, t) -> genKeyID . Txt.unpack $ t) <$> intervalTags) + foldr deleteRMapEntry tagMap ((\(_, _, t) -> genKeyID . Txt.unpack $ t) <$> intervalTags) pure . Right $ () where channelGetAll :: TChan a -> STM [a] @@ -479,3 +480,28 @@ processIncomingPosts serv = forever $ do _ <- forceLookupKey (baseDHT serv) (Txt.unpack tag) atomically . writeTQueue (relayInQueue serv) $ (tag, pID, pContent) Right yay -> putStrLn $ "Yay! " <> show yay + + +-- | process the pending fetch jobs of delivered post IDs: Delivered posts are tried to be fetched from their URI-ID +fetchTagPosts :: DHT d => PostService d -> IO () +fetchTagPosts serv = forever $ do + -- blocks until available + -- TODO: batching, retry + -- TODO: process multiple in parallel + pIdUri <- atomically . readTQueue $ postFetchQueue serv + httpMan <- HTTP.newManager HTTP.defaultManagerSettings + fetchReq <- HTTP.parseRequest . Txt.unpack $pIdUri + resp <- try $ HTTP.httpLbs fetchReq httpMan :: IO (Either HTTP.HttpException (HTTP.Response BSUL.ByteString)) + case resp of + Right response -> + if HTTPT.statusCode (HTTP.responseStatus response) == 200 + then + -- success, TODO: statistics + putStrLn "post fetch success" + else + -- TODO error handling, retry + pure () + Left _ -> + -- TODO error handling, retry + pure () + From dcd4a7b563a046f6e05cac27f6abc4c2160189b9 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 13:08:38 +0200 Subject: [PATCH 29/35] add nix shell environment without HIE for smaller foot print --- shell-minimal.nix | 1 + 1 file changed, 1 insertion(+) create mode 100644 shell-minimal.nix diff --git a/shell-minimal.nix b/shell-minimal.nix new file mode 100644 index 0000000..15cd4fb --- /dev/null +++ b/shell-minimal.nix @@ -0,0 +1 @@ +(import ./default.nix {withHIE = false;}).shell From 375014812ac41480f347b7e891713f928dc60ad9 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 19:05:28 +0200 Subject: [PATCH 30/35] use a shared HTTP manager for requests --- src/Hash2Pub/PostService.hs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 47a4059..92cd772 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -1,4 +1,4 @@ -{-# laNGUAGE DataKinds #-} +{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} @@ -58,6 +58,7 @@ data PostService d = PostService , relayInQueue :: TQueue (Hashtag, PostID, PostContent) -- ^ Queue for processing incoming posts of own instance asynchronously , postFetchQueue :: TQueue PostID + , httpMan :: HTTP.Manager } deriving (Typeable) @@ -84,6 +85,7 @@ instance DHT d => Service PostService d where ownPostVar <- newTVarIO HSet.empty relayInQueue' <- newTQueueIO postFetchQueue' <- newTQueueIO + httpMan' <- HTTP.newManager HTTP.defaultManagerSettings let thisService = PostService { serviceConf = conf @@ -94,6 +96,7 @@ instance DHT d => Service PostService d where , ownPosts = ownPostVar , relayInQueue = relayInQueue' , postFetchQueue = postFetchQueue' + , httpMan = httpMan' } port' = fromIntegral (confServicePort conf) warpSettings = Warp.setPort port' . Warp.setHost (fromString . confServiceHost $ conf) $ Warp.defaultSettings @@ -334,8 +337,7 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do "" intervalTags -- send subscribers - httpMan <- HTTP.newManager HTTP.defaultManagerSettings - resp <- runClientM (subscriptionDeliveryClient subscriberData) (mkClientEnv httpMan (BaseUrl Http toHost (fromIntegral toPort) "")) + resp <- runClientM (subscriptionDeliveryClient subscriberData) (mkClientEnv (httpMan serv) (BaseUrl Http toHost (fromIntegral toPort) "")) -- on failure return a Left, otherwise delete subscription entry case resp of Left err -> pure . Left . show $ err @@ -469,8 +471,7 @@ processIncomingPosts serv = forever $ do -- no vserver active => wait and retry Nothing -> threadDelay $ 10 * 10^6 Just (responsibleHost, responsiblePort) -> do - httpMan <- HTTP.newManager HTTP.defaultManagerSettings - resp <- runClientM (relayInboxClient tag $ pID <> "," <> pContent) (mkClientEnv httpMan (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) + resp <- runClientM (relayInboxClient tag $ pID <> "," <> pContent) (mkClientEnv (httpMan serv) (BaseUrl Http responsibleHost (fromIntegral responsiblePort) "")) case resp of Left err -> do putStrLn $ "Error: " <> show err @@ -489,9 +490,8 @@ fetchTagPosts serv = forever $ do -- TODO: batching, retry -- TODO: process multiple in parallel pIdUri <- atomically . readTQueue $ postFetchQueue serv - httpMan <- HTTP.newManager HTTP.defaultManagerSettings fetchReq <- HTTP.parseRequest . Txt.unpack $pIdUri - resp <- try $ HTTP.httpLbs fetchReq httpMan :: IO (Either HTTP.HttpException (HTTP.Response BSUL.ByteString)) + resp <- try $ HTTP.httpLbs fetchReq (httpMan serv) :: IO (Either HTTP.HttpException (HTTP.Response BSUL.ByteString)) case resp of Right response -> if HTTPT.statusCode (HTTP.responseStatus response) == 200 From e9ae258ddeec73b424528639c379c18d7c3d3e2c Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 21:12:22 +0200 Subject: [PATCH 31/35] subscribe to tag --- src/Hash2Pub/PostService.hs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 92cd772..15901e0 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -354,6 +354,21 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do haveRead <- tryReadTChan chan maybe (pure acc) (\x -> channelGetAll' chan (x:acc)) haveRead + +-- | Subscribe the client to the given hashtag. On success it returns the given lease time. +clientSubscribeTo :: DHT d => PostService d -> Hashtag -> IO (Either String Integer) +clientSubscribeTo serv tag = do + lookupRes <- lookupKey (baseDHT serv) (Txt.unpack tag) + maybe + (pure . Left $ "No node found") + (\(foundHost, foundPort) -> do + resp <- runClientM (tagSubscribeClient tag (Just . fromString . confServiceHost . serviceConf $ serv)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) + case resp of + Left err -> pure . Left . show $ err + Right lease -> pure . Right $ lease + ) + lookupRes + -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI getClients hostname' port' httpMan = hoistClient clientAPI From e646045ab294ef88e08598e9c2f3ea3427425358 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 21:57:28 +0200 Subject: [PATCH 32/35] include port in Origin header --- src/Hash2Pub/PostService.hs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 15901e0..1de7302 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -359,10 +359,11 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do clientSubscribeTo :: DHT d => PostService d -> Hashtag -> IO (Either String Integer) clientSubscribeTo serv tag = do lookupRes <- lookupKey (baseDHT serv) (Txt.unpack tag) + let origin = "http://" <> Txt.pack (confServiceHost $ serviceConf serv) <> ":" <> Txt.pack (show (getListeningPortFromService serv :: Integer)) maybe (pure . Left $ "No node found") (\(foundHost, foundPort) -> do - resp <- runClientM (tagSubscribeClient tag (Just . fromString . confServiceHost . serviceConf $ serv)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) + resp <- runClientM (tagSubscribeClient tag (Just origin)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) case resp of Left err -> pure . Left . show $ err Right lease -> pure . Right $ lease From 402378a78bd94c351c1bab77fd6b8d1bc985ed18 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 23:44:24 +0200 Subject: [PATCH 33/35] signal and handle non-responsibility to subscriptions --- src/Hash2Pub/PostService.hs | 34 +++++++++++++++++++++++----------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 1de7302..26c473b 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -272,8 +272,13 @@ tagDelivery serv hashtag posts = do pure () pure $ "Received a postID for tag " <> hashtag -tagSubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Integer +tagSubscribe :: DHT d => PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Integer tagSubscribe serv hashtag origin = do + responsible <- liftIO $ isResponsibleFor (baseDHT serv) (genKeyID . Txt.unpack $ hashtag) + if not responsible + -- GONE if not responsible + then throwError err410 { errBody = "not responsible for this tag" } + else pure () originURL <- maybe (throwError $ err400 { errBody = "Missing Origin header" }) pure @@ -359,16 +364,23 @@ clientDeliverSubscriptions serv fromTag toTag (toHost, toPort) = do clientSubscribeTo :: DHT d => PostService d -> Hashtag -> IO (Either String Integer) clientSubscribeTo serv tag = do lookupRes <- lookupKey (baseDHT serv) (Txt.unpack tag) - let origin = "http://" <> Txt.pack (confServiceHost $ serviceConf serv) <> ":" <> Txt.pack (show (getListeningPortFromService serv :: Integer)) - maybe - (pure . Left $ "No node found") - (\(foundHost, foundPort) -> do - resp <- runClientM (tagSubscribeClient tag (Just origin)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) - case resp of - Left err -> pure . Left . show $ err - Right lease -> pure . Right $ lease - ) - lookupRes + doSubscribe lookupRes True + where + doSubscribe lookupResponse allowRetry = maybe + (pure . Left $ "No node found") + (\(foundHost, foundPort) -> do + let origin = "http://" <> Txt.pack (confServiceHost $ serviceConf serv) <> ":" <> Txt.pack (show (getListeningPortFromService serv :: Integer)) + resp <- runClientM (tagSubscribeClient tag (Just origin)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) + case resp of + Left (FailureResponse _ fresp) + |(HTTPT.statusCode . responseStatusCode $ fresp) == 410 && allowRetry -> do -- responsibility gone, force new lookup + newRes <- forceLookupKey (baseDHT serv) (Txt.unpack tag) + doSubscribe newRes False + Left err -> pure . Left . show $ err + Right lease -> pure . Right $ lease + ) + lookupResponse + -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI From bf277c5a730f92f669929f2f015aa6b471758b59 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Thu, 13 Aug 2020 23:50:33 +0200 Subject: [PATCH 34/35] unsubsribe from tag --- src/Hash2Pub/PostService.hs | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 26c473b..99a9efb 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -291,8 +291,13 @@ tagSubscribe serv hashtag origin = do pure $ round leaseTime -tagUnsubscribe :: PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Text +tagUnsubscribe :: DHT d => PostService d -> Txt.Text -> Maybe Txt.Text -> Handler Txt.Text tagUnsubscribe serv hashtag origin = do + responsible <- liftIO $ isResponsibleFor (baseDHT serv) (genKeyID . Txt.unpack $ hashtag) + if not responsible + -- GONE if not responsible + then throwError err410 { errBody = "not responsible for this tag" } + else pure () originURL <- maybe (throwError $ err400 { errBody = "Missing Origin header" }) pure @@ -382,6 +387,28 @@ clientSubscribeTo serv tag = do lookupResponse +-- | Unsubscribe the client from the given hashtag. +clientUnsubscribeFrom :: DHT d => PostService d -> Hashtag -> IO (Either String ()) +clientUnsubscribeFrom serv tag = do + lookupRes <- lookupKey (baseDHT serv) (Txt.unpack tag) + doUnsubscribe lookupRes True + where + doUnsubscribe lookupResponse allowRetry = maybe + (pure . Left $ "No node found") + (\(foundHost, foundPort) -> do + let origin = "http://" <> Txt.pack (confServiceHost $ serviceConf serv) <> ":" <> Txt.pack (show (getListeningPortFromService serv :: Integer)) + resp <- runClientM (tagUnsubscribeClient tag (Just origin)) (mkClientEnv (httpMan serv) (BaseUrl Http foundHost (fromIntegral foundPort) "")) + case resp of + Left (FailureResponse _ fresp) + |(HTTPT.statusCode . responseStatusCode $ fresp) == 410 && allowRetry -> do -- responsibility gone, force new lookup + newRes <- forceLookupKey (baseDHT serv) (Txt.unpack tag) + doUnsubscribe newRes False + Left err -> pure . Left . show $ err + Right _ -> pure . Right $ () + ) + lookupResponse + + -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI getClients hostname' port' httpMan = hoistClient clientAPI From 4339cace201193d11842b95a502ccc6c7bef4742 Mon Sep 17 00:00:00 2001 From: Trolli Schmittlauch Date: Fri, 14 Aug 2020 11:06:58 +0200 Subject: [PATCH 35/35] function for initially publishing a post --- src/Hash2Pub/PostService.hs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Hash2Pub/PostService.hs b/src/Hash2Pub/PostService.hs index 99a9efb..797a9e6 100644 --- a/src/Hash2Pub/PostService.hs +++ b/src/Hash2Pub/PostService.hs @@ -19,6 +19,7 @@ import Control.Exception (Exception (..), try) import Control.Monad (foldM, forM, forM_, forever) import Control.Monad.IO.Class (liftIO) import Control.Monad.STM +import Data.Bifunctor import qualified Data.ByteString.Lazy.UTF8 as BSUL import qualified Data.ByteString.UTF8 as BSU import qualified Data.HashMap.Strict as HMap @@ -409,6 +410,20 @@ clientUnsubscribeFrom serv tag = do lookupResponse +-- | publish a new post to the inbox of a specified relay instance. This +-- instance will then be the originating instance of the post and will forward +-- the post to the responsible relays. +-- As the initial publishing isn't done by a specific relay (but *to* a specific relay +-- instead), the function does *not* take a PostService as argument. +clientPublishPost :: HTTP.Manager -- for better performance, a shared HTTP manager has to be provided + -> String -- hostname + -> Int -- port + -> PostContent -- post content + -> IO (Either String ()) -- error or success +clientPublishPost httpman hostname port postC = do + resp <- runClientM (postInboxClient postC) (mkClientEnv httpman (BaseUrl Http hostname port "")) + pure . bimap show (const ()) $ resp + -- currently this is unused code getClients :: String -> Int -> HTTP.Manager -> Client IO PostServiceAPI getClients hostname' port' httpMan = hoistClient clientAPI