WebSockets + Akka, on Scalatra
Bay Area Scalatra Hackers (BASH)
January 30, 2013
What is this group about?
Scalatra!
Scalatra + Spray?
Scala Web Development?
What do you think?
Is this the last BASH meetup?
I'm delighted to do the organizing.
But I'm not giving every talk!
-
Giving talks isn't all that hard.
- Step 1: Pick a topic you'd like to learn about.
- Step 2: Sign up for a talk one month out.
- Step 3: Learn about the topic when you have time.
- Step 4: Share your findings!
Where are we going?
I. Intro to Scalatra
II. Intro to WebSockets
III. Intro to Akka
IV. Mashup!
Some banter
-
Episode 22: Derek Wyatt on Akka Concurrency
-
Episode 24: Ivan Porto Carrero on Scalatra
-
Episodes 27-28: Mathias Doenitz on Spray
-
Episode 29: James Roper on Play!
/Advertisement
Warning
-
This is mostly a "concepts" talk. Very little code will be shown.
-
If you want particulars, ask!
Section I
Intro to Scalatra
Hello Scalatra
import org.scalatra._
class HelloScalatra extends ScalatraServlet {
get("/") {
"Hello, world!"
}
}
BEFORE I FORGET!
Use Scalatra version 2.2, currently in RC3.
-
-
Scalatra's philosophy: transparency
No magic!
It's elephants all the way down.
More a set of libraries than a "framework".
Source code is extremely readable.
Scalatra's philosophy: unobtrusiveness
Absolute minimum of configuration. Did you see hello world?
Not "opinionated".
No fancy build system.
Everything is modifiable via idiomatic Scala.
Integrations are all optional, and often independent.
Scalatra's philosophy: scalability
High performance out of the box.
Stateless by default. Sessions if you want them.
Async via Akka.
Scalatra's philosophy:
don't reinvent the wheel!
Servlet-based
Use the best of the ecosystem.
-
Implementation side: Atmosphere, Json4s, Akka, etc.
-
Application side: love thy InputStream
NIH isn't in the vocabulary.
The dark side of Scalatra ...
Routes parameters are not typed.
-
Core DSL is mutable. (The DSL is a Sinatra port, so go figure.)
-
Servlets
- Not as asynchronous as Netty until Servlet 3.5
- Some people really hate servlet containers. Why?!
-
Generally can't penetrate the Servlet API without bring in classes specific to
your container.
- Not Scala elephants all the way down. (See spray-io.)
Section II
Intro to WebSockets
HTTP history
-
HTTP/1 only has simple request-response.
-
HTTP/1.1
-
Persistent connections
-
HTTP pipelining
-
Comet
-
SPDY (working draft of HTTP/2.0)
-
Multiplexing
-
Prioritization
-
Full compression
What are WebSockets?
-
WebSocket is a web technology providing full-duplex communications channels
over a single TCP connection.
-
WebSockets is an independent TCP/IP protocol not based on HTTP.
-
Clients can be web browsers or servers.
Browser support
-
Firefox >= v6
-
Chrome >= v14
-
Internet Explorer >= v10
-
Opera >= v12.10
-
Yes, web browsers briefly disabled WebSockets last year, but that's over now.
-
Safari not re-enabled yet
-
Not much mobile support yet
HTTP handshake
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Advantages of WebSockets
-
Communication is over port 80
-
Proxy traversal
-
Full-duplex communication
- That includes "browser push" and many other models.
-
Between connection & disconnection the parties send arbitrary messages at
arbitrary times.
-
Reduced latency & overhead, improved scalability, compared to Comet (reverse AJAX).
-
Simpler implementation than Comet.
Disadvantages of WebSockets
-
Client support isn't all there.
-
May encourage stateful design.
-
Lower level
-
Unfamiliar
What is Akka?
-
Concurrency framework
-
Increasingly integrated with Scala standard library
-
Supports many styles of concurrency
Actors
Futures
Agents
Dataflow
STM from Scala
Actors in one slide
Actors are objects that ...
-
define a method for handling messages of any type.
-
have a first-in-first-out mailbox of messages.
-
send messages to other actors asynchronously.
-
can safely maintain mutable state.
-
don't need to worry about thread scheduling, message routing, or locking.
Sound familiar?
-
Like the client & host on a socket connection, actors send
messages whenever they wish.
-
Scalatra uses Akka to make sure socket messages are processed asynchronously.
-
Biggest difference: actors must handle messages in order.
That does not mean that the "reply" comes in the same order, like pipelining.
What Akka looks like
class MyActor extends Actor {
var count = 0
def receive = {
case "hi" => sender ! "and hello to you"
case Inc =>
count += 1
sender ! count
case quotesRequest: GetStockQuotes =>
actorOf[StockChecker] ! (quotesRequest, sender)
}
}
val ref: ActorRef = actorOf[MyActor]
val res: Future[Any] = ref ? Inc
res foreach println
Atmosphere
-
Written by Jeanfrancois Arcand of GlassFish & async-http-client fame.
-
Provides automatic fallback from WebSockets to other transports.
OMFG!
-
Java server implementation, Javascript client implementation.
-
async-http-client provides a Java client.
-
Comes with implementations of high-level patterns.
-
Integration with Swagger.
Scalatra's Atmosphere integration
class ChatController extends ScalatraServlet
with JValueResult with JacksonJsonSupport //let's use json!
with SessionSupport with AtmosphereSupport { //let's use atmosphere!
atmosphere("/the-chat") {
new AtmosphereClient {
def receive = { //this is a *partial* function, just like Akka
case Connected =>
broadcast(
("author" -> "Someone") ~
("message" -> "joined the room"))
send("welcome!")
case Disconnected(ClientDisconnected, cause) =>
case Disconnected(ServerDisconnected, cause) =>
case TextMessage(str) =>
case JsonMessage(json) =>
case BinaryMessage(array) =>
}
}
}
My opinion
-
Scalatra is a full-featured web framework that is easy for beginners, but lets
power users be power users.
Atmosphere is its killer app.
If you don't need "full-featured" then Spray is seriously hot.
←
→
/
#