23. Play: the Scala you’ll inherit
Part IV has built a service the way I’d build one now. A Scala web application that has been running for ten years was probably built on the Play framework. In outline Play is close to Spring MVC: there’s a file of routes, a controller class with a method for each route and a dependency injection container that builds the controllers. Underneath it’s asynchronous, built on the Future type from Scala’s standard library.
In this chapter we rebuild two of chapter 19’s endpoints in Play 3, on top of the booking rules in core, so that you can find your way around a Play application when you’re handed one.
23.1. A Future has already started
A Play controller answers each request with a Future. A Future needs nothing from Play, so try one in a script first. Save this as futures.scala in a directory of its own and run it:
//> using scala 3.9.0
//> using jvm 25
import scala.concurrent.{Await, Future}
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration.*
@main def futures(): Unit =
val table = Future:
println("looking for a table")
6
Thread.sleep(100)
println("the Future has been made, and nothing has asked for its result")
val twice =
for
first <- table
second <- table
yield first + second
println(Await.result(twice, 1.second))
$ scala run futures.scala
looking for a table
the Future has been made, and nothing has asked for its result
12
Like IO.delay, Future takes a block of code, but the block doesn’t wait for anything to run it. Here the block ran as soon as the Future was made, on another thread. Its message is the first line of output, ahead of the one printed after the sleep. That thread came from an ExecutionContext, Scala’s name for a thread pool that futures run on. The import of global supplies a default one as a given.
The for then uses table twice, yet the message was printed once. A Future runs once and keeps its result, so flatMap on a finished one hands over the value it already has. An IO used twice in a for would have printed the message twice.
The retrying we wrote in chapter 15 took a program and ran it again if it failed, up to a number of attempts. Handed a Future, it could only read the same result again, so code that retries futures takes a function that makes a new Future on each call. A Future can’t be cancelled either, and a timeout on one stops the waiting while the work carries on. Exercise 4 has you swap a val holding a Future for a def and see how many times its block then runs.
The last line’s Await.result blocks the current thread until the Future has finished, so that the script doesn’t end first. A Play controller never needs to wait, because it hands its Future to the framework and returns.
23.2. The rules as a library
The Play application is a separate project that uses core as a library. It can’t be a fourth subproject, because the stable release of Play, 3.0, has an sbt plugin for sbt 1 and not yet for sbt 2. In the Fully Booked directory, publish core to a repository on your own machine. These are two of the lines sbt prints, with ~ standing for your home directory:
$ sbt core/publishLocal
[info] published core_3 to ~/.ivy2/local/com.fullybooked/core_3/0.1.0/jars/core_3.jar
[success] elapsed time: 2 s
The organisation and version at the top of build.sbt have been there since chapter 18. With the subproject’s name they make up what another build asks for: com.fullybooked, core and 0.1.0. The publishLocal task puts the library under ~/.ivy2/local, where only builds on this machine will find it. A team would normally publish to a repository that all of its builds can reach.
23.3. A Play project
Make a new directory called fully-booked-play beside the other one. Its build starts with project/build.properties, which asks for sbt 1:
sbt.version=1.13.1
Play’s plugin goes in project/plugins.sbt:
addSbtPlugin("org.playframework" % "sbt-plugin" % "3.0.12")
The build.sbt goes in the new directory itself:
name := "fully-booked-play"
scalaVersion := "3.9.0"
lazy val root = (project in file(".")).enablePlugins(PlayScala)
libraryDependencies ++= Seq(
guice,
"com.fullybooked" %% "core" % "0.1.0",
"org.scalatestplus.play" %% "scalatestplus-play" % "7.0.2" % Test
)
Test / javaOptions += "--sun-misc-unsafe-memory-access=allow"
The sbt command is the launcher you already have, which reads build.properties and starts sbt 1.13.1 for this directory. In build.sbt, project in file(".") makes the directory itself the project, the usual way to write a build with no subprojects. Turning on PlayScala brings in Play’s libraries, its directory layout and a run task of its own. The plugin also defines guice, its name for the dependency injection library Play uses. The line below it asks for the core we’ve just published. The last setting passes the JVM option from chapter 6 to the tests. From here on sbt prints Play’s banner before every command, which the output shown in this chapter leaves out.
Play has a directory layout of its own in place of Maven’s. Code goes under app, in packages named for what the classes are, such as controllers, models and services. Configuration and the routes go in conf, and tests in test. Create an empty file at conf/application.conf. Ours has nothing to set, but without the file Play answers every request with a configuration error. An application that’s been in production for years will probably have a long application.conf, in the format of the one we wrote for the http4s service.
23.4. Two endpoints
The JSON types go in app/models/views.scala:
package models
import fullybooked.{describe, Booking}
import play.api.libs.json.{Json, OFormat}
case class NewBooking(name: String, size: Int, time: String, phone: Option[String])
case class BookingView(name: String, size: Int, table: Int, time: String, status: String)
object NewBooking:
given OFormat[NewBooking] = Json.format[NewBooking]
object BookingView:
given OFormat[BookingView] = Json.format[BookingView]
def of(booking: Booking): BookingView =
BookingView(
booking.party.name,
booking.party.size,
booking.table.number,
booking.time.toString,
describe(booking.status)
)
These are chapter 19’s NewBooking and BookingView with Play’s own JSON library, play-json, behind them in place of circe. In chapter 19 a derives clause had circe write the code that turns a case class into JSON and back. Here Json.format writes it, also at compile time, as an OFormat. Each OFormat is a given in its class’s companion object, which is one of the places the compiler looks for givens.
The bookings are held by a class in app/services/BookingBook.scala:
package services
import fullybooked.{decide, Booking, BookingError, Party}
import java.time.LocalTime
import javax.inject.Singleton
import scala.concurrent.Future
@Singleton
class BookingBook:
private var bookings = List[Booking]()
def all: Future[List[Booking]] =
Future.successful(synchronized(bookings))
def reserve(party: Party, time: LocalTime): Future[Either[BookingError, Booking]] =
Future.successful:
synchronized:
decide(bookings, party, time).map: booking =>
bookings = bookings :+ booking
booking
As in chapter 17’s DirectBookings, the list is a var that’s only read or changed inside synchronized. Each answer is wrapped in Future.successful, which makes a Future that has already finished. In an application with a database the futures would come from the database library: Slick, which Play has a module for, returns a Future from every query it runs. I’ll come back to @Singleton once the application runs.
The controller is app/controllers/BookingController.scala:
package controllers
import fullybooked.{explain, validate, BookingError, BookingRequest}
import javax.inject.{Inject, Singleton}
import models.{BookingView, NewBooking}
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents, Result}
import scala.concurrent.{ExecutionContext, Future}
import services.BookingBook
@Singleton
class BookingController @Inject() (book: BookingBook, components: ControllerComponents)(using
ExecutionContext
) extends AbstractController(components):
def list() = Action.async:
book.all.map(bookings => Ok(Json.toJson(bookings.map(BookingView.of))))
def create() = Action.async(parse.json[NewBooking]): request =>
val asked = request.body
val asText =
BookingRequest(asked.name, asked.size.toString, asked.time, asked.phone.getOrElse(""))
validate(asText) match
case Left(errors) =>
Future.successful(BadRequest(Json.obj("problems" -> errors.toList.map(explain))))
case Right((party, time)) =>
book
.reserve(party, time)
.map:
case Right(booking) => Created(Json.toJson(BookingView.of(booking)))
case Left(error) => refused(error)
private def refused(error: BookingError): Result =
val problems = Json.obj("problems" -> List(explain(error)))
error match
case BookingError.NothingFree(_, _) | BookingError.NotAllowed(_, _) => Conflict(problems)
case BookingError.PartyTooLarge(_) | BookingError.KitchenClosed(_) |
BookingError.NameMissing | BookingError.BadPartySize(_) | BookingError.BadTime(_) |
BookingError.BadPhone(_) =>
BadRequest(problems)
Each public method of the controller returns an action, a function from a request to a Future of a result, and Action.async builds one from a block. The controller gets Action from AbstractController, along with parse and the functions that make results: Ok, Created, BadRequest and Conflict, named for their status codes. A result’s body here is JSON, made either by Json.toJson with the formats from views.scala or by Json.obj from pairs of names and values. I’ve left the return types off the two actions, as Play code usually does.
The create method goes through the steps of chapter 19’s create. It turns the NewBooking into a BookingRequest and calls validate from core. If that fails it answers 400 with the output of explain. When reserve turns a booking down, the refused method picks 409 or 400, as statusOf does in the http4s service. With parse.json[NewBooking], Play decodes the body before our block runs. The map near the end is on the Future that reserve returns, so its function runs on a thread from the ExecutionContext in the class’s using clause. That parameter has no name because nothing in the class refers to it, and map finds it as a given.
The routes go in conf/routes, one line for each request and the method that answers it:
GET /bookings controllers.BookingController.list()
POST /bookings controllers.BookingController.create()
23.5. Running it
Start Play with sbt run. Play listens on port 9000 in what it calls development mode, where nothing is compiled until the first request arrives:
$ curl localhost:9000/bookings
[]
$ curl -d '{"name":"Hughes","size":4,"time":"18:30"}' -H 'Content-Type: application/json' localhost:9000/bookings
{"name":"Hughes","size":4,"table":3,"time":"18:30","status":"confirmed"}
$ curl -d '{"name":"","size":4,"time":"7pm"}' -H 'Content-Type: application/json' -w '\n%{http_code}\n' localhost:9000/bookings
{"problems":["we need a name for the booking","'7pm' isn't a time, try 19:30"]}
400
Leave it running and change something in the controller. On the next request Play recompiles what changed and starts the application again, which also means a new, empty BookingBook. Then break the controller by misspelling book.all and open http://localhost:9000/bookings in a browser. The compile error is the response, on a page that shows the offending line. Put the spelling right afterwards and leave the server running. When it’s time to stop it, press Enter in sbt’s terminal.
A body that isn’t a NewBooking never reaches create, because Play answers it first, as Tapir did in chapter 19. This is the start of Play’s answer:
$ curl -s -d '{"name":"Tanaka","size":"eight","time":"20:00"}' -H 'Content-Type: application/json' localhost:9000/bookings | head -n 4
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bad Request</title>
The status is 400 and the body is a page of HTML, since Play’s default error handler is written for browsers. Play has a JSON one as well, chosen with play.http.errorHandler = play.api.http.JsonHttpErrorHandler in application.conf. For an API I’d set that on the first day.
Stop the server, change list() to listAll() in conf/routes and compile:
$ sbt compile
[error] conf/routes:1:1: value listAll is not a member of controllers.BookingController
[error] GET /bookings controllers.BookingController.listAll()
[error] one error found
[error] (Compile / compileIncremental) Compilation failed
Play turns the routes into Scala before the compiler runs, so a route to a method that doesn’t exist fails the build with the routes file’s own line number in the error. Put list() back.
23.6. Who calls the constructor
Guice makes the BookingController and hands it a BookingBook when the application starts. The @Inject() annotation marks the constructor that Guice should call. Guice finds a value for each parameter by its type: it builds the BookingBook itself, and Play provides the ControllerComponents and the ExecutionContext for the using clause. With @Singleton, there’s one BookingBook for the whole application, where Guice’s default is a new one for every place that wants it.
In chapter 19 bookingRoutes(bookings) got what it depended on as an argument, and the compiler checked that it was there. Guice does its wiring at run time, so a constructor parameter that it can’t supply still compiles and the application fails as it starts. It’s the reason I prefer plain arguments, though in a Play codebase injection is the convention and I follow it.
In Scala 2 the controller’s last parameter list reads (implicit ec: ExecutionContext), with implicit where Scala 3 has using.
23.7. Testing a controller
The last dependency in build.sbt, scalatestplus-play, has Play’s test helpers for ScalaTest, the framework we saw a sample of in chapter 6. Create test/controllers/BookingControllerSpec.scala:
package controllers
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.guice.GuiceOneAppPerTest
import play.api.libs.json.Json
import play.api.test.FakeRequest
import play.api.test.Helpers.*
class BookingControllerSpec extends PlaySpec with GuiceOneAppPerTest:
def booking(name: String, size: Int, time: String) =
FakeRequest(POST, "/bookings")
.withJsonBody(Json.obj("name" -> name, "size" -> size, "time" -> time))
"POST /bookings".should:
"book a table that can then be listed".in:
val created = route(app, booking("Hughes", 4, "18:30")).get
status(created).mustBe(CREATED)
val listed = route(app, FakeRequest(GET, "/bookings")).get
(contentAsJson(listed) \\ "name").map(_.as[String]).mustBe(Seq("Hughes"))
"refuse the second party after the last table".in:
status(route(app, booking("Mbeki", 8, "20:00")).get).mustBe(CREATED)
status(route(app, booking("Tanaka", 8, "20:00")).get).mustBe(CONFLICT)
"say what was wrong with a bad request".in:
val refused = route(app, booking("", 4, "7pm")).get
status(refused).mustBe(BAD_REQUEST)
(contentAsJson(refused) \ "problems").as[Seq[String]].size.mustBe(2)
$ sbt test
[info] BookingControllerSpec:
[info] POST /bookings
[info] - should book a table that can then be listed
[info] - should refuse the second party after the last table
[info] - should say what was wrong with a bad request
[info] Tests: succeeded 3, failed 0, canceled 0, ignored 0, pending 0
[info] All tests passed.
I’ve left out the log lines that Play prints between the test names. The suite extends PlaySpec, a ScalaTest suite with Play’s helpers added. Its other parent, GuiceOneAppPerTest, has Guice build a whole application before each test, so every test starts with an empty BookingBook. A test’s route(app, request) sends the request through the routes file to the controller without a network. Since a request might match no route, the result is an Option of a Future. Calling .get on it gives the Future, or throws if there was no route. Play’s status and contentAsJson wait for that Future. In the JSON, \ picks out a field and \\ collects every field of that name at any depth. The as method reads a piece of JSON as a Scala type.
I’ve written .should:, .in: and .mustBe with dots, to match the rest of the book. ScalaTest’s own documentation has them as bare words, as in status(created) mustBe CREATED, with braces around the blocks. An inherited codebase will probably use that style.
23.8. Working in a codebase you didn’t choose
A Play application that you’re given will probably be written in Scala 2, the subject of appendix A, with braces and implicit throughout. The application may also be on Play 2. Play 2.9 and 3.0 are the same framework, the first running on Akka and the second on Pekko, the open-source fork that was made after Akka’s licence changed in 2022. In the code, imports start with akka on Play 2 and with org.apache.pekko on Play 3.
You probably won’t be able to switch on chapter 18’s compiler options all at once. With -Wunused:all this application of two routes gets five warnings, every one of them in code that Play generated from the routes file. I’d still turn the warnings on and work through the ones in my own files before thinking about -Werror.
When one of these applications is slow, I look for blocking first. Play runs controllers on a small pool of threads that it expects never to wait. A JDBC call made inside a Future on that pool holds one of its threads for the length of the query. Cats Effect has IO.blocking for that problem, and Play’s answer is a second ExecutionContext kept for blocking work. I’d read the page on thread pools in its documentation before changing any database code.
With an inherited application I’d begin by moving the rules out of the controllers into plain functions with tests around them, and I’d leave the framework where it is. The functions in core were written that way, which is why a Play controller could call them unchanged. If you add Cats Effect code to such an application, it can be joined to the futures: unsafeToFuture() turns an IO into a Future, and IO.fromFuture goes the other way.
23.9. Exercises
Solutions to the first two are in the book’s downloadable code, under ch23/exercises.
-
Add
GET /bookings/:name, which answers with one booking or a 404. In the routes file a parameter is written/bookings/:nameand the method asfind(name: String).findBookingincoredoes the looking up, andNotFoundmakes the result. -
Add a test for it to
BookingControllerSpec: 200 for a name that has a booking and 404 for one that hasn’t. -
Give
BookingBooka constructor parameter whose type is a trait with no implementation, such astrait Clock, and put@Inject()before the parameter list, importingInjectbesideSingleton. Compile. Then run the tests and find Guice’s message in the output. -
In
futures.scala, changeval tabletodef table. Work out what it will print before running it.