-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Endpoint and credential configuration with bounded HTTP schedules.
module Cometa.Provider.Blockfrost.Internal.Config
  ( Network (..),
    ProjectId,
    mkProjectId,
    Config (..),
    defaultConfig,
    validateConfig,
    parseEndpoint,
    baseUrl,
    networkMagic,
    projectIdBytes,
  )
where

-- IMPORTS --------------------------------------------------------------------

import Cometa.Error (Error (..))
import Control.Monad (foldM, void)
import Data.ByteString (ByteString)
import Data.Char (isAlphaNum, isAscii, isDigit, ord)
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import Data.Word (Word32)
import qualified Network.HTTP.Client as Http
import qualified Network.URI as URI

-- TYPES ----------------------------------------------------------------------

-- | Cardano chain identity. A custom endpoint does not change its network magic.
data Network
  = -- | Cardano mainnet, with network magic 764824073.
    Mainnet
  | -- | Pre-production test network, with network magic 1.
    Preprod
  | -- | Preview test network, with network magic 2.
    Preview
  deriving (Network -> Network -> Bool
(Network -> Network -> Bool)
-> (Network -> Network -> Bool) -> Eq Network
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Network -> Network -> Bool
== :: Network -> Network -> Bool
$c/= :: Network -> Network -> Bool
/= :: Network -> Network -> Bool
Eq, Eq Network
Eq Network =>
(Network -> Network -> Ordering)
-> (Network -> Network -> Bool)
-> (Network -> Network -> Bool)
-> (Network -> Network -> Bool)
-> (Network -> Network -> Bool)
-> (Network -> Network -> Network)
-> (Network -> Network -> Network)
-> Ord Network
Network -> Network -> Bool
Network -> Network -> Ordering
Network -> Network -> Network
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Network -> Network -> Ordering
compare :: Network -> Network -> Ordering
$c< :: Network -> Network -> Bool
< :: Network -> Network -> Bool
$c<= :: Network -> Network -> Bool
<= :: Network -> Network -> Bool
$c> :: Network -> Network -> Bool
> :: Network -> Network -> Bool
$c>= :: Network -> Network -> Bool
>= :: Network -> Network -> Bool
$cmax :: Network -> Network -> Network
max :: Network -> Network -> Network
$cmin :: Network -> Network -> Network
min :: Network -> Network -> Network
Ord, Int -> Network -> ShowS
[Network] -> ShowS
Network -> String
(Int -> Network -> ShowS)
-> (Network -> String) -> ([Network] -> ShowS) -> Show Network
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Network -> ShowS
showsPrec :: Int -> Network -> ShowS
$cshow :: Network -> String
show :: Network -> String
$cshowList :: [Network] -> ShowS
showList :: [Network] -> ShowS
Show, Int -> Network
Network -> Int
Network -> [Network]
Network -> Network
Network -> Network -> [Network]
Network -> Network -> Network -> [Network]
(Network -> Network)
-> (Network -> Network)
-> (Int -> Network)
-> (Network -> Int)
-> (Network -> [Network])
-> (Network -> Network -> [Network])
-> (Network -> Network -> [Network])
-> (Network -> Network -> Network -> [Network])
-> Enum Network
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: Network -> Network
succ :: Network -> Network
$cpred :: Network -> Network
pred :: Network -> Network
$ctoEnum :: Int -> Network
toEnum :: Int -> Network
$cfromEnum :: Network -> Int
fromEnum :: Network -> Int
$cenumFrom :: Network -> [Network]
enumFrom :: Network -> [Network]
$cenumFromThen :: Network -> Network -> [Network]
enumFromThen :: Network -> Network -> [Network]
$cenumFromTo :: Network -> Network -> [Network]
enumFromTo :: Network -> Network -> [Network]
$cenumFromThenTo :: Network -> Network -> Network -> [Network]
enumFromThenTo :: Network -> Network -> Network -> [Network]
Enum, Network
Network -> Network -> Bounded Network
forall a. a -> a -> Bounded a
$cminBound :: Network
minBound :: Network
$cmaxBound :: Network
maxBound :: Network
Bounded)

-- | An opaque API credential. No printable instance exposes its contents.
newtype ProjectId = ProjectId ByteString deriving (ProjectId -> ProjectId -> Bool
(ProjectId -> ProjectId -> Bool)
-> (ProjectId -> ProjectId -> Bool) -> Eq ProjectId
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ProjectId -> ProjectId -> Bool
== :: ProjectId -> ProjectId -> Bool
$c/= :: ProjectId -> ProjectId -> Bool
/= :: ProjectId -> ProjectId -> Bool
Eq)

-- | HTTP and confirmation-poll settings. Validate once with @withProvider@.
-- Millisecond durations must be between 1 and 60,000 inclusive.
data Config = Config
  { -- | Chain identity and network magic, independent of the endpoint URL.
    Config -> Network
network :: !Network,
    -- | Absolute HTTP or HTTPS base URL, including any path prefix and query
    -- parameters. User information and fragments are not supported. Operation
    -- query parameters override base parameters with the same name.
    Config -> Text
endpoint :: !Text,
    -- | Optional project credential. 'Nothing' omits the project_id header.
    Config -> Maybe ProjectId
projectId :: !(Maybe ProjectId),
    -- | Whole-request deadline, in milliseconds, from 1 through 60000.
    Config -> Int
responseTimeoutMillis :: !Int,
    -- | Delay between confirmation polls, in milliseconds, from 1 through 60000.
    Config -> Int
pollIntervalMillis :: !Int
  }

-- DEFINITIONS ----------------------------------------------------------------

-- | Import 1 through 128 ASCII letters, digits, hyphens or underscores.
-- Whitespace and header delimiters are rejected without echoing the input.
mkProjectId :: Text -> Either Error ProjectId
mkProjectId :: Text -> Either Error ProjectId
mkProjectId Text
value
  | Text -> Bool
Text.null Text
value Bool -> Bool -> Bool
|| Text -> Int
Text.length Text
value Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
128 Bool -> Bool -> Bool
|| Bool -> Bool
not ((Char -> Bool) -> Text -> Bool
Text.all Char -> Bool
allowed Text
value) =
      Error -> Either Error ProjectId
forall a b. a -> Either a b
Left (Text -> Error
InvalidProviderConfiguration Text
"Project identifier must contain 1 through 128 ASCII letters, digits, hyphens or underscores")
  | Bool
otherwise = ProjectId -> Either Error ProjectId
forall a b. b -> Either a b
Right (ByteString -> ProjectId
ProjectId (Text -> ByteString
Text.encodeUtf8 Text
value))
  where
    allowed :: Char -> Bool
allowed Char
character = Char -> Bool
isAscii Char
character Bool -> Bool -> Bool
&& (Char -> Bool
isAlphaNum Char
character Bool -> Bool -> Bool
|| Char
character Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'-' Bool -> Bool -> Bool
|| Char
character Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'_')

-- | The network's official HTTPS endpoint, a 30-second whole-request timeout,
-- and a one-second confirmation poll period. Supply 'Nothing' when the endpoint
-- does not require a project credential; set 'endpoint' for a custom service.
defaultConfig :: Network -> Maybe ProjectId -> Config
defaultConfig :: Network -> Maybe ProjectId -> Config
defaultConfig Network
selected Maybe ProjectId
credential = Network -> Text -> Maybe ProjectId -> Int -> Int -> Config
Config Network
selected (String -> Text
Text.pack (Network -> String
baseUrl Network
selected)) Maybe ProjectId
credential Int
30000 Int
1000

validateConfig :: Config -> Either Error ()
validateConfig :: Config -> Either Error ()
validateConfig Config
config
  | Int -> Bool
forall {a}. (Ord a, Num a) => a -> Bool
invalid (Config -> Int
responseTimeoutMillis Config
config) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidProviderConfiguration Text
"HTTP timeout must be between 1 and 60000 milliseconds")
  | Int -> Bool
forall {a}. (Ord a, Num a) => a -> Bool
invalid (Config -> Int
pollIntervalMillis Config
config) = Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidProviderConfiguration Text
"Polling interval must be between 1 and 60000 milliseconds")
  | Bool
otherwise = Either Error Request -> Either Error ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (Text -> Either Error Request
parseEndpoint (Config -> Text
endpoint Config
config))
  where
    invalid :: a -> Bool
invalid a
value = a
value a -> a -> Bool
forall a. Ord a => a -> a -> Bool
< a
1 Bool -> Bool -> Bool
|| a
value a -> a -> Bool
forall a. Ord a => a -> a -> Bool
> a
60000

-- | The standard URI parser handles authority, percent escapes and bracketed
-- IPv6. The HTTP client's pure conversion checks its supported schemes and port
-- representation. Neither parser's diagnostic is exposed: URLs can contain query
-- credentials, and userinfo would install implicit Basic authentication.
parseEndpoint :: Text -> Either Error Http.Request
parseEndpoint :: Text -> Either Error Request
parseEndpoint Text
value = case String -> Maybe URI
URI.parseURI (Text -> String
Text.unpack Text
value) of
  Just URI
uri
    | Just URIAuth
authority <- URI -> Maybe URIAuth
URI.uriAuthority URI
uri,
      Bool -> Bool
not (String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (URIAuth -> String
URI.uriRegName URIAuth
authority)),
      String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (URIAuth -> String
URI.uriUserInfo URIAuth
authority),
      String -> Bool
validPort (URIAuth -> String
URI.uriPort URIAuth
authority),
      String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (URI -> String
URI.uriFragment URI
uri) -> case URI -> Maybe Request
forall (m :: * -> *). MonadThrow m => URI -> m Request
Http.requestFromURI URI
uri :: Maybe Http.Request of
        Just Request
request | Request -> Int
Http.port Request
request Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
1 Bool -> Bool -> Bool
&& Request -> Int
Http.port Request
request Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
65535 -> Request -> Either Error Request
forall a b. b -> Either a b
Right Request
request
        Maybe Request
_ -> Either Error Request
forall {b}. Either Error b
invalidEndpoint
  Maybe URI
_ -> Either Error Request
forall {b}. Either Error b
invalidEndpoint
  where
    invalidEndpoint :: Either Error b
invalidEndpoint = Error -> Either Error b
forall a b. a -> Either a b
Left (Text -> Error
InvalidProviderConfiguration Text
"Endpoint must be an absolute HTTP or HTTPS URL with a host and valid port, without user information or a fragment")

-- Validate the URI authority's decimal port before the client's Int conversion:
-- http-client 0.7.19 uses Read Int, which can wrap excessively large values.
-- The accumulator never exceeds 65535, including with arbitrarily many zeros.
validPort :: String -> Bool
validPort :: String -> Bool
validPort String
"" = Bool
True
validPort (Char
':' : String
digits) =
  Bool -> Bool
not (String -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
digits) Bool -> Bool -> Bool
&& case (Int -> Char -> Maybe Int) -> Int -> String -> Maybe Int
forall (t :: * -> *) (m :: * -> *) b a.
(Foldable t, Monad m) =>
(b -> a -> m b) -> b -> t a -> m b
foldM Int -> Char -> Maybe Int
digit Int
0 String
digits of
    Just Int
value -> Int
value Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
1
    Maybe Int
Nothing -> Bool
False
  where
    digit :: Int -> Char -> Maybe Int
    digit :: Int -> Char -> Maybe Int
digit Int
current Char
character
      | Char -> Bool
isDigit Char
character Bool -> Bool -> Bool
&& Int
next Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
65535 = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
next
      | Bool
otherwise = Maybe Int
forall a. Maybe a
Nothing
      where
        next :: Int
next = Int
current Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
10 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Char -> Int
ord Char
character Int -> Int -> Int
forall a. Num a => a -> a -> a
- Char -> Int
ord Char
'0'
validPort String
_ = Bool
False

baseUrl :: Network -> String
baseUrl :: Network -> String
baseUrl Network
selected = case Network
selected of
  Network
Mainnet -> String
"https://cardano-mainnet.blockfrost.io/api/v0"
  Network
Preprod -> String
"https://cardano-preprod.blockfrost.io/api/v0"
  Network
Preview -> String
"https://cardano-preview.blockfrost.io/api/v0"

networkMagic :: Network -> Word32
networkMagic :: Network -> Word32
networkMagic Network
selected = case Network
selected of
  Network
Mainnet -> Word32
764824073
  Network
Preprod -> Word32
1
  Network
Preview -> Word32
2

projectIdBytes :: ProjectId -> ByteString
projectIdBytes :: ProjectId -> ByteString
projectIdBytes (ProjectId ByteString
bytes) = ByteString
bytes