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

{- | The proxy listener runs beside the role's worker and advisory-sync tasks.
"Ecluse.Service" supplies its mounts and probes.
-}
module Ecluse.Proxy (
    runProxy,
    runServer,
) where

import UnliftIO (concurrently_, race_)
import UnliftIO.Async (mapConcurrently_)

import Ecluse.Boot (applyServerSettings)
import Ecluse.Config (AppConfig (cfgServer))
import Ecluse.Proxy.Internal (warpExceptionHook)
import Ecluse.Runtime.Env (Env, envLogEnv)
import Ecluse.Runtime.Server (
    ServerConfig (scCheckLive, scCheckReady, scOnException),
    mkServerConfig,
 )
import Ecluse.Runtime.Server qualified as Server
import Ecluse.Service (ServiceRuntime (..), runWorker)

-- | Run the listener and cancel its background tasks when the HTTP drain ends.
runProxy :: ServiceRuntime -> IO ()
runProxy :: ServiceRuntime -> IO ()
runProxy ServiceRuntime
runtime =
    -- The background tasks never return, so the race cancels them at shutdown. A dropped job
    -- re-enqueues on the next demand and a cancelled sync resumes on next boot.
    case ServiceRuntime -> Maybe (IO ())
svcMirrorDrain ServiceRuntime
runtime of
        Maybe (IO ())
Nothing -> IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m ()
race_ IO ()
frontDoor ((IO () -> IO ()) -> [IO ()] -> IO ()
forall (m :: * -> *) (f :: * -> *) a b.
(MonadUnliftIO m, Foldable f) =>
(a -> m b) -> f a -> m ()
mapConcurrently_ IO () -> IO ()
forall a. a -> a
id [IO ()]
tasks)
        Just IO ()
drain -> IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m ()
race_ IO ()
frontDoor (IO () -> IO () -> IO ()
forall (m :: * -> *) a b. MonadUnliftIO m => m a -> m b -> m ()
concurrently_ IO ()
drain ((IO () -> IO ()) -> [IO ()] -> IO ()
forall (m :: * -> *) (f :: * -> *) a b.
(MonadUnliftIO m, Foldable f) =>
(a -> m b) -> f a -> m ()
mapConcurrently_ IO () -> IO ()
forall a. a -> a
id [IO ()]
tasks))
  where
    -- The memory sampler always runs, so the list is never empty and the race never ends at once.
    tasks :: [IO ()]
tasks = ServiceRuntime -> IO ()
svcMemorySampler ServiceRuntime
runtime IO () -> [IO ()] -> [IO ()]
forall a. a -> [a] -> [a]
: ServiceRuntime -> [IO ()]
svcSyncTasks ServiceRuntime
runtime
    env :: Env
env = ServiceRuntime -> Env
svcEnv ServiceRuntime
runtime
    serverConfig :: ServerConfig
serverConfig = ServiceRuntime -> ServerConfig
proxyServerConfig ServiceRuntime
runtime
    frontDoor :: IO ()
frontDoor
        -- The worker loop never returns, so the server's graceful return must cancel it,
        -- never wait on it.
        | ServiceRuntime -> Bool
svcRunsWorker ServiceRuntime
runtime =
            IO () -> IO () -> IO ()
forall (m :: * -> *). MonadUnliftIO m => m () -> m () -> m ()
Server.raceServerAgainstLoop (ServerConfig -> Env -> IO ()
runServer ServerConfig
serverConfig Env
env) (WorkerPolicies -> Env -> IO ()
runWorker (ServiceRuntime -> WorkerPolicies
svcWorkerPolicies ServiceRuntime
runtime) Env
env)
        | Bool
otherwise = ServerConfig -> Env -> IO ()
runServer ServerConfig
serverConfig Env
env

proxyServerConfig :: ServiceRuntime -> ServerConfig
proxyServerConfig :: ServiceRuntime -> ServerConfig
proxyServerConfig ServiceRuntime
runtime =
    (ServerSettings -> ServerConfig -> ServerConfig
applyServerSettings (AppConfig -> ServerSettings
cfgServer (ServiceRuntime -> AppConfig
svcAppConfig ServiceRuntime
runtime)) ([MountBinding] -> ServerConfig
mkServerConfig (ServiceRuntime -> [MountBinding]
svcBindings ServiceRuntime
runtime)))
        { scCheckReady = svcCheckReady runtime
        , scCheckLive = svcCheckLive runtime
        , scOnException = warpExceptionHook (envLogEnv (svcEnv runtime))
        }

-- | Run the proxy listener with the mounted adapters and shared process resources.
runServer :: ServerConfig -> Env -> IO ()
runServer :: ServerConfig -> Env -> IO ()
runServer ServerConfig
cfg Env
env = LogEnv
-> Text
-> ServerConfig
-> (ServerConfig -> IO Application)
-> IO ()
Server.runWarp (Env -> LogEnv
envLogEnv Env
env) Text
Server.proxyListener ServerConfig
cfg (ServerConfig -> Env -> IO Application
`Server.tracedApplication` Env
env)