Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
A few Picard fixes now reintegrated in dantebronto/picard .
JavaScript Ruby
Tree: d4ab27cf9e

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
picard/lib
sample_app
sinatra_app_for_benchmarks
README.textile

README.textile

Picard: A Micro-framework for node.js

If you want to check it out, install Node and start the sample app with `node app.js`. There are no other dependencies.

Picard uses Haml thanks to creationix’s haml-js project.

A sample application:

  require('./config/env')

  get('/', function(){
    return { text: 'Hello Universe' }
  })

  get('/haml', function(){
    return {
      template: 'index',
      print_date: function () {
        return (new Date()).toDateString();
      },
      current_user: {
        name: "Jean-Luc Picard",
        bio: "Captain of the USS Enterprise"
      }
    }
  })

  var commands = [ 
    { command: 'Make it so' }, 
    { command: 'You have the bridge, Number One' } 
  ]

  get('/json', function(){
    return {
      type: 'application/json',
      body: JSON.stringify(commands)
    }
  })

  get('/partial', function(){
    return { 
      template: 'partial_test', 
      layout: 'application',
      commands: commands
    }
  })

  get('/redirect/?', function(request){
    // the '?' at the end of the route 
    // makes the trailing slash optional
    return request.redirect('/haml')
  })

  post('/order', function(){
    return { text: 'Tea, Earl Grey, Hot' }
  })

  put('/weapon/:id', function(params){
    return { text: '<p>Phaser with id #' + params.id + ' set to stun</p>' }
  })

  del('/fire/:number', function(params){  
    var text = '<p>Borg cube destroyed using ' + params.number + ' photon torpedoes</p>'

    if (  Number(params.number) > 12 )
      text = '<h1>Maximum yield, full spread!</h1>'

    return { text: text }
  })

  get(/\/regex\/(.*)\/(.*)/, function(params){
    return { text: params.captures[0] + ' ' + params.captures[1] }
  })

  get(/\/selective\/(\d+)/, function(params){ // must be a number
    return { text: params.captures[0] }
  })

  get('/cookie', function(request){
    
    // a simple key-value cookie
    request.cookie('hobby', 'literature')

    // cookie with all options
    var expires=new Date()
    expires.setDate(expires.getDate() + 30)

    request.cookie('user', 'LCDR Data', { 
      domain: '.your_domain.org', 
      path: '/cookie', 
      expires: expires, 
      secure: true 
    })

    // will render 'literature'
    return { text: '<h1>' + request.cookie('hobby').value + '</h1>' }
  })

  // Below we make a GET request to /haml (to simulate an http service call).
  // Rather than block other processing while waiting for a response,
  // we attach event listeners to the request without returning a value from our callback.
  // Only when the GET has returned do we render the result via the 'on_screen' method.

  get('/async_example', function(params){

    // This could easily be a call to CouchDB or other service
    var local = require('http').createClient(9900, "localhost")
    var request = local.get("/haml", { "host": "localhost" })

    request.finish(function(response) {
      var body = ''

      response.addListener('body', function (chunk) {
        body += chunk
      })

      // Here we call on_screen manually when the request is complete.
      // We can pass the normal scope object with body, status, template, etc.
      response.addListener('complete', function(){
        params.on_screen({ body: body })
      })
    })
  })

  // You can also use helper functions for logic that is shared across routes.
  // Every Picard callback function gets called with a request/environment 
  // variable as the single argument. Here we pass this object to our helper 
  // function for evaluation:

  var authorized = function(request){
    return (request.parsed_url().pathname == '/holodeck') // very simple example
  }

  get('/holodeck', function(request){
    if(authorized(request))
      return 'Welcome'
    else
      return request.redirect('/')
  })

See the sample app for more examples.

Benchmarks

The included sinatra_app_for_benchmarks is a Ruby port of the Picard sample_app. According to these benchmarks, the Picard app on node.js runs about twice as fast as the Sinatra app on Thin and can handle around 10x as many requests per second for some routes (due to the asynchronous nature of node.js). Below is a sample output of the benchmarks:

  $ cd sinatra_app_for_benchmarks
  $ ruby benchmark.rb

  Running Sinatra specs 10 times:

  Finished in 0.083148 seconds
  Finished in 0.083371 seconds
  Finished in 0.112633 seconds
  Finished in 0.083442 seconds
  Finished in 0.083424 seconds
  Finished in 0.082644 seconds
  Finished in 0.083286 seconds
  Finished in 0.084136 seconds
  Finished in 0.113771 seconds
  Finished in 0.08323 seconds
  Average time was 0.0893085 seconds

  Running Picard specs 10 times:

  Finished in 0.040487 seconds
  Finished in 0.040587 seconds
  Finished in 0.041176 seconds
  Finished in 0.042727 seconds
  Finished in 0.04083 seconds
  Finished in 0.040875 seconds
  Finished in 0.040128 seconds
  Finished in 0.039876 seconds
  Finished in 0.040797 seconds
  Finished in 0.041551 seconds
  Average time was 0.0409034 seconds

  Picard was 2.18 times faster!

Apache Benchmark Test for Sinatra app:

  $ ab -n 5000 -c 50 http://127.0.0.1:3000/haml
  
  ...
  
  Server Software:        thin
  Server Hostname:        127.0.0.1
  Server Port:            3000
  Document Path:          /haml
  Requests per second:    95.83 [#/sec] (mean)
  Time per request:       521.740 [ms] (mean)
  Time per request:       10.435 [ms] (mean, across all concurrent requests)

Apache Benchmark Test for Picard app:

  $ ab -n 5000 -c 50 http://127.0.0.1:9900/haml
  
  ...
  
  Server Software:        Picard
  Server Hostname:        127.0.0.1
  Server Port:            9900
  Document Path:          /haml
  Requests per second:    988.58 [#/sec] (mean)
  Time per request:       50.578 [ms] (mean)
  Time per request:       1.012 [ms] (mean, across all concurrent requests)
  

988.58 requests per second for Picard verses 95.83 for Sinatra!

Specs: MacBook Pro 2 × 2.53 GHz, 4 GB RAM, Ruby v1.8.7 on Thin 1.2.5, node.js v0.1.18

Note: The Sinatra app is not event driven, so to be fair I should really be testing Picard verses Sinatra + EventMachine. However, this illustrates the fact that node.js is evented out of the box, and obviates the need for separate libraries like EventMachine.

License

Copyright © 2009 Kellen Presley

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Something went wrong with that request. Please try again.