refactor: deduplicate host resolution logic and observations
Replaces the "API server listening on unix socket" with simpler "API server listening on " observation. This allows refactoring redundant code. Signed-off-by: Taimoor Zaeem <taimoorzaeem@gmail.com>
This commit is contained in:
committed by
Steve Chavez
parent
ef9ac61d9e
commit
41b6ebea58
+28
-12
@@ -1,21 +1,37 @@
|
||||
module PostgREST.Network
|
||||
( resolveHost
|
||||
( resolveSocketToAddress
|
||||
) where
|
||||
|
||||
import Data.IP (fromHostAddress, fromHostAddress6)
|
||||
import Data.String (IsString (..))
|
||||
import qualified Network.Socket as NS
|
||||
|
||||
import Protolude
|
||||
|
||||
resolveHost :: NS.Socket -> IO (Maybe Text)
|
||||
resolveHost sock = do
|
||||
-- | Resolves the socket to an address depending on the socket type. The Show
|
||||
-- instance of the socket types automatically resolves it to the correct
|
||||
-- address. Example resolution:
|
||||
-- -----------------------------------------------------
|
||||
-- | IPv4 | IPv6 | Unix |
|
||||
-- -----------------------------------------------------
|
||||
-- | 127.0.0.1:80 | [2001:db8::1]:80 | /tmp/pgrst.sock |
|
||||
-- -----------------------------------------------------
|
||||
resolveSocketToAddress :: NS.Socket -> IO Text
|
||||
resolveSocketToAddress sock = do
|
||||
sn <- NS.getSocketName sock
|
||||
case sn of
|
||||
NS.SockAddrInet _ hostAddr -> pure $ Just $ fromString $ show $ fromHostAddress hostAddr
|
||||
-- The IPv6 addresses are wrapped in [] brackets. This is done in accordance
|
||||
-- to RFC 3986 (https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2).
|
||||
-- In short, we did this to have a clear separation between the port and host
|
||||
-- because the components of an IPv6 are separated with the ':' character.
|
||||
NS.SockAddrInet6 _ _ hostAddr6 _ -> pure $ Just $ fromString $ "[" ++ show (fromHostAddress6 hostAddr6) ++ "]"
|
||||
_ -> pure Nothing
|
||||
return $ showSocketAddr sn
|
||||
|
||||
-- |
|
||||
-- >>> let addr_ipv4 = NS.SockAddrInet 80 (NS.tupleToHostAddress (127,0,0,1))
|
||||
-- >>> let addr_ipv6 = NS.SockAddrInet6 80 0 (0,0,0,1) 0
|
||||
-- >>> let addr_unix = NS.SockAddrUnix "/tmp/pgrst.sock"
|
||||
--
|
||||
-- >>> showSocketAddr addr_ipv4
|
||||
-- "127.0.0.1:80"
|
||||
|
||||
-- >>> showSocketAddr addr_ipv6
|
||||
-- "[::1]:80"
|
||||
--
|
||||
-- >>> showSocketAddr addr_unix
|
||||
-- "/tmp/pgrst.sock"
|
||||
showSocketAddr :: NS.SockAddr -> Text
|
||||
showSocketAddr = fromString . show
|
||||
|
||||
Reference in New Issue
Block a user