diff --git a/readme.md b/readme.md index d9da0e1..530c26d 100644 --- a/readme.md +++ b/readme.md @@ -62,6 +62,27 @@ The static `Proc.Start` has a timeout of `4 minutes` if not specified. **NOTE** `ConsoleOut` will always be set regardless of whether an `IConsoleOutWriter` is provided +## Proc.StartLongRunning + +Start a process that keeps running, such as a web server or a database, and go on once it says it is ready. +Disposing the returned subscription stops the process. + +```csharp +var args = new LongRunningArguments("dotnet", "run", "--project", "api") +{ + StartedConfirmationHandler = l => l.Line.Contains("Now listening"), + SendControlCFirst = true +}; +using (var api = Proc.StartLongRunning(args, TimeSpan.FromMinutes(1))) +{ + // api.ProcessId, api.ExitCode (once it exited on its own), api.WaitForCompletion(timeout) +} +``` + +`StartLongRunning` waits for a line that `StartedConfirmationHandler` accepts. Without a handler it returns straight away. +When no such line comes in time, it stops the process and throws `ProcExecException`. +`ExitCode` stays `null` while the process runs, and after disposing stopped it. + ## ObservableProcess The heart of it all this is an `IObservable`. It listens on the output buffers directly and does not wait on @@ -166,7 +187,20 @@ let sha = shell { } ``` -See [src/Proc.Fs/README.md](src/Proc.Fs/README.md) for `shell { }`, the `Cmd` module, pipes and the `exec { }` builder. +A block can also start a background process and stop it at the end of a scope, run clean-up commands, and run blocks +at the same time: + +```fsharp +shell { + use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening")) + use! _ = defer (sh $"docker compose down") + let! _ = concurrently [ steps { sh $"dotnet test tests/A" }; steps { sh $"dotnet test tests/B" } ] + return () +} +``` + +See [src/Proc.Fs/README.md](src/Proc.Fs/README.md) for `shell { }`, background processes, the `Cmd` module, pipes and +the `exec { }` builder. # .NET 11 diff --git a/src/Proc.Fs/Bindings.fs b/src/Proc.Fs/Bindings.fs index 7dcb32f..b7b365b 100644 --- a/src/Proc.Fs/Bindings.fs +++ b/src/Proc.Fs/Bindings.fs @@ -16,7 +16,7 @@ type ExecBuilder() = /// the arguments to pass on to the binary being executed [] member this.Execute(opts, binary, [] arguments: string array) = - Runner.run { opts with Binary = binary; Arguments = Some (arguments |> List.ofArray)} + Runner.run System.Threading.CancellationToken.None { opts with Binary = binary; Arguments = Some (arguments |> List.ofArray)} ///Runs using immediately /// the computation build thus far, not specified directly @@ -24,7 +24,7 @@ type ExecBuilder() = /// the arguments to pass on to the binary being executed [] member this.Execute(opts, binary, arguments: string list) = - Runner.run { opts with Binary = binary; Arguments = Some arguments} + Runner.run System.Threading.CancellationToken.None { opts with Binary = binary; Arguments = Some arguments} /// /// Runs the the computation build thus far. @@ -33,7 +33,7 @@ type ExecBuilder() = [] member this.Execute(opts) = if opts.Binary = "" then failwithf "No binary specified to exec computation expression" - Runner.run opts + Runner.run System.Threading.CancellationToken.None opts ///Supply external to bootstrap [] @@ -162,11 +162,11 @@ type ExecBuilder() = [] member this.InvokeArgs(opts, [] arguments: string array) = - Runner.run { opts with Arguments = Some (arguments |> List.ofArray) } + Runner.run System.Threading.CancellationToken.None { opts with Arguments = Some (arguments |> List.ofArray) } [] member this.InvokeArgs(opts, arguments: string list) = - Runner.run { opts with Arguments = Some arguments } + Runner.run System.Threading.CancellationToken.None { opts with Arguments = Some arguments } [] member this.ReturnStatus(opts, binary, arguments: string list) = diff --git a/src/Proc.Fs/Cmd.fs b/src/Proc.Fs/Cmd.fs index 6e37890..10be2b8 100644 --- a/src/Proc.Fs/Cmd.fs +++ b/src/Proc.Fs/Cmd.fs @@ -225,15 +225,18 @@ module internal Runner = lock buffer (fun () -> for line in buffer do console line) reraise () - /// Runs attempt again while it throws ProcExecException and the command's retry policy allows - let retrying (cmd: Cmd) (attempt: unit -> 'T) : 'T = + /// Runs attempt again while it throws ProcExecException and the command's retry policy allows. + /// Stops retrying once ct is cancelled. + let retrying (cmd: Cmd) (ct: CancellationToken) (attempt: unit -> 'T) : 'T = let policy = cmd.Retry |> Option.defaultValue { Retries = 0; Delay = TimeSpan.Zero } let rec go tries = try attempt () - with :? ProcExecException as e when tries < policy.Retries -> + with :? ProcExecException as e when tries < policy.Retries && not ct.IsCancellationRequested -> if cmd.Quiet <> Some true then Console.Error.WriteLine $"Retrying ({tries + 1} of {policy.Retries}) after: {e.Message}" - if policy.Delay > TimeSpan.Zero then Thread.Sleep policy.Delay + if policy.Delay > TimeSpan.Zero then + if ct.CanBeCanceled then ct.WaitHandle.WaitOne policy.Delay |> ignore else Thread.Sleep policy.Delay + ct.ThrowIfCancellationRequested() go (tries + 1) go 0 @@ -310,22 +313,24 @@ module internal Runner = with :? OperationCanceledException when feedCts.IsCancellationRequested -> None completed |> Option.iter (validate upstream)) - /// Runs the command on the shared console and throws when it fails - let run (cmd: Cmd) = - retrying cmd (fun () -> + /// Runs the command on the shared console and throws when it fails. + /// Cancelling ct stops the process and throws OperationCanceledException. + let run (ct: CancellationToken) (cmd: Cmd) = + retrying cmd ct (fun () -> match cmd with - | { Stdin = None; Stdout = None; Quiet = (None | Some false) } -> + // Proc.Exec takes no cancellation token, so a cancellable run streams instead + | { Stdin = None; Stdout = None; Quiet = (None | Some false) } when not ct.CanBeCanceled -> Proc.Exec(Args.exec { cmd with Retry = None }) |> ignore | _ -> withConsole cmd printLine (fun console -> - stream cmd CancellationToken.None console console |> validate cmd)) + stream cmd ct console console |> validate cmd)) /// Calls f for each line of standard out as it is printed; standard error goes to the console - let iter (f: string -> unit) (cmd: Cmd) = - retrying cmd (fun () -> + let iter (ct: CancellationToken) (f: string -> unit) (cmd: Cmd) = + retrying cmd ct (fun () -> withConsole cmd printLine (fun console -> let mutable error: exn = null - use cts = new CancellationTokenSource() + use cts = CancellationTokenSource.CreateLinkedTokenSource ct let onLine (line: LineOut) = if line.Error then console line elif isNull error then @@ -340,14 +345,14 @@ module internal Runner = result |> Option.iter (validate cmd))) /// Runs the command, collecting every line, and reads the result - let get (capture: Capture<'T>) : 'T = - retrying capture.Cmd (fun () -> + let get (ct: CancellationToken) (capture: Capture<'T>) : 'T = + retrying capture.Cmd ct (fun () -> withConsole capture.Cmd printLine (fun console -> let lines = ResizeArray() let onLine (line: LineOut) = lock lines (fun () -> lines.Add line) if line.Error || capture.EchoStdout then console line - let result = stream capture.Cmd CancellationToken.None console onLine + let result = stream capture.Cmd ct console onLine validate capture.Cmd result capture.Read (ProcessCaptureResult(result.Completed, lines, result.ExitCode)))) @@ -437,6 +442,13 @@ module Cmd = /// Terminates the process when this process exits (.NET 11+ on Windows and Linux only) let killOnParentExit (cmd: Cmd) = { cmd with KillOnParentExit = Some true } + /// + /// For background in a shell { } block: wait until the command prints a line, on standard out or + /// standard error, for which is true. Cmd.timeout limits that wait. + /// + let waitFor (isReady: string -> bool) (cmd: Cmd) = + { cmd with StartedConfirmationHandler = Some (fun (line: LineOut) -> isReady line.Line) } + /// Writes to the standard input of the process, then closes it let stdin (lines: string seq) (cmd: Cmd) = { cmd with Stdin = Some (StdinSource.Lines lines) } @@ -531,16 +543,16 @@ module Cmd = let choose (f: string -> 'U option) (capture: Capture) = mapCapture (List.choose f) capture /// Runs the command on the shared console. Throws when it fails. - let run (cmd: Cmd) = Runner.run cmd + let run (cmd: Cmd) = Runner.run CancellationToken.None cmd /// Runs the command and returns what the capture reads - let get (capture: Capture<'T>) : 'T = Runner.get capture + let get (capture: Capture<'T>) : 'T = Runner.get CancellationToken.None capture /// /// Calls for each line of standard out while the command runs, without buffering. /// Standard error goes to the console. Throws when the command fails or throws. /// - let iter (f: string -> unit) (cmd: Cmd) = Runner.iter f cmd + let iter (f: string -> unit) (cmd: Cmd) = Runner.iter CancellationToken.None f cmd /// Brought into scope by open Proc.Fs [] diff --git a/src/Proc.Fs/README.md b/src/Proc.Fs/README.md index 929cd2c..15fd5e3 100644 --- a/src/Proc.Fs/README.md +++ b/src/Proc.Fs/README.md @@ -70,6 +70,57 @@ shell { A command's own `Cmd.cwd` resolves against the shell's directory, and its own `Cmd.env` wins over `setEnv`. `do!` still works in front of commands and steps, for example `do! cd "src"`. +## Background processes, clean-up and running steps at the same time + +```fsharp +shell { + use! api = background (sh $"dotnet run --project api" |> Cmd.waitFor (fun l -> l.Contains "Now listening")) + use! _ = defer (sh $"docker compose down") + sh $"docker compose up -d db" + let! results = concurrently [ + steps { cd "tests/Unit"; sh $"dotnet test" } + steps { cd "tests/Integration"; sh $"dotnet test" } + ] + return results +} // the api gets Ctrl+C, then compose down runs +``` + +| Inside `shell { }` | Does | +|---|---| +| `use! p = background cmd` | starts `cmd` and goes on; stops it at the end of the scope | +| `Cmd.waitFor (fun line -> …)` | `background` first waits for a line that says the process is ready | +| `do! wait p` | waits until the background process exits; throws when its exit code is not accepted | +| `use! _ = defer cmd` | runs `cmd` at the end of the scope, also when the scope fails, like `trap … EXIT` | +| `let! rs = concurrently [ … ]` | runs `steps { }` blocks at the same time; results in the same order | +| `let! rs = concurrentlyAtMost n [ … ]` | the same, at most `n` at a time | + +`background`: + +- The process uses the block's `cd` and `env`. Its output goes to the console. +- Without `Cmd.waitFor`, the block goes on straight away. With it, `background` throws when the process exits before + it prints the line, or when the line does not come within `Cmd.timeout` (default 60 seconds). + On a background command, `Cmd.timeout` only limits that wait, as with `wait_until` in `exec { }`. +- When the process exits with an exit code that `Cmd.validExitCode` does not accept (by default anything but `0`), + the **next command** of the block throws, like `set -e`. An exit code of `0` does not fail the block. +- Stopping sends Ctrl+C first and kills the process when it has not exited after 10 seconds. Stopping never throws. +- The block stops background processes that are still running when it ends, also ones bound with `let!`. +- `p.ProcessId`, `p.HasExited`, `p.ExitCode`, `p.Stop()` and `p.SendControlC()` work on the handle. + +`defer` runs its command in the directory and environment of the moment `defer` runs, so a later `cd` does not +change it. When the scope fails and the deferred command fails too, the scope's exception propagates and the +failure of the deferred command goes to standard error. + +`steps { }` is a `shell { }` block that does not run when it is evaluated. It runs where you use it, with `do!`, +`let!` or on a line of its own, in the directory and environment of the block that uses it. + +`concurrently`: + +- Each branch starts with a copy of the directory and environment, so a `cd` in one branch does not reach the + others or the block. +- The first branch that fails stops the others, and its exception is the one that propagates. +- A background process the block started that fails also fails the branches. +- Output of the branches interleaves line by line on the console. + ## Writing commands with `sh` `sh` takes an interpolated string, `$"…"`. It splits **only the text you wrote**: diff --git a/src/Proc.Fs/Shell.fs b/src/Proc.Fs/Shell.fs index 4a00a7f..ff74835 100644 --- a/src/Proc.Fs/Shell.fs +++ b/src/Proc.Fs/Shell.fs @@ -2,6 +2,44 @@ namespace Proc.Fs open System open System.IO +open System.Runtime.ExceptionServices +open System.Threading +open System.Threading.Tasks +open ProcNet +open ProcNet.Std + +/// +/// A process that background started in a shell { } block. Disposing it stops the process: Ctrl+C +/// first, then a kill when it has not exited after 10 seconds. use! stops it at the end of the scope. +/// +[] +type Background internal (cmd: Cmd, subscription: LongRunningApplicationSubscription) = + let mutable stopped = 0 + + /// The command, with the directory and environment of the shell applied + member _.Cmd = cmd + /// The id of the process + member _.ProcessId = Option.ofNullable subscription.ProcessId + /// The exit code once the process exited on its own; None while it runs or after Stop + member _.ExitCode = Option.ofNullable subscription.ExitCode + /// Whether the process exited on its own + member b.HasExited = b.ExitCode.IsSome + /// Sends Ctrl+C (SIGINT) to the process + member _.SendControlC() = subscription.SendControlC() + + member internal _.IsStopped = stopped = 1 + member internal _.Subscription = subscription + /// Marks the process as handled, so the shell no longer checks or stops it + member internal _.Release() = Interlocked.Exchange(&stopped, 1) = 0 + + /// Stops the process: Ctrl+C first, a kill after 10 seconds. Never throws. + member b.Stop() = + if b.Release() then + try subscription.Dispose() + with e -> Console.Error.WriteLine $"Stopping \"{Runner.describe cmd}\" failed: {e.Message}" + + interface IDisposable with + member b.Dispose() = b.Stop() /// /// The working directory, environment and echo setting shared by every command in one shell { } block. @@ -16,6 +54,38 @@ type ShellContext() = /// Print $ binary arguments before running each command, like set -x member val EchoCommands = false with get, set + /// Cancelled when a sibling branch of concurrently fails + member val internal Token = CancellationToken.None with get, set + /// The context this one was forked from, whose background processes it also checks + member val internal Parent: ShellContext option = None with get, set + /// Background processes started in this context, oldest first + member val internal Backgrounds = ResizeArray() with get + + /// A copy for one branch of concurrently: changes to it do not reach this context + member internal ctx.Fork(token: CancellationToken) = + ShellContext( + WorkingDirectory = ctx.WorkingDirectory, Environment = ctx.Environment, + DirectoryStack = ctx.DirectoryStack, EchoCommands = ctx.EchoCommands, + Token = token, Parent = Some ctx) + + /// Throws when a background process of this context, or of one it was forked from, exited with an exit code + /// its command does not accept + member internal ctx.CheckBackgrounds() = + for background in ctx.Backgrounds do + match background.ExitCode with + | Some code when not background.IsStopped -> + let isValid = background.Cmd.ValidExitCodeClassifier |> Option.defaultValue (fun c -> c = 0) + if not (isValid code) && background.Release() then + raise (ProcExecException( + $"Background process exited with '{code}' \"{Runner.describe background.Cmd}\"", ExitCode = Nullable code)) + | _ -> () + ctx.Parent |> Option.iter (fun parent -> parent.CheckBackgrounds()) + + /// Stops the background processes this context started and nobody stopped, newest first + member internal ctx.StopBackgrounds() = + for i in ctx.Backgrounds.Count - 1 .. -1 .. 0 do ctx.Backgrounds[i].Stop() + ctx.Backgrounds.Clear() + /// Fills in what the command does not set itself: a relative working directory resolves against the shell's, /// and the command's own environment variables win over the shell's member internal ctx.Apply(cmd: Cmd) : Cmd = @@ -36,6 +106,8 @@ type ShellContext() = { cmd with WorkingDirectory = workingDirectory; Environment = environment; Stdin = stdin } member internal ctx.Prepare(cmd: Cmd) = + ctx.Token.ThrowIfCancellationRequested() + ctx.CheckBackgrounds() let cmd = ctx.Apply cmd if ctx.EchoCommands then Console.Out.WriteLine $"$ {Runner.describe cmd}" cmd @@ -58,23 +130,23 @@ type ShellBuilder(echoCommands: bool) = member _.Zero() : ShellStep = ShellStep ignore /// A command on a line of its own: runs it and stops the block when it fails - member _.Yield(cmd: Cmd) : ShellStep = ShellStep (fun ctx -> Runner.run (ctx.Prepare cmd)) + member _.Yield(cmd: Cmd) : ShellStep = ShellStep (fun ctx -> Runner.run ctx.Token (ctx.Prepare cmd)) /// A step such as cd "src" on a line of its own member _.Yield(step: ShellStep) : ShellStep = step member _.Return(value: 'T) : ShellStep<'T> = ShellStep (fun _ -> value) member _.ReturnFrom(step: ShellStep<'T>) = step member _.ReturnFrom(capture: Capture<'T>) : ShellStep<'T> = - ShellStep (fun ctx -> Runner.get { capture with Cmd = ctx.Prepare capture.Cmd }) + ShellStep (fun ctx -> Runner.get ctx.Token { capture with Cmd = ctx.Prepare capture.Cmd }) member _.Bind(step: ShellStep<'T>, f: 'T -> ShellStep<'U>) : ShellStep<'U> = ShellStep (fun ctx -> ShellStep.run ctx step |> f |> ShellStep.run ctx) member _.Bind(cmd: Cmd, f: unit -> ShellStep<'U>) : ShellStep<'U> = ShellStep (fun ctx -> - Runner.run (ctx.Prepare cmd) + Runner.run ctx.Token (ctx.Prepare cmd) ShellStep.run ctx (f ())) member _.Bind(capture: Capture<'T>, f: 'T -> ShellStep<'U>) : ShellStep<'U> = ShellStep (fun ctx -> - Runner.get { capture with Cmd = ctx.Prepare capture.Cmd } |> f |> ShellStep.run ctx) + Runner.get ctx.Token { capture with Cmd = ctx.Prepare capture.Cmd } |> f |> ShellStep.run ctx) member _.Delay(f: unit -> ShellStep<'T>) : ShellStep<'T> = ShellStep (fun ctx -> ShellStep.run ctx (f ())) member _.Combine(first: ShellStep, second: ShellStep<'T>) : ShellStep<'T> = @@ -87,7 +159,7 @@ type ShellBuilder(echoCommands: bool) = /// for line in cmd "git" ["ls-files"] |> Cmd.lines do runs the command, then loops member _.For(capture: Capture<'T list>, body: 'T -> ShellStep) : ShellStep = ShellStep (fun ctx -> - for item in Runner.get { capture with Cmd = ctx.Prepare capture.Cmd } do ShellStep.run ctx (body item)) + for item in Runner.get ctx.Token { capture with Cmd = ctx.Prepare capture.Cmd } do ShellStep.run ctx (body item)) member _.While(guard: unit -> bool, body: ShellStep) : ShellStep = ShellStep (fun ctx -> while guard () do ShellStep.run ctx body) @@ -95,12 +167,37 @@ type ShellBuilder(echoCommands: bool) = ShellStep (fun ctx -> try ShellStep.run ctx body with e -> ShellStep.run ctx (handler e)) member _.TryFinally(body: ShellStep<'T>, compensation: unit -> unit) : ShellStep<'T> = ShellStep (fun ctx -> try ShellStep.run ctx body finally compensation ()) + /// + /// Disposes at the end of the scope. When the scope failed and disposing fails too, + /// the failure of the scope propagates and the failure to dispose goes to standard error. + /// member _.Using(resource: 'R :> IDisposable, body: 'R -> ShellStep<'T>) : ShellStep<'T> = ShellStep (fun ctx -> - try ShellStep.run ctx (body resource) - finally if not (isNull (box resource)) then resource.Dispose()) + let dispose () = if not (isNull (box resource)) then resource.Dispose() + let result = + try ShellStep.run ctx (body resource) + with _ -> + try dispose () + with cleanup -> Console.Error.WriteLine $"Cleanup failed after an earlier error: {cleanup.Message}" + reraise () + dispose () + result) + + /// Runs the block. Background processes still running at its end are stopped. + member _.Run(step: ShellStep<'T>) : 'T = + let ctx = ShellContext(EchoCommands = echoCommands) + try ShellStep.run ctx step + finally ctx.StopBackgrounds() - member _.Run(step: ShellStep<'T>) : 'T = ShellStep.run (ShellContext(EchoCommands = echoCommands)) step +/// +/// Builds steps { } blocks: the same as shell { }, but the block does not run when it is evaluated. +/// It runs where it is used inside a shell { } block, in that block's directory and environment, or as one +/// branch of concurrently. +/// +type StepsBuilder() = + inherit ShellBuilder(false) + /// Returns the block as a step, without running it + member _.Run(step: ShellStep<'T>) : ShellStep<'T> = step /// Brought into scope by open Proc.Fs [] @@ -121,6 +218,111 @@ module ShellSteps = /// Like shell, but prints $ binary arguments before each command, like set -x let shellx = ShellBuilder(true) + /// + /// A block of steps that runs later, where it is used: do! build inside a shell { } block runs it + /// in that block's directory and environment. + /// + /// let build = steps { cd "src"; sh $"dotnet build" } + /// shell { do! build } + /// + /// + let steps = StepsBuilder() + + let private runParallel (limit: int option) (branches: ShellStep<'T> list) : ShellStep<'T list> = + ShellStep (fun ctx -> + use cts = CancellationTokenSource.CreateLinkedTokenSource ctx.Token + use gate = match limit with Some n -> new SemaphoreSlim(n, n) | None -> null + let errorLock = obj () + let firstError: ExceptionDispatchInfo ref = ref null + let fail (e: exn) = + lock errorLock (fun () -> if isNull firstError.Value then firstError.Value <- ExceptionDispatchInfo.Capture e) + cts.Cancel() + let runBranch (branch: ShellStep<'T>) () : 'T option = + let child = ctx.Fork cts.Token + try + try + if not (isNull gate) then gate.Wait cts.Token + try Some (ShellStep.run child branch) + finally if not (isNull gate) then gate.Release() |> ignore + with + // A sibling failed, or the block was cancelled: not this branch's failure + | :? OperationCanceledException when cts.IsCancellationRequested -> None + | e -> fail e; None + finally child.StopBackgrounds() + // The branches block on processes, so each gets a thread of its own instead of one from the pool + let tasks = + branches |> List.map (fun branch -> + Task.Factory.StartNew(runBranch branch, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)) + Task.WaitAll(tasks |> List.map (fun t -> t :> Task) |> Array.ofList) + if not (isNull firstError.Value) then firstError.Value.Throw() + ctx.Token.ThrowIfCancellationRequested() + tasks |> List.map (fun t -> t.Result.Value)) + + /// + /// Runs the branches at the same time and returns their results in the same order. Each branch starts with a + /// copy of the directory and environment, so a cd in one does not reach the others. The first branch + /// that fails stops the others, and its exception is the one that propagates. + /// + /// let! results = concurrently [ steps { sh $"dotnet test a" }; steps { sh $"dotnet test b" } ] + /// + /// + let concurrently (branches: ShellStep<'T> list) : ShellStep<'T list> = runParallel None branches + + /// Like concurrently, but runs at most branches at a time + let concurrentlyAtMost (limit: int) (branches: ShellStep<'T> list) : ShellStep<'T list> = + if limit < 1 then invalidArg (nameof limit) "concurrentlyAtMost needs a limit of at least 1" + runParallel (Some limit) branches + + /// + /// Starts in the background and goes on with the block: use! api = background cmd. + /// With Cmd.waitFor it first waits for a line that says the process is ready; Cmd.timeout limits + /// that wait (default 60 seconds). + /// + /// When the process exits with an exit code it does not accept (Cmd.validExitCode, default only 0), + /// the next command of the block throws. use! stops the process at the end of the scope, and the block + /// stops whatever is still running when it ends. + /// + /// + let background (cmd: Cmd) : ShellStep = + ShellStep (fun ctx -> + let cmd = ctx.Prepare cmd + let cmd = { cmd with SendControlCFirst = Some (defaultArg cmd.SendControlCFirst true) } + // StartLongRunning also returns when the process exits before it printed the line, so track it here + let ready = ref false + let isReady = + cmd.StartedConfirmationHandler |> Option.map (fun isReady -> + fun (line: LineOut) -> if isReady line then ready.Value <- true; true else false) + let args = Args.longRunning { cmd with StartedConfirmationHandler = isReady } + if isReady.IsSome && cmd.StopBufferingAfterStarted.IsNone then args.StopBufferingAfterStarted <- true + let startup = cmd.Timeout |> Option.defaultValue (TimeSpan.FromSeconds 60.) + let subscription = Proc.StartLongRunning(args, startup, null, ctx.Token) + let started = new Background(cmd, subscription) + if isReady.IsSome && not ready.Value then + started.Stop() + let code = started.ExitCode |> Option.map string |> Option.defaultValue "?" + raise (ProcExecException( + $"Background process exited with '{code}' before it was ready \"{Runner.describe cmd}\"", + ExitCode = Option.toNullable started.ExitCode)) + ctx.Backgrounds.Add started + started) + + /// + /// Waits until a background process exits, like wait in bash. Throws when its exit code is not + /// accepted. The shell no longer checks or stops the process afterwards. + /// + let wait (background: Background) : ShellStep = + ShellStep (fun ctx -> + background.Subscription.WaitForCompletion(Nullable(), ctx.Token) |> ignore + if background.Release() then + let cmd = background.Cmd + match background.ExitCode with + | None -> raise (ProcExecException($"Process did not report an exit code \"{Runner.describe cmd}\"")) + | Some code -> + let isValid = cmd.ValidExitCodeClassifier |> Option.defaultValue (fun c -> c = 0) + if not (isValid code) then + raise (ProcExecException($"Process exited with '{code}' \"{Runner.describe cmd}\"", ExitCode = Nullable code)) + else invalidOp $"wait: \"{Runner.describe background.Cmd}\" was already stopped or waited for") + let private currentDirectory (ctx: ShellContext) = ctx.WorkingDirectory |> Option.defaultWith Directory.GetCurrentDirectory @@ -132,6 +334,22 @@ module ShellSteps = let private restoring (restore: unit -> unit) = { new IDisposable with member _.Dispose() = restore () } + /// + /// Runs at the end of the enclosing scope, also when the scope fails, like + /// trap … EXIT: use! _ = defer (sh $"docker compose down"). It runs in the directory and + /// environment of the moment defer runs, so a later cd does not change it. + /// + let defer (cmd: Cmd) : ShellStep = + ShellStep (fun ctx -> + let cmd = ctx.Apply cmd + let echo = ctx.EchoCommands + let ran = ref 0 + restoring (fun () -> + if Interlocked.Exchange(&ran.contents, 1) = 0 then + if echo then Console.Out.WriteLine $"$ {Runner.describe cmd}" + // Not the block's token: clean-up runs even when the block was cancelled + Runner.run CancellationToken.None cmd)) + /// /// Changes the working directory for the commands that follow in this shell { } block. /// A relative path resolves against the current one. Throws when the directory does not exist. diff --git a/src/Proc.Fs/skills/proc-fs/SKILL.md b/src/Proc.Fs/skills/proc-fs/SKILL.md index 96743fe..3dbe008 100644 --- a/src/Proc.Fs/skills/proc-fs/SKILL.md +++ b/src/Proc.Fs/skills/proc-fs/SKILL.md @@ -37,11 +37,24 @@ shell { } ``` +Background processes, clean-up and steps that run at the same time: + +```fsharp +shell { + use! api = background (sh $"dotnet run" |> Cmd.waitFor (fun l -> l.Contains "Now listening")) // stopped at scope end + use! _ = defer (sh $"docker compose down") // runs at scope end, also after a failure + let! results = concurrently [ steps { sh $"dotnet test a" }; steps { sh $"dotnet test b" } ] + return results +} +``` + ## Gotchas - `sh` takes an interpolated string and splits only the text you wrote: whitespace separates arguments, quotes group them, and an interpolated value never splits. Do not build the command string with `sprintf` first. - Unquoted `>`, `<`, `;` and `&` throw: there is no redirection or chaining. Quote them to pass them literally, and use separate `sh` lines instead of `;` or `&&`. -- A `shell { }` block runs as soon as it is evaluated; wrap it in a function to run it later. +- A `shell { }` block runs as soon as it is evaluated; use `steps { }` for a block that runs later, where it is used. +- A background process that exits with a non-zero exit code fails the next command of the block. +- `parallel` is reserved in F#: the step is `concurrently`. - The package's README has the full list of steps, `exec { }` and `Cmd`. diff --git a/src/Proc/Proc.StartLongRunning.cs b/src/Proc/Proc.StartLongRunning.cs index b71c5d0..7e63cfa 100644 --- a/src/Proc/Proc.StartLongRunning.cs +++ b/src/Proc/Proc.StartLongRunning.cs @@ -23,6 +23,18 @@ internal LongRunningApplicationSubscription(ObservableProcess process, Composite public ManualResetEvent WaitHandle { get; } = new(false); + /// The id of the process, once it started + public int? ProcessId => Process?.ProcessId; + + /// + /// The exit code of the process once it exited on its own. null while it runs, and after it was stopped + /// by . + /// + public int? ExitCode => Process?.ExitCode; + + /// + public bool WaitForCompletion(TimeSpan? timeout, CancellationToken ct = default) => Process.WaitForCompletion(timeout, ct); + /// > public bool SendControlC(int processId) => Process.SendControlC(processId); diff --git a/src/Proc/README.md b/src/Proc/README.md index 8216660..0f7f061 100644 --- a/src/Proc/README.md +++ b/src/Proc/README.md @@ -57,6 +57,27 @@ The static `Proc.Start` has a timeout of `4 minutes` if not specified. **NOTE** `ConsoleOut` will always be set regardless of whether an `IConsoleOutWriter` is provided +## Proc.StartLongRunning + +Start a process that keeps running, such as a web server or a database, and go on once it says it is ready. +Disposing the returned subscription stops the process. + +```csharp +var args = new LongRunningArguments("dotnet", "run", "--project", "api") +{ + StartedConfirmationHandler = l => l.Line.Contains("Now listening"), + SendControlCFirst = true +}; +using (var api = Proc.StartLongRunning(args, TimeSpan.FromMinutes(1))) +{ + // api.ProcessId, api.ExitCode (once it exited on its own), api.WaitForCompletion(timeout) +} +``` + +`StartLongRunning` waits for a line that `StartedConfirmationHandler` accepts. Without a handler it returns straight away. +When no such line comes in time, it stops the process and throws `ProcExecException`. +`ExitCode` stays `null` while the process runs, and after disposing stopped it. + ## ObservableProcess The heart of it all this is an `IObservable`. It listens on the output buffers directly and does not wait on diff --git a/src/Proc/skills/proc/SKILL.md b/src/Proc/skills/proc/SKILL.md index 70a5a11..a09a391 100644 --- a/src/Proc/skills/proc/SKILL.md +++ b/src/Proc/skills/proc/SKILL.md @@ -16,7 +16,7 @@ description: >- | the same, async | `await Proc.ExecAsync(new ExecArguments("dotnet", "build"), ct)` | exit code | | its output | `Proc.Start("git", "status", "--short")` | `ProcessCaptureResult`: `Completed`, `ExitCode`, `ConsoleOut` | | each line as it arrives | `Proc.StartRedirected(handler, "dotnet", "test")` | `ProcessResult` | -| a long-running server you wait on | `Proc.StartLongRunning(args, waitForStartedConfirmation)` | a subscription; dispose it to stop | +| a long-running server you wait on | `Proc.StartLongRunning(args, waitForStartedConfirmation)` | a subscription with `ProcessId` and `ExitCode`; dispose it to stop | ```csharp // options go on ExecArguments / StartArguments diff --git a/tests/Proc.Fs.Tests/ConcurrencyTests.fs b/tests/Proc.Fs.Tests/ConcurrencyTests.fs new file mode 100644 index 0000000..ea5e50d --- /dev/null +++ b/tests/Proc.Fs.Tests/ConcurrencyTests.fs @@ -0,0 +1,297 @@ +module Proc.Fs.Tests.ConcurrencyTests + +open System +open System.Diagnostics +open System.IO +open ProcNet +open Proc.Fs +open Proc.Fs.Tests.TestBinary +open TUnit.Core + +let private bin = TestBinary.path +let private test args = cmd bin args |> Cmd.timeout (TimeSpan.FromSeconds 20.) + +/// A background server: prints "ready" and its process id, then runs until stopped +let private server () = cmd bin [ "ReadyThenWait" ] |> Cmd.waitFor ((=) "ready") + +let private isRunning (pid: int) = + try not (Process.GetProcessById(pid).HasExited) + with :? ArgumentException -> false + +let private pidOf (background: Background) = + match background.ProcessId with + | Some pid -> pid + | None -> failwith "the background process has no process id" + +type BackgroundTests() = + + [] + member _.``background waits for the ready line and use! stops the process at the end of the scope`` () = + let pid = ref 0 + shell { + do! steps { + use! api = background (server ()) + pid.Value <- pidOf api + Assert.True(isRunning pid.Value, "the background process is not running inside its scope") + do! test [ "ExitWith"; "0" ] + } + Assert.False(isRunning pid.Value, "the background process still runs after its scope") + } + Assert.False(isRunning pid.Value) + + [] + member _.``the block stops a background process bound with let!`` () = + let pid = shell { + let! api = background (server ()) + return pidOf api + } + Assert.False(isRunning pid, "the background process outlived the block") + + [] + member _.``background uses the environment of the block`` () = + let seen = shell { + setEnv "PROC_FS_BACKGROUND" "from-the-shell" + use! printer = background (cmd bin [ "PrintEnv"; "PROC_FS_BACKGROUND" ] |> Cmd.waitFor ((=) "from-the-shell")) + return printer.Cmd.Environment |> Option.bind (Map.tryFind "PROC_FS_BACKGROUND") + } + Assert.Equal(Some "from-the-shell", seen) + + [] + member _.``a background process that crashes fails the next command`` () = + let ranAfter = ref false + let ex = Assert.Throws(fun () -> + shell { + use! _ = background (cmd bin [ "ReadyThenExit"; "3"; "100" ] |> Cmd.waitFor ((=) "ready")) + do! test [ "Sleep"; "1000" ] + do! test [ "ExitWith"; "0" ] + ranAfter.Value <- true + }) + Assert.Equal(Nullable 3, ex.ExitCode) + Assert.Contains("Background process exited with '3'", ex.Message) + Assert.False(ranAfter.Value, "a command ran after the background process crashed") + + [] + member _.``a background process that exits with 0 does not fail the block`` () = + let ranAfter = ref false + shell { + use! _ = background (cmd bin [ "ReadyThenExit"; "0"; "100" ] |> Cmd.waitFor ((=) "ready")) + do! test [ "Sleep"; "1000" ] + do! test [ "ExitWith"; "0" ] + ranAfter.Value <- true + } + Assert.True ranAfter.Value + + [] + member _.``background throws when the process exits before it is ready`` () = + let ex = Assert.Throws(fun () -> + shell { + use! _ = background (cmd bin [ "ExitWith"; "4" ] |> Cmd.waitFor ((=) "never printed")) + return () + }) + Assert.Contains("before it was ready", ex.Message) + Assert.Equal(Nullable 4, ex.ExitCode) + + [] + member _.``background stops the process when it is not ready in time`` () = + let pid = ref 0 + let notReady (line: string) = + match Int32.TryParse line with + | true, p -> pid.Value <- p + | _ -> () + false + let started = Stopwatch.StartNew() + Assert.Throws(fun () -> + shell { + use! _ = background (cmd bin [ "ReadyThenWait" ] |> Cmd.waitFor notReady |> Cmd.timeout (TimeSpan.FromSeconds 1.)) + return () + }) |> ignore + Assert.True(started.Elapsed < TimeSpan.FromSeconds 15., $"took {started.Elapsed}") + Assert.NotEqual(0, pid.Value) + Assert.False(isRunning pid.Value, "the process that was not ready in time still runs") + + [] + member _.``wait throws when the background process fails`` () = + let ex = Assert.Throws(fun () -> + shell { + let! job = background (cmd bin [ "ReadyThenExit"; "5"; "50" ] |> Cmd.waitFor ((=) "ready")) + do! wait job + }) + Assert.Equal(Nullable 5, ex.ExitCode) + + [] + member _.``wait returns once the background process exits with 0`` () = + let exitCode = shell { + let! job = background (cmd bin [ "ReadyThenExit"; "0"; "50" ] |> Cmd.waitFor ((=) "ready")) + do! wait job + do! test [ "ExitWith"; "0" ] + return job.ExitCode + } + Assert.Equal(Some 0, exitCode) + +type DeferTests() = + + [] + member _.``defer runs at the end of the scope`` () = + use dir = new TempDir() + let marker = dir.File "deferred.txt" + let existedInside = shell { + use! _ = defer (test [ "PrintArgs"; "cleaned" ] |> Cmd.toFile marker) + return File.Exists marker + } + Assert.False(existedInside, "the deferred command ran before the end of its scope") + Assert.Equal("cleaned", (File.ReadAllText marker).Trim()) + + [] + member _.``defer runs when the scope fails`` () = + use dir = new TempDir() + let marker = dir.File "deferred.txt" + let ex = Assert.Throws(fun () -> + shell { + use! _ = defer (test [ "PrintArgs"; "cleaned" ] |> Cmd.toFile marker) + do! test [ "ExitWith"; "3" ] + }) + Assert.Equal(Nullable 3, ex.ExitCode) + Assert.True(File.Exists marker, "the deferred command did not run after the failure") + + [] + member _.``the failure of the scope wins over a failing deferred command`` () = + let ex = Assert.Throws(fun () -> + shell { + use! _ = defer (test [ "ExitWith"; "9" ]) + do! test [ "ExitWith"; "3" ] + }) + Assert.Equal(Nullable 3, ex.ExitCode) + + [] + member _.``a failing deferred command fails a scope that succeeded`` () = + let ex = Assert.Throws(fun () -> + shell { + use! _ = defer (test [ "ExitWith"; "9" ]) + do! test [ "ExitWith"; "0" ] + }) + Assert.Equal(Nullable 9, ex.ExitCode) + + [] + member _.``defer keeps the directory of the moment it ran`` () = + use dir = new TempDir() + Directory.CreateDirectory(dir.File "sub") |> ignore + shell { + cd dir.Path + use! _ = defer (test [ "PrintArgs"; "cleaned" ] |> Cmd.toFile "deferred.txt") + cd "sub" + } + Assert.True(File.Exists(dir.File "deferred.txt"), "the deferred command did not run in the directory of defer") + Assert.False(File.Exists(Path.Combine(dir.Path, "sub", "deferred.txt"))) + +type StepsTests() = + + [] + member _.``steps does not run until it is used`` () = + let ran = ref false + let later = steps { + do! test [ "ExitWith"; "0" ] + ran.Value <- true + } + Assert.False(ran.Value, "steps ran when it was evaluated") + shell { do! later } + Assert.True ran.Value + + [] + member _.``steps runs in the environment of the block that uses it`` () = + let read = steps { + let! value = test [ "PrintEnv"; "PROC_FS_STEPS" ] |> Cmd.text + return value + } + let value = shell { + setEnv "PROC_FS_STEPS" "inherited" + let! value = read + return value + } + Assert.Equal("inherited", value) + +type ConcurrentlyTests() = + + [] + member _.``concurrently runs the branches at the same time and keeps their order`` () = + let started = Stopwatch.StartNew() + let results = shell { + let! results = concurrently [ + for name in [ "a"; "b"; "c" ] -> + steps { + do! test [ "Sleep"; "1500" ] + let! echoed = test [ "PrintArgs"; name ] |> Cmd.text + return echoed + } + ] + return results + } + Assert.Equal([ "a"; "b"; "c" ], results) + // One after the other takes 4.5s or more + Assert.True(started.Elapsed < TimeSpan.FromSeconds 4., $"took {started.Elapsed}") + + [] + member _.``the first failing branch stops the others and its exception propagates`` () = + let started = Stopwatch.StartNew() + let ranAfter = ref false + let ex = Assert.Throws(fun () -> + shell { + let! _ = concurrently [ + steps { + do! test [ "Sleep"; "30000" ] + ranAfter.Value <- true + } + steps { do! test [ "ExitWith"; "3" ] } + ] + return () + }) + Assert.Equal(Nullable 3, ex.ExitCode) + Assert.False(ranAfter.Value, "the sibling of the failing branch went on") + Assert.True(started.Elapsed < TimeSpan.FromSeconds 15., $"took {started.Elapsed}") + + [] + member _.``a cd inside a branch does not reach the block`` () = + use dir = new TempDir() + let before, after = shell { + let! before = pwd + let! _ = concurrently [ steps { cd dir.Path } ] + let! after = pwd + return before, after + } + Assert.Equal(before, after) + + [] + member _.``concurrentlyAtMost 1 runs one branch at a time`` () = + let started = Stopwatch.StartNew() + shell { + let! _ = concurrentlyAtMost 1 [ steps { do! test [ "Sleep"; "800" ] }; steps { do! test [ "Sleep"; "800" ] } ] + return () + } + Assert.True(started.Elapsed >= TimeSpan.FromSeconds 1.6, $"took {started.Elapsed}") + + [] + member _.``a background process started in a branch stops when the branch ends`` () = + let pids = shell { + let! pids = concurrently [ + steps { + let! api = background (server ()) + return pidOf api + } + ] + return pids + } + Assert.All(pids, fun pid -> Assert.False(isRunning pid, "the background process outlived its branch")) + + [] + member _.``a background process of the block that crashes fails a branch`` () = + let ex = Assert.Throws(fun () -> + shell { + use! _ = background (cmd bin [ "ReadyThenExit"; "6"; "100" ] |> Cmd.waitFor ((=) "ready")) + let! _ = concurrently [ + steps { + do! test [ "Sleep"; "1000" ] + do! test [ "ExitWith"; "0" ] + } + ] + return () + }) + Assert.Equal(Nullable 6, ex.ExitCode) diff --git a/tests/Proc.Fs.Tests/Proc.Fs.Tests.fsproj b/tests/Proc.Fs.Tests/Proc.Fs.Tests.fsproj index 99e4c9f..9e159ed 100644 --- a/tests/Proc.Fs.Tests/Proc.Fs.Tests.fsproj +++ b/tests/Proc.Fs.Tests/Proc.Fs.Tests.fsproj @@ -19,6 +19,7 @@ + diff --git a/tests/Proc.Tests.Binary/Program.cs b/tests/Proc.Tests.Binary/Program.cs index 32021b9..f968da8 100644 --- a/tests/Proc.Tests.Binary/Program.cs +++ b/tests/Proc.Tests.Binary/Program.cs @@ -75,6 +75,12 @@ public static async Task Main(string[] args) return KillOnParentExitChild(args[1]); if (testCase == nameof(WriteChildPidAndWait).ToLowerInvariant()) return WriteChildPidAndWait(args[1]); + if (testCase == nameof(ReadyThenWait).ToLowerInvariant()) + return await ReadyThenWait(); + if (testCase == nameof(ReadyThenExit).ToLowerInvariant()) + return await ReadyThenExit(args[1], args[2]); + if (testCase == nameof(Sleep).ToLowerInvariant()) + return await Sleep(args[1]); return 1; } @@ -86,6 +92,31 @@ private static int PrintArgs(string[] args) } private static int ExitWith(string exitCode) => int.Parse(exitCode, CultureInfo.InvariantCulture); + // Prints "ready" and its process id, then runs until it is stopped. Used as a background server. + private static async Task ReadyThenWait() + { + Console.WriteLine("ready"); + Console.WriteLine(Environment.ProcessId.ToString(CultureInfo.InvariantCulture)); + await Task.Delay(Timeout.Infinite); + return 0; + } + + // Prints "ready", then exits with the given exit code after the given number of milliseconds. + private static async Task ReadyThenExit(string exitCode, string milliseconds) + { + Console.WriteLine("ready"); + await Task.Delay(int.Parse(milliseconds, CultureInfo.InvariantCulture)); + return int.Parse(exitCode, CultureInfo.InvariantCulture); + } + + // Sleeps the given number of milliseconds, then prints "slept" and exits with 0. + private static async Task Sleep(string milliseconds) + { + await Task.Delay(int.Parse(milliseconds, CultureInfo.InvariantCulture)); + Console.WriteLine("slept"); + return 0; + } + // Counts its runs in the given file and exits with 1 for the first runs, 0 after that. // Prints "attempt N" to standard out and "failed N" to standard error on a failing run. private static int FailTimes(string counterFile, string times)