-- SPDX-FileCopyrightText: 2026 Alexandra de Wit
--
-- SPDX-License-Identifier: MIT

{- | The front door's request timeout and its control-plane health probes, @\/livez@ and @\/readyz@.
The request-body cap is a route concern, enforced where the only body-consuming route (publish)
reads its body.
-}
module Ecluse.Runtime.Server.Middleware (
    -- * The request timeout
    requestTimeout,

    -- * Control-plane health probes
    probeApplication,

    -- * Neutral response shapes
    jsonResponse,
) where

import Data.Aeson (Value, encode, object, (.=))
import Data.Aeson.Key qualified as Key
import Data.Map.Strict qualified as Map
import Network.HTTP.Types (Status, hContentType, status200, status404, status503)
import Network.Wai (Application, Middleware, Response, pathInfo, responseLBS)

import Ecluse.Core.Deadline (Deadlines, timeout)
import Ecluse.Core.Ecosystem (Ecosystem, ecosystemName)
import Ecluse.Core.Server.Readiness (
    MountReadiness (MountAwaitingFirstSync, MountReady),
    Readiness (AwaitingMounts, Latched, Routable),
    routable,
 )
import Ecluse.Core.Worker (Liveness (liveHealthy, liveLastPoll))

{- | Answer an empty @503@ for a request that outlives this many seconds, about one sweep late. Like
wai-extra's @timeout@, it answers even when a response has already begun.
-}
requestTimeout :: Deadlines -> Int -> Middleware
requestTimeout :: Deadlines -> Int -> Middleware
requestTimeout Deadlines
deadlines Int
seconds Application
app Request
request Response -> IO ResponseReceived
respond =
    Deadlines
-> Int -> IO ResponseReceived -> IO (Maybe ResponseReceived)
forall a. Deadlines -> Int -> IO a -> IO (Maybe a)
timeout Deadlines
deadlines (Int
seconds Int -> Int -> Int
forall a. Num a => a -> a -> a
* Int
1_000_000) (Application
app Request
request Response -> IO ResponseReceived
respond) IO (Maybe ResponseReceived)
-> (Maybe ResponseReceived -> IO ResponseReceived)
-> IO ResponseReceived
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO ResponseReceived
-> (ResponseReceived -> IO ResponseReceived)
-> Maybe ResponseReceived
-> IO ResponseReceived
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Response -> IO ResponseReceived
respond (Status -> ResponseHeaders -> ByteString -> Response
responseLBS Status
status503 [] ByteString
"")) ResponseReceived -> IO ResponseReceived
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure

{- | The control-plane health probes, answered above any mount: @\/livez@ and @\/readyz@ from the
injected checks. Any other path is a @404@.
-}
probeApplication :: IO Readiness -> IO Liveness -> Application
probeApplication :: IO Readiness -> IO Liveness -> Application
probeApplication IO Readiness
checkReady IO Liveness
checkLiveness Request
request Response -> IO ResponseReceived
respond =
    case Request -> [Text]
pathInfo Request
request of
        [Text
"livez"] -> IO Liveness
checkLiveness IO Liveness
-> (Liveness -> IO ResponseReceived) -> IO ResponseReceived
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Response -> IO ResponseReceived
respond (Response -> IO ResponseReceived)
-> (Liveness -> Response) -> Liveness -> IO ResponseReceived
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Liveness -> Response
livenessResponse
        [Text
"readyz"] -> IO Readiness
checkReady IO Readiness
-> (Readiness -> IO ResponseReceived) -> IO ResponseReceived
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Response -> IO ResponseReceived
respond (Response -> IO ResponseReceived)
-> (Readiness -> Response) -> Readiness -> IO ResponseReceived
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Readiness -> Response
readinessResponse
        [Text]
_ -> Response -> IO ResponseReceived
respond Response
notFound

{- The @\/livez@ body carries the loop's last recorded progress beside the verdict, so a
dedicated worker fleet's orchestrator can judge staleness rather than only pass or fail. -}
livenessResponse :: Liveness -> Response
livenessResponse :: Liveness -> Response
livenessResponse Liveness
liveness
    | Liveness -> Bool
liveHealthy Liveness
liveness = Status -> Text -> Response
body Status
status200 Text
"live"
    | Bool
otherwise = Status -> Text -> Response
body Status
status503 Text
"liveness check failed"
  where
    body :: Status -> Text -> Response
    body :: Status -> Text -> Response
body Status
status Text
label =
        Status -> ByteString -> Response
jsonResponse Status
status (Value -> ByteString
forall a. ToJSON a => a -> ByteString
encode ([Pair] -> Value
object [Key
"status" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
label, Key
"lastPoll" Key -> Maybe UTCTime -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Liveness -> Maybe UTCTime
liveLastPoll Liveness
liveness]))

{- The body names every configured mount beside the verdict, so an operator sees which ecosystem
awaits its advisory database while the others keep serving. -}
readinessResponse :: Readiness -> Response
readinessResponse :: Readiness -> Response
readinessResponse Readiness
verdict = case Readiness
verdict of
    Routable Map Ecosystem MountReadiness
mounts -> Text -> Map Ecosystem MountReadiness -> Response
forall {v}.
ToJSON v =>
v -> Map Ecosystem MountReadiness -> Response
withMounts Text
readyLabel Map Ecosystem MountReadiness
mounts
    AwaitingMounts Map Ecosystem MountReadiness
mounts -> Text -> Map Ecosystem MountReadiness -> Response
forall {v}.
ToJSON v =>
v -> Map Ecosystem MountReadiness -> Response
withMounts Text
awaitingLabel Map Ecosystem MountReadiness
mounts
    Readiness
Latched -> Status -> Text -> Response
statusOnly Status
status Text
"halted"
  where
    -- 'routable' alone decides the status, and the match decides only what the body reports.
    status :: Status
status = Status -> Status -> Bool -> Status
forall a. a -> a -> Bool -> a
bool Status
status503 Status
status200 (Readiness -> Bool
routable Readiness
verdict)
    withMounts :: v -> Map Ecosystem MountReadiness -> Response
withMounts v
label Map Ecosystem MountReadiness
mounts =
        Status -> ByteString -> Response
jsonResponse Status
status (Value -> ByteString
forall a. ToJSON a => a -> ByteString
encode ([Pair] -> Value
object [Key
"status" Key -> v -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= v
label, Key
"mounts" Key -> Value -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Map Ecosystem MountReadiness -> Value
mountsOf Map Ecosystem MountReadiness
mounts]))

-- A mount reports the two words the whole verdict reports, under its configured ecosystem key.
mountsOf :: Map.Map Ecosystem MountReadiness -> Value
mountsOf :: Map Ecosystem MountReadiness -> Value
mountsOf Map Ecosystem MountReadiness
mounts =
    [Pair] -> Value
object [Text -> Key
Key.fromText (Ecosystem -> Text
ecosystemName Ecosystem
eco) Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= MountReadiness -> Text
mountLabel MountReadiness
mount | (Ecosystem
eco, MountReadiness
mount) <- Map Ecosystem MountReadiness -> [(Ecosystem, MountReadiness)]
forall k a. Map k a -> [(k, a)]
Map.toList Map Ecosystem MountReadiness
mounts]

mountLabel :: MountReadiness -> Text
mountLabel :: MountReadiness -> Text
mountLabel = \case
    MountReadiness
MountReady -> Text
readyLabel
    MountReadiness
MountAwaitingFirstSync -> Text
awaitingLabel

readyLabel, awaitingLabel :: Text
readyLabel :: Text
readyLabel = Text
"ready"
-- Only a mount that denies on the advisory database waits, so the label names what is missing and
-- which role publishes it rather than reporting a generic startup delay.
awaitingLabel :: Text
awaitingLabel = Text
"awaiting the advisory database that ecluse pilot publishes"

-- A probe body carrying the verdict alone, for a state no mount detail explains.
statusOnly :: Status -> Text -> Response
statusOnly :: Status -> Text -> Response
statusOnly Status
status Text
label = Status -> ByteString -> Response
jsonResponse Status
status (Value -> ByteString
forall a. ToJSON a => a -> ByteString
encode ([Pair] -> Value
object [Key
"status" Key -> Text -> Pair
forall v. ToJSON v => Key -> v -> Pair
forall e kv v. (KeyValue e kv, ToJSON v) => Key -> v -> kv
.= Text
label]))

-- This tier sits above the mounts, so no ecosystem shapes the body of an unmounted path.
notFound :: Response
notFound :: Response
notFound =
    Status -> ResponseHeaders -> ByteString -> Response
responseLBS Status
status404 [(HeaderName
hContentType, ByteString
"text/plain; charset=utf-8")] ByteString
"Not Found\n"

-- | A JSON response with the given status and body, tagged @application\/json@.
jsonResponse :: Status -> LByteString -> Response
jsonResponse :: Status -> ByteString -> Response
jsonResponse Status
status =
    Status -> ResponseHeaders -> ByteString -> Response
responseLBS Status
status [(HeaderName
hContentType, ByteString
"application/json")]