|
| 1 | +package examples.client |
| 2 | + |
| 3 | +import fs2.Stream |
| 4 | +import cats.effect._ |
| 5 | +import cats.syntax.all._ |
| 6 | +import scala.jdk.CollectionConverters._ |
| 7 | +import java.io.OutputStream |
| 8 | + |
| 9 | +trait ChildProcess[F[_]] { |
| 10 | + def stdin: fs2.Pipe[F, Byte, Unit] |
| 11 | + def stdout: Stream[F, Byte] |
| 12 | + def stderr: Stream[F, Byte] |
| 13 | +} |
| 14 | + |
| 15 | +object ChildProcess { |
| 16 | + |
| 17 | + def spawn[F[_]: Async](command: String*): Stream[F, ChildProcess[F]] = |
| 18 | + Stream.bracket(start[F](command))(_._2).map(_._1) |
| 19 | + |
| 20 | + val readBufferSize = 512 |
| 21 | + private def start[F[_]: Async](command: Seq[String]) = Async[F].interruptible { |
| 22 | + val p = |
| 23 | + new java.lang.ProcessBuilder(command.asJava) |
| 24 | + .start() // .directory(new java.io.File(wd)).start() |
| 25 | + val done = Async[F].fromCompletableFuture(Sync[F].delay(p.onExit())) |
| 26 | + |
| 27 | + val terminate: F[Unit] = Sync[F].interruptible(p.destroy()) |
| 28 | + |
| 29 | + import cats._ |
| 30 | + val onGlobal = new (F ~> F) { |
| 31 | + def apply[A](fa: F[A]): F[A] = Async[F].evalOn(fa, scala.concurrent.ExecutionContext.global) |
| 32 | + } |
| 33 | + |
| 34 | + val cp = new ChildProcess[F] { |
| 35 | + def stdin: fs2.Pipe[F, Byte, Unit] = |
| 36 | + writeOutputStreamFlushingChunks[F](Sync[F].interruptible(p.getOutputStream())) |
| 37 | + |
| 38 | + def stdout: fs2.Stream[F, Byte] = fs2.io |
| 39 | + .readInputStream[F](Sync[F].interruptible(p.getInputStream()), chunkSize = readBufferSize) |
| 40 | + .translate(onGlobal) |
| 41 | + |
| 42 | + def stderr: fs2.Stream[F, Byte] = fs2.io |
| 43 | + .readInputStream[F](Sync[F].blocking(p.getErrorStream()), chunkSize = readBufferSize) |
| 44 | + .translate(onGlobal) |
| 45 | + // Avoids broken pipe - we cut off when the program ends. |
| 46 | + // Users can decide what to do with the error logs using the exitCode value |
| 47 | + .interruptWhen(done.void.attempt) |
| 48 | + } |
| 49 | + (cp, terminate) |
| 50 | + } |
| 51 | + |
| 52 | + /** Adds a flush after each chunk |
| 53 | + */ |
| 54 | + def writeOutputStreamFlushingChunks[F[_]]( |
| 55 | + fos: F[OutputStream], |
| 56 | + closeAfterUse: Boolean = true |
| 57 | + )(implicit F: Sync[F]): fs2.Pipe[F, Byte, Nothing] = |
| 58 | + s => { |
| 59 | + def useOs(os: OutputStream): Stream[F, Nothing] = |
| 60 | + s.chunks.foreach(c => F.interruptible(os.write(c.toArray)) >> F.blocking(os.flush())) |
| 61 | + |
| 62 | + val os = |
| 63 | + if (closeAfterUse) Stream.bracket(fos)(os => F.blocking(os.close())) |
| 64 | + else Stream.eval(fos) |
| 65 | + os.flatMap(os => useOs(os) ++ Stream.exec(F.blocking(os.flush()))) |
| 66 | + } |
| 67 | + |
| 68 | +} |
0 commit comments