packages feed

plexus-synapse-4.2.0: src/Synapse/Watch.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}

-- | @--watch@: a call made again each time a file it reads changes.
--
-- The owner, 2026-11-16, of writing a component against a running service
-- and seeing it drawn as it is written: "write the change into synapse for
-- now". A value read from a file (@--flag \@FILE@, @-p \@FILE@, SYNAPSE-10)
-- is read once, so every save was the command run again by hand. With
-- @--watch@ synapse does that:
--
-- @
-- synapse --watch -P 4460 menger ui author --bundle live \\
--   --sources.name clock --sources.profile svelte/1 --sources.source \@clock.svelte
-- @
--
-- * the call is made at once, then again on every change of a file the
--   command names with @\@@ — the command as written, the files read anew;
-- * __each call is a process of its own__ (this binary, the same arguments
--   without @--watch@), so a call under @--watch@ is the call run by hand:
--   the same answer, the same exit code, the same @-o FILE@ written whole,
--   and nothing of one call's state left for the next. The connection is
--   the holder's (SYNAPSE-28), so a call is still one round trip;
-- * a file is looked at every 20 ms (its modification time and size — no
--   watcher's library, and a save by rename is seen as any other), and
--   read once it has stopped changing for 15 ms, so an editor that
--   truncates and writes is one change, not two;
-- * changes that arrive while a call runs are one more call when it ends,
--   however many they were: the last contents are what is sent;
-- * a call that fails ends nothing — its failure is on stderr as it would
--   be, and the next change is the next call. Ctrl-C ends it, 130.
--
-- It is the client's half of writing against a running service, and no
-- faster than the method it calls: a save is one call, answered when the
-- service has done with it.
--
-- stdout carries the calls' answers and nothing else; what the watch has to
-- say (what it follows, and after each call which file changed, how the
-- call ended, how long it took and how long after the save that was) goes
-- to stderr.
--
-- Refused, 2, before anything is called: a command that reads no file
-- (nothing would ever change), and one that reads stdin (it is read once).
module Synapse.Watch
  ( -- * What is watched
    WatchRefusal(..)
  , watchedFiles
  , renderRefusal
  , childArgs

    -- * A file's state
  , Stamp(..)
  , stampOf
  , awaitChange
  , pollMicros
  , settleMicros

    -- * The loop
  , runWatch
  , reportLine
  ) where

import Control.Concurrent (threadDelay)
import Control.Exception (AsyncException(..), IOException, catch, throwIO)
import Control.Monad (when)
import Data.List (intercalate, nub)
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Clock (NominalDiffTime, UTCTime, diffUTCTime, getCurrentTime)
import System.Directory (getCurrentDirectory, getFileSize, getModificationTime)
import System.Environment (getExecutablePath)
import System.Exit (ExitCode(..), exitWith)
import System.FilePath (makeRelative)
import System.IO (hFlush, hPutStrLn, stderr, stdout)
import System.Process (CreateProcess(..), proc, waitForProcess, withCreateProcess)

import Synapse.CLI.Source (SourceEnv, sourcePath)

-- ============================================================================
-- What is watched
-- ============================================================================

-- | Why a command cannot be watched.
data WatchRefusal
  = NothingToWatch
    -- ^ no value of the command is read from a file
  | ReadsStdin Text
    -- ^ a value is read from stdin: the flag as written (@-p@, @--body@)
  deriving (Show, Eq)

-- | The files a command reads, in the order it names them, each once:
-- @-p@'s value and every value after the service's name. The values are
-- taken as written, before any flag is paired with its parameter (the
-- method is not known yet): a token that begins with @\@@ is a file exactly
-- when 'Synapse.CLI.Source.expandValue' would read it as one.
watchedFiles :: SourceEnv -> Maybe Text -> [Text] -> Either WatchRefusal [FilePath]
watchedFiles env params path
  | Just flag <- listToMaybe [f | (f, "-") <- values] = Left (ReadsStdin flag)
  | null files = Left NothingToWatch
  | otherwise = Right (nub files)
  where
    values = [("-p", v) | Just v <- [params]] ++ flagValues path
    files = mapMaybe (sourcePath env . snd) values

-- | Each value after the service's name with the flag it follows:
-- @--key value@ and @--key=value@. A token that is no flag's value (a path
-- segment, the method) is paired with the empty flag, and is no file.
flagValues :: [Text] -> [(Text, Text)]
flagValues = go ""
  where
    go _ [] = []
    go prev (t : rest)
      | Just kv <- T.stripPrefix "--" t, not (T.null kv) =
          case T.breakOn "=" kv of
            (k, v) | not (T.null v) -> ("--" <> k, T.drop 1 v) : go "" rest
            _ -> go t rest
      | otherwise = (prev, t) : go "" rest

renderRefusal :: WatchRefusal -> Text
renderRefusal = \case
  NothingToWatch ->
    "--watch follows the files a call reads, and this one reads none: give a value as @FILE "
      <> "(--body @body.md, -p @params.json), and the call is made again each time that file changes"
  ReadsStdin flag ->
    "--watch cannot follow stdin (" <> flag <> " -): stdin is read once. Give the value as @FILE"

-- | The arguments of one call: the command's own, without @--watch@. The
-- option is synapse's, so it stands before the service's name, and the
-- first one is it.
childArgs :: [String] -> [String]
childArgs args = case break (== "--watch") args of
  (before, _ : after) -> before ++ after
  (before, []) -> before

-- ============================================================================
-- A file's state
-- ============================================================================

-- | What is known of a file without reading it: when it was last written
-- and how long it is, or that it is not there.
data Stamp = Gone | Stamp UTCTime Integer
  deriving (Show, Eq)

stampOf :: FilePath -> IO Stamp
stampOf f = (Stamp <$> getModificationTime f <*> getFileSize f)
  `catch` \(_ :: IOException) -> pure Gone

-- | How often the files are looked at, and how long they must have stood
-- still before they are read (microseconds).
pollMicros, settleMicros :: Int
pollMicros = 20000
settleMicros = 15000

-- | Waits until the files are no longer as @seen@ and have stopped
-- changing; answers them as they are now, and which changed. A file that
-- was there and is gone is waited for — a save by rename has it missing
-- for a moment, and a file deleted for good has nothing to send.
awaitChange :: Int -> Int -> [(FilePath, Stamp)] -> IO ([(FilePath, Stamp)], [FilePath])
awaitChange poll settle seen = look >>= waiting
  where
    look = mapM (\(f, _) -> (f,) <$> stampOf f) seen
    vanished now = or [was /= Gone && is == Gone | ((_, was), (_, is)) <- zip seen now]
    waiting now
      | map snd now == map snd seen || vanished now = threadDelay poll >> look >>= waiting
      | otherwise = settling now
    settling prev = do
      threadDelay settle
      now <- look
      if map snd now /= map snd prev || vanished now
        then settling now
        else if map snd now == map snd seen
          -- it changed and changed back (a touch undone): nothing to send
          then waiting now
          else pure (now, [f | ((f, is), (_, was)) <- zip now seen, is /= was])

-- ============================================================================
-- The loop
-- ============================================================================

-- | What stderr says after a call: which call it was, what changed, how it
-- ended, how long the call took and — for a change — how long after the
-- save its answer was whole. A call that ended 0 was /answered/, and no
-- more is claimed: what a service refuses in band (a source that does not
-- compile) is an answer, printed above this line as any answer is.
reportLine :: Int -> [FilePath] -> ExitCode -> NominalDiffTime -> Maybe NominalDiffTime -> String
reportLine n changed code took sinceSave =
  "synapse: #" <> show n <> " " <> what <> ": " <> ended <> " in " <> ms took
    <> maybe "" (\d -> ", " <> ms d <> " after the save") sinceSave
  where
    what = if null changed then "the call as it stands" else intercalate ", " changed <> " changed"
    ended = case code of
      ExitSuccess -> "answered"
      ExitFailure c -> "exit " <> show c
    ms d = show (round (realToFrac d * 1000 :: Double) :: Integer) <> " ms"

-- | The watch: the call now, then again on every change of @files@, each a
-- process of its own running this binary with @args@. Never returns: it
-- ends by Ctrl-C (130), or with a call that was itself interrupted.
runWatch :: [FilePath] -> [String] -> IO a
runWatch files args = do
  exe <- getExecutablePath
  cwd <- getCurrentDirectory
  let shown = makeRelative cwd
  say $ "synapse: watching " <> intercalate ", " (map shown files)
    <> " \x2014 the call is made now, and again on every change; Ctrl-C ends it"
  seen <- mapM (\f -> (f,) <$> stampOf f) files
  let go :: Int -> [FilePath] -> [(FilePath, Stamp)] -> IO a
      go n changed now = do
        t0 <- getCurrentTime
        code <- withCreateProcess (proc exe args) { delegate_ctlc = True } $ \_ _ _ ph -> waitForProcess ph
        t1 <- getCurrentTime
        hFlush stdout
        let saved = [t | (f, Stamp t _) <- now, f `elem` changed]
            sinceSave = if null saved then Nothing else Just (diffUTCTime t1 (maximum saved))
        say (reportLine n (map shown changed) code (diffUTCTime t1 t0) sinceSave)
        -- the call was interrupted (Ctrl-C reaches it too): so is the watch
        when (code == ExitFailure 130) $ exitWith code
        (now', changed') <- awaitChange pollMicros settleMicros now
        go (n + 1) changed' now'
  go 1 [] seen `catch` \case
    UserInterrupt -> exitWith (ExitFailure 130)
    e -> throwIO e
  where
    say = hPutStrLn stderr