packages feed

http-env-0.0.0.0: src/Network/HTTP/Env/OptParse/Duration.hs

{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}

-- | A human-readable duration such as @30s@ or @1h@, for a setting.
module Network.HTTP.Env.OptParse.Duration
  ( Duration (..),
    DurationParseError (..),
    renderDurationParseError,
    formatDuration,
    parseDuration,
  )
where

import Autodocodec
import Control.Arrow (left)
import qualified Data.Char as Char
import Data.Maybe (fromMaybe, listToMaybe, mapMaybe)
import Data.Ratio (denominator, numerator)
import Data.Scientific (Scientific)
import qualified Data.Text as Text
import Data.Time (NominalDiffTime)
import Network.HTTP.Env.Numeric (intToNominalDiffTime, rationalToNominalDiffTime, scientificToRational)
import Text.Read (readMaybe)

-- | Shown as its 'NominalDiffTime', so a documented default reads as seconds.
newtype Duration = Duration {unDuration :: NominalDiffTime}
  deriving (Eq)
  deriving newtype (Show)

-- | Either a duration with a unit, or a whole number of seconds.
instance HasCodec Duration where
  codec =
    dimapCodec
      (\case Left d -> d; Right d -> d)
      Left
      $ eitherCodec
        (bimapCodec (left renderDurationParseError . parseDuration) formatDuration codec)
        (dimapCodec (Duration . intToNominalDiffTime) (round . unDuration) codec)

-- | In the largest unit that divides the duration exactly, or in seconds.
formatDuration :: Duration -> String
formatDuration (Duration d) =
  let units :: [(Rational, String)]
      units =
        [ (30 * 24 * 60 * 60, "M"),
          (7 * 24 * 60 * 60, "w"),
          (24 * 60 * 60, "d"),
          (60 * 60, "h"),
          (60, "m")
        ]
      seconds :: Rational
      seconds = toRational d
      inUnit :: (Rational, String) -> Maybe String
      inUnit (size, unit) =
        let count = seconds / size
         in if seconds /= 0 && denominator count == 1
              then Just (concat [show @Integer (numerator count), unit])
              else Nothing
   in fromMaybe (show @NominalDiffTime d) (listToMaybe (mapMaybe inUnit units))

-- | Why a duration could not be read.
data DurationParseError
  = DurationParseErrorMustStartWithNumber
  | DurationParseErrorInvalidNumber
  | DurationParseErrorUnknownUnit !String
  deriving (Show, Eq)

-- | For a person.
renderDurationParseError :: DurationParseError -> String
renderDurationParseError = \case
  DurationParseErrorMustStartWithNumber -> "Duration must start with a number"
  DurationParseErrorInvalidNumber -> "Invalid number"
  DurationParseErrorUnknownUnit unit ->
    concat
      [ "Unknown duration unit: ",
        unit,
        ". Valid units: s, m, h, d, w, M, seconds, minutes, hours, days, weeks, months"
      ]

-- | A number followed by a unit, which defaults to seconds.
-- Multiplied as a 'Rational' rather than a 'Double', so that a large count of a
-- large unit lands exactly on a multiple of that unit.
parseDuration :: String -> Either DurationParseError Duration
parseDuration s = do
  (num, unit) <- case span (\c -> Char.isDigit c || c == '.') s of
    ([], _) -> Left DurationParseErrorMustStartWithNumber
    (n, u) -> case readMaybe n :: Maybe Scientific of
      Nothing -> Left DurationParseErrorInvalidNumber
      Just num' -> Right (num', u)
  let stripped = Text.strip (Text.pack unit)
  factor :: Rational <- case stripped of
    -- Single letters are case-sensitive, because M is months and m minutes.
    "" -> Right 1
    "s" -> Right 1
    "m" -> Right 60
    "h" -> Right (60 * 60)
    "d" -> Right (24 * 60 * 60)
    "w" -> Right (7 * 24 * 60 * 60)
    "M" -> Right (30 * 24 * 60 * 60)
    _ -> case Text.toLower stripped of
      "seconds" -> Right 1
      "minutes" -> Right 60
      "hours" -> Right (60 * 60)
      "days" -> Right (24 * 60 * 60)
      "weeks" -> Right (7 * 24 * 60 * 60)
      "months" -> Right (30 * 24 * 60 * 60)
      _ -> Left $ DurationParseErrorUnknownUnit unit
  pure $ Duration $ rationalToNominalDiffTime $ scientificToRational num * factor