Skip to content

Instantly share code, notes, and snippets.

@otobrglez
Last active September 16, 2021 12:07
Show Gist options
  • Save otobrglez/6466eda97114b2267dc81655a51f34cf to your computer and use it in GitHub Desktop.
Save otobrglez/6466eda97114b2267dc81655a51f34cf to your computer and use it in GitHub Desktop.
Booting Akka with Cats Effect
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import cats.effect.{IO, IOApp, Resource}
import cats.syntax.all.catsSyntaxMonadErrorRethrow
import ch.megard.akka.http.cors.scaladsl.CorsDirectives.cors
import com.google.cloud.texttospeech.v1.TextToSpeechClient
import com.typesafe.scalalogging.LazyLogging
object Boot extends IOApp.Simple with LazyLogging {
def logInfo(message: String): IO[Unit] = IO(logger.info(message)).void
def mkTextToSpeechClient(): Resource[IO, TextToSpeechClient] =
Resource.make(IO(TextToSpeechClient.create()))(client => IO(client.shutdown()))
.evalTap(_ => logInfo("TextToSpeech Client Started"))
.onFinalize(logInfo("TextToSpeech Client Finalized"))
def mkServer(config: Configuration,
ttsClient: TextToSpeechClient)
(implicit actorSystem: ActorSystem): Resource[IO, Http.ServerBinding] =
Resource.make {
IO.fromFuture(IO(
Http()(actorSystem)
.newServerAt(config.voice.interface, config.voice.port)
.bindFlow(cors()(get(complete(s"Voice ${BuildInfo}"))))
))
}(binding => IO.fromFuture(IO(binding.unbind())).void)
def mkActorSystem(): Resource[IO, ActorSystem] =
Resource.make(IO(ActorSystem("voice-backend")))(
system => IO.fromFuture(IO(system.terminate())).void)
def printBanner(): IO[Unit] =
logInfo(s"""Voice $BuildInfo""".stripMargin)
val run: IO[Unit] =
(for {
_ <- Resource.eval(printBanner())
config <- Resource.eval(IO(Configuration.load()).rethrow)
client <- mkTextToSpeechClient()
system <- mkActorSystem()
server <- mkServer(config, client)(system)
} yield {
server
}).use(_ => IO.never)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment