11
11
-- | This module implements functionality of NTP client.
12
12
13
13
module Ntp.Client
14
- ( NtpClientSettings (.. )
14
+ ( NtpConfiguration (.. )
15
+ , NtpClientSettings (.. )
16
+ , ntpClientSettings
15
17
, NtpStatus (.. )
16
18
, withNtpClient
17
19
) where
@@ -24,11 +26,15 @@ import Control.Concurrent.Async (async, cancel, concurrently_, race,
24
26
import Control.Concurrent.STM (TVar , modifyTVar' , retry )
25
27
import Control.Exception (Exception , IOException , catch , handle )
26
28
import Control.Monad (forever )
29
+ import Data.Aeson (FromJSON (.. ), ToJSON (.. ), genericParseJSON ,
30
+ genericToJSON )
31
+ import Data.Aeson.Options (defaultOptions )
27
32
import Data.Binary (decodeOrFail )
28
33
import qualified Data.ByteString.Lazy as LBS
29
34
import qualified Data.List.NonEmpty as NE
30
35
import Data.Semigroup (Last (.. ))
31
- import Data.Time.Units (Microsecond , TimeUnit , toMicroseconds )
36
+ import Data.Time.Units (Microsecond , TimeUnit , fromMicroseconds ,
37
+ toMicroseconds )
32
38
import Data.Typeable (Typeable )
33
39
import Formatting (sformat , shown , (%) )
34
40
import qualified Network.Socket as Socket
@@ -80,6 +86,32 @@ data NtpClient = NtpClient
80
86
-- ^ Ntp client configuration.
81
87
}
82
88
89
+ data NtpConfiguration = NtpConfiguration
90
+ {
91
+ ntpcServers :: [String ]
92
+ -- ^ List of DNS names of ntp servers
93
+ , ntpcResponseTimeout :: ! Integer
94
+ -- ^ how long to await for responses from ntp servers (in microseconds)
95
+ , ntpcPollDelay :: ! Integer
96
+ -- ^ how long to wait between sending requests to the ntp servers (in
97
+ -- microseconds)
98
+ } deriving (Show , Generic )
99
+
100
+ instance FromJSON NtpConfiguration where
101
+ parseJSON = genericParseJSON defaultOptions
102
+
103
+ instance ToJSON NtpConfiguration where
104
+ toJSON = genericToJSON defaultOptions
105
+
106
+ ntpClientSettings :: NtpConfiguration -> NtpClientSettings
107
+ ntpClientSettings NtpConfiguration {.. } = NtpClientSettings
108
+ { ntpServers = ntpcServers
109
+ , ntpResponseTimeout = fromMicroseconds $ ntpcResponseTimeout
110
+ , ntpPollDelay = fromMicroseconds $ ntpcPollDelay
111
+ , ntpSelection = minimum . NE. map abs
112
+ -- ^ Take minmum of received offsets.
113
+ }
114
+
83
115
mkNtpClient :: NtpClientSettings -> TVar NtpStatus -> Sockets -> IO NtpClient
84
116
mkNtpClient ncSettings ncStatus sock = liftIO $ do
85
117
ncSockets <- newTVarIO sock
0 commit comments