Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Fast, testable, Scala HTTP services built on Twitter-Server and Finagle
Scala Java Python Other

Add optional 'name' parameter to routes

Problem:
Currently RouteInfo can only give you information about a
routes Controller and Http method. This means, for instance,
that stats are scoped only by these two values. If you do
not follow best practices of one resources per controller, this
leads to overlapping stats names, making stats mostly useless.

Motivation:
Better granularity for stats and other potential uses of
RouteInfo.

Solution:
When defining routes in a controller, you can now pass an
optional 'name' parameter which should uniquely describe the
route. If passed, this will be used instead of the controller
name in the stats name. Also, if no name is passed, rather than
the controller name, a sanitized version of the path string will
be used. The sanitation converts all / to _ and strips out
any other non alphanumeric characters (except _ ).

Result:
Fewer name collisions in stat names and the opportunity to give
each route a unique and relevant name. More useful RouteInfo for
other potential uses.

RB_ID=713926
latest commit 71d9c4f7b3
@nhnFreespirit nhnFreespirit authored jenkins committed
Failed to load latest commit information.
benchmarks move birdage/3rdparty/BUILD targets in their own 3rdparty/jvm dir; up…
examples Fix Finatra build.sbt to create leaf-node project assemblies correctl…
http Add optional 'name' parameter to routes
httpclient Deprecate HttpAssertions in favor of HttpWarmup. Update HttpClient to…
inject finatra/inject: ThriftClientModule - keep StackClient.defaultParams
jackson Rename finatra/logback to finatra/slf4j and remove the logback depend…
project Finatra - added and updated documentation.
slf4j finatra/slf4j: Slf4jBridgeModule filename should match class
utils Remove deprecated HttpAssertions from Finatra.
.gitignore Move finatra/examples code to be based on unpublished source for sbt …
.travis.yml Update .travis.yml
ADOPTERS.md Add and update files for open-repository
CHANGELOG.md Update Finatra to version 2.0.0.M3-SNAPSHOT
CONTRIBUTING.md Updated documentation and pushpatches to use master branch.
LICENSE Add and update files for open-repository
README.md Fix Finatra build.sbt to create leaf-node project assemblies correctl…
build.sbt Update dependency versions for finagle, util and twitter-server to mo…
finatra_logo.jpg Add and update files for open-repository
finatra_logo.png Added transparent logo and updated README.md
sbt Fix sbt jar retrieval

README.md

Finatra

Fast, testable Scala services inspired by Sinatra and powered by twitter-server.

finatra logo

Build Status Coverage Status

Maven Central

Gitter

Announcing the next milestone release of Finatra version 2!

Finatra v2 slides from SFScala meetup

Documentation for prior versions can be found here.

Features

  • Production use as Twitter’s HTTP framework
  • ~50 times faster than v1.6 in several benchmarks
  • Powerful feature and integration test support
  • JSR-330 Dependency Injection using Google Guice
  • Jackson based JSON parsing supporting required fields, default values, and custom validations
  • Logback MDC integration with com.twitter.util.Local for contextual logging across futures
  • Guice request scope integration with Futures

Quick Start

To get started we'll focus on building an HTTP API for posting and getting tweets:

Domain

case class PostedTweet(
  @Size(min = 1, max = 140) message: String,
  location: Option[Location],
  sensitive: Boolean = false) {

case class GetTweet(
  @RouteParam id: StatusId)

Then, let's create a Controller:

Controller

@Singleton
class TweetsController @Inject()(
  tweetsService: TweetsService)
  extends Controller {

  post("/tweet") { postedTweet: PostedTweet =>
    tweetsService.save(postedTweet) map { savedTweet =>
      response
        .created(savedTweet)
        .location(savedTweet.id)
    }
  }

  get("/tweet/:id") { request: GetTweet =>
    tweetsService.get(request.id)
  }
}

Next, let's create a server:

Server

class TwitterCloneServer extends HttpServer {

  override val modules = Seq(FirebaseHttpClientModule)

  override def configureHttp(router: HttpRouter): Unit = {
    router
      .register[StatusMessageBodyWriter]
      .filter[CommonFilters]
      .add[TweetsController]
  }
}

And finally, we can write a Feature Test:

Feature Test

class TwitterCloneFeatureTest extends FeatureTest with Mockito {

  override val server = new EmbeddedHttpServer(
    twitterServer = new TwitterCloneServer {
      override val overrideModules = Seq(integrationTestModule)
    })

  @Bind val firebaseClient = smartMock[FirebaseClient]

  @Bind val idService = smartMock[IdService]

  "tweet creation" in {
    //Setup mocks
    idService.getId returns Future(StatusId("123"))

    val mockStatus = Status(
      id = StatusId("123"),
      text = "Hello #SFScala",
      lat = Some(37.7821120598956),
      long = Some(-122.400612831116),
      sensitive = false)

    firebaseClient.put("/statuses/123.json", mockStatus) returns Future.Unit
    firebaseClient.get("/statuses/123.json")(manifest[Status]) returns Future(Option(mockStatus))

    //Assert tweet post
    val result = server.httpPost(
      path = "/tweet",
      postBody = """
        {
          "message": "Hello #SFScala",
          "location": {
            "lat": "37.7821120598956",
            "long": "-122.400612831116"
          },
          "sensitive": false
        }""",
      andExpect = Created,
      withJsonBody = """
        {
          "id": "123",
          "message": "Hello #SFScala",
          "location": {
            "lat": "37.7821120598956",
            "long": "-122.400612831116"
          },
          "sensitive": false
        }""")

    //Assert tweet get
    server.httpGet(
      path = result.location.get,
      andExpect = Ok,
      withJsonBody = result.contentString)
  }

  "Post bad tweet" in {
    server.httpPost(
      path = "/tweet",
      postBody = """
        {
          "message": "",
          "location": {
            "lat": "9999"
          },
          "sensitive": "abc"
        }""",
      andExpect = BadRequest,
      withJsonBody = """
        {
          "errors" : [
            "message size [0] is not between 1 and 140",
            "location.lat [9999.0] is not between -85 and 85",
            "location.long is a required field",
            "sensitive's value 'abc' is not a valid boolean"
          ]
        }
        """)
  }
}

Libraries

We are publishing Scala 2.10 and 2.11 compatible libraries to Maven central. The Finatra project is currently split up into multiple components: (Twitter Inject and Finatra libraries).

Twitter Inject (com.twitter.inject)

Inject provides libraries for integrating twitter-server and util-app with Google Guice.

Detailed documentation

Finatra (com.twitter.finatra)

Finatra is a framework for easily building API services on top of Twitter’s Scala stack (twitter-server, finagle, twitter/util)

Detailed documentation

Examples

You can run the examples in finatra/examples using sbt, e.g., to run the finatra/examples/finatra-hello-world example,

$ sbt helloWorld/run

Or you can create an assembly and run the assembly,

$ sbt helloWorld/assembly
...
$ java -jar examples/finatra-hello-world/target/scala-2.11/finatra-hello-world-assembly-2.0.0.M3-SNAPSHOT.jar -http.port=:8888 -admin.port=:9990

Authors

A full list of contributors can be found on GitHub.

Follow @finatra on Twitter for updates.

License

Copyright 2015 Twitter, Inc.

Licensed under the Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0

Something went wrong with that request. Please try again.