diff options
Diffstat (limited to 'src/Network/Kademlia/Persistence.hs')
-rw-r--r-- | src/Network/Kademlia/Persistence.hs | 51 |
1 files changed, 0 insertions, 51 deletions
diff --git a/src/Network/Kademlia/Persistence.hs b/src/Network/Kademlia/Persistence.hs deleted file mode 100644 index d7431671..00000000 --- a/src/Network/Kademlia/Persistence.hs +++ /dev/null | |||
@@ -1,51 +0,0 @@ | |||
1 | {-# LANGUAGE NamedFieldPuns #-} | ||
2 | module Network.Kademlia.Persistence where | ||
3 | |||
4 | import Network.Kademlia.CommonAPI | ||
5 | import Network.Kademlia.Routing as R | ||
6 | |||
7 | import Control.Concurrent.STM | ||
8 | import qualified Data.Aeson as J | ||
9 | ;import Data.Aeson as J (FromJSON) | ||
10 | import qualified Data.ByteString.Lazy as L | ||
11 | import qualified Data.HashMap.Strict as HashMap | ||
12 | import Data.List | ||
13 | import qualified Data.Vector as V | ||
14 | import System.IO.Error | ||
15 | |||
16 | saveNodes :: String -> DHT -> IO () | ||
17 | saveNodes netname DHT{dhtBuckets} = do | ||
18 | bkts <- atomically $ readTVar dhtBuckets | ||
19 | let ns = map fst $ concat $ R.toList bkts | ||
20 | bs = J.encode ns | ||
21 | fname = nodesFileName netname | ||
22 | L.writeFile fname bs | ||
23 | |||
24 | loadNodes :: FromJSON ni => String -> IO [ni] | ||
25 | loadNodes netname = do | ||
26 | let fname = nodesFileName netname | ||
27 | attempt <- tryIOError $ do | ||
28 | J.decode <$> L.readFile fname | ||
29 | >>= maybe (ioError $ userError "Nothing") return | ||
30 | either (const $ fallbackLoad fname) return attempt | ||
31 | |||
32 | nodesFileName :: String -> String | ||
33 | nodesFileName netname = netname ++ "-nodes.json" | ||
34 | |||
35 | fallbackLoad :: FromJSON t => FilePath -> IO [t] | ||
36 | fallbackLoad fname = do | ||
37 | attempt <- tryIOError $ do | ||
38 | J.decode <$> L.readFile fname | ||
39 | >>= maybe (ioError $ userError "Nothing") return | ||
40 | let go r = do | ||
41 | let m = HashMap.lookup "nodes" (r :: J.Object) | ||
42 | ns0 = case m of Just (J.Array v) -> V.toList v | ||
43 | Nothing -> [] | ||
44 | ns1 = zip (map J.fromJSON ns0) ns0 | ||
45 | issuc (J.Error _,_) = False | ||
46 | issuc _ = True | ||
47 | (ss,fs) = partition issuc ns1 | ||
48 | ns = map (\(J.Success n,_) -> n) ss | ||
49 | mapM_ print (map snd fs) >> return ns | ||
50 | either (const $ return []) go attempt | ||
51 | |||