{-# OPTIONS_GHC -fno-cse #-}

module Platform.DevLog
  ( writeSpanToDevLog,
  )
where

import qualified Control.Concurrent.MVar as MVar
import qualified Control.Monad
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy
import qualified Data.Time as Time
import NriPrelude
import qualified Platform.Internal
import qualified System.Environment.Blank as Environment
import qualified System.IO
import qualified System.IO.Unsafe
import qualified System.Posix.Files as Files
import qualified Prelude

-- | Write a tracing span to the development log, where it can be found by
-- `log-explorer` for closer inspection.
writeSpanToDevLog :: Platform.Internal.TracingSpan -> Prelude.IO ()
writeSpanToDevLog :: TracingSpan -> IO ()
writeSpanToDevLog TracingSpan
span = do
  now <- IO UTCTime
Time.getCurrentTime
  logFile <- Environment.getEnvDefault "NRI_DEV_LOG" "/tmp/nri-prelude-logs"
  MVar.withMVar writeLock <| \()
_ ->
    String -> IOMode -> (Handle -> IO ()) -> IO ()
forall r. String -> IOMode -> (Handle -> IO r) -> IO r
System.IO.withFile
      String
logFile
      IOMode
System.IO.AppendMode
      ( \Handle
handle -> do
          fileStatus <- String -> IO FileStatus
Files.getFileStatus String
logFile
          let fileMode = FileStatus -> FileMode
Files.fileMode FileStatus
fileStatus
          let fileAccessModes = FileMode -> FileMode -> FileMode
Files.intersectFileModes FileMode
fileMode FileMode
Files.accessModes
          Control.Monad.unless (fileAccessModes == Files.stdFileMode) <|
            Files.setFileMode logFile Files.stdFileMode
          Data.ByteString.Lazy.hPut handle (Aeson.encode (now, span))
          Data.ByteString.Lazy.hPut handle "\n"
      )

-- A lock used to ensure writing spans to the dev log are atomic, processes will
-- take turns to fully write their spans to the log to prevent interleaving.
{-# NOINLINE writeLock #-}
writeLock :: MVar.MVar ()
writeLock :: MVar ()
writeLock =
  () -> IO (MVar ())
forall a. a -> IO (MVar a)
MVar.newMVar ()
    IO (MVar ()) -> (IO (MVar ()) -> MVar ()) -> MVar ()
forall a b. a -> (a -> b) -> b
|> IO (MVar ()) -> MVar ()
forall a. IO a -> a
System.IO.Unsafe.unsafePerformIO