SlideShare une entreprise Scribd logo
1  sur  32
Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded.
From world
to
The task:
Backend for real-time
communication app
Why Ruby?
2011
Elegant language &
environment
1. Beautiful Language: Dynamic, OO, linear
##
# Distribute a system message
#
def find_and_distribute(message_id)
message = Message.find(message_id)
raise SystemError, "Message not found" if message.nil?
message.start_distribution
return message.to_json
rescue SystemError
log.error "[API] distribute fail: "#{e.message}”
end
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
Elegant language &
environment
class MediaRobotUser
include Mongoid::Document
# schema
field :rss_url, type: String
field :updated, type: DateTime
field :update_freq, type: Integer, default: 5
# Validations
validates :rss_url, :presence => true
validates :update_freq, :presence => true
def activate_user
robot_queue = ”robot_update_#{self.id.to_s}"
Resque.remove_schedule(robot_queue)
schedule_options =
{ 'every' => '15m',
'custom_job_class' => “Bot::Jobs::UpdateMediaRobot",
'queue' => :update_media_robot,
'args' => self.id.to_s,
}
Resque.set_schedule(robot_queue, schedule_options)
end
end # class MediaRobotUser
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
3. Robust libraries: Community focus on libs selected for Rails
Elegant language &
environment
1. Beautiful Language: Dynamic, OO, linear
2. Super ORM/ODM: ActiveRecord & Mongoid
3. Robust libraries: Rails gives focus on library development
4. Killer server stack for API: Thin + Rack + Sinatra
Elegant language &
environment
Dedicated async web server for Ruby apps
Instead of complex Apache/Passenger setup, you
download thin and just run your app with it.
Layer between web servers and web frameworks
De facto standard in Ruby world: choose any ruby
web server, choose any ruby framework, throw
own middleware into soup and it just works!
Simple HTTP request handler on top of Rack
No MVC bloat for a simple, RESTful API
application, but want still use same robust libraries
Rails apps use. Just write functionality for your
GET /my/api endpoint and go!
# Set Rails session to OAuth2 access token convert middleware
use Auth::RailsSessionConverter
# Set OAuth2 handler
use Rack::OAuth2::Server
# launch Sinatra REST API server
require File.dirname(__FILE__) + '/app/access/restapi'
map('/rest/vp5/') { run Access::RESTAPI }
2. Define Rack configuration (e.g. myrack.ru):
3. Run web server:
1. Write Sinatra web app:
##
# API call to get backend version.
#
get '/system/version' do
authenticate!('int_api_user')
content_type :json
status 200
return (JSON :data_api_version => 'proto v5.0')
end
$ bundle exec thin –R myrack.ru –p 9400 -e development start
Ruby ≠ Rails! Sinatra,
Resque and many other
cool frameworks
Could map
other apps to
different paths
“homemade”
middleware block
hooked in!
No fuzz
The next task:
Backend for Media App
2013
So.. Let’s think about
Culture for
unsecure
code?
Born in
2011 – are
the libs
there?
Don’t want
that callback
spaghetti!
DB drivers
and
ODMs?Performance
?
How to keep
running in
production?
/**
* Static content delivery
*/
staticDelivery: function (req, res) {
var tmpDir = lzconf.filedbdir + "/tmp";
file.mkdir(tmpDir, '777’, function() {
var fileSource = lzconf.filedbdir + "/" + req.params[0];
// do the work
easyimg.rescrop(options, function(err, image) {
console.log('Resized and cropped: ', image);
// send file
res.sendfile(tmpTarget, {maxAge: 604800}, function(err) {
if (err) { … }
// remove temp file
fs.unlink(tmpTarget, function(err, success) {
…
});
});
});
});
}
function myApiFunc(callback)
{
/*
* This pattern does NOT work!
*/
try {
doSomeAsynchronousOperation(function (err) {
if (err)
throw (err);
/* continue as normal */
});
} catch (ex) {
callback(ex);
}
}
Source: http://www.joyent.com/developers/node/design/errors
Whaaat?
Cannot use
try…catch??
“Sadly, that seems to be the story of
Node.JS and the frameworks that use it.
Derby, Meteor, SocketStream– they all are
relatively new and immature, and in some
cases, lack critical functionality of a web
framework or have serious issues with
security. That sort of puts me, as a
developer, in an odd position. I’ve
determined Node.JS is a good platform for a
project, but without reinventing the wheel,
what framework do I use to speed up
development?”
– Andrew Munsell
https://www.andrewmunsell.com/blog/the-odd-
state-of-nodejs-and-its-frameworks
“Sinatra inspired web development
framework for node.js – insanely fast,
flexible, and simple.”
Yes!
Powered by Connect
More over,
future looked
promising:
“Next generation web framework
for node js.”
Why it rocks
ECMAScript 6: Generators
$ node --harmony
> function* giveMeFruit() {
... yield "apple";
... yield "banana";
... }
> var fruitMachine = giveMeFruit()
> fruitMachine.next()
{ value: 'apple', done: false }
> fruitMachine.next()
{ value: 'banana', done: false }
> fruitMachine.next()
{ value: undefined, done: true }
> fruitMachine.next()
Error: Generator has already finished
at GeneratorFunctionPrototype.next (native)
…
What an earth
this has to do
with a HTTP
framework?
Why it rocks
co– “The ultimate generator based flow-
control goodness for nodejs (supports thunks,
promises, etc)”
var co = require('co');
co(function *(){
console.log(“updating user...”);
try {
var user = yield Users.findOneById(‘123’).exec();
if (!user) throw new Error(“Cannot find user”);
user.name = “juha”;
yield Promise.promisify(user.save, user)();
} catch (err) {
console.log(“Name update failed: ”, err);
}
})()
This Mongoose
finder returns a
promise by default
“Save” need to be
transferred into
promise first for
yield
Try…catch as it
should be 
Generator flow control (co)
is the heart of Koa server
Why it rocks
var koa = require('koa’)
, api = require('./v1/myApiModule’), ...
app.use(mount(‘/api/v1’, api));
app.listen(8080);
Why it rocks
Additional middleware to
handle routing, e.g. koa-
mount
Custom middleware
upstream &
downstream
app.use(function *(next) {
var start = new Date;
yield next;
var ms = new Date - start;
this.set('X-Response-Time', ms + 'ms');
});
Many needed middleware
libs already ported, such as
* koa-session-mongo
* koa-passport
* koa-cors
* koa-send
app.use(session());
app.use(passport.username());
app.use(function *(next) {
try {
yield next;
} catch (err) {
this.status = err.status || 500;
}
})
More robust code
API
with koa-router
Why it rocks
var Router = require('koa-router')
var API = new Router()
API.get('/topics/:topicId', function *() {
try {
this.body = yield MySubSystem.getTopic({
id: this.params.topicId,
filter: this.request.query.filter_by
});
} catch (err) {
if (err.name === "DocumentNotFoundError") {
this.body = "Topic not found";
this.status = 404;
} else {
throw err;
}
}
}
Why it rocks
Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded.
Thank you!

Contenu connexe

Tendances

Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.ioArnout Kazemier
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyLaunchAny
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJSAlmog Baku
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswanivvaswani
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSAntonio Peric-Mazar
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史Shengyou Fan
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and othersYusuke Wada
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with ExpressAaron Stannard
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframeworkInviqa
 

Tendances (20)

Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
Build REST API clients for AngularJS
Build REST API clients for AngularJSBuild REST API clients for AngularJS
Build REST API clients for AngularJS
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Building Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJSBuilding Single Page Application (SPA) with Symfony2 and AngularJS
Building Single Page Application (SPA) with Symfony2 and AngularJS
 
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
[PHP 也有 Day] 垃圾留言守城記 - 用 Laravel 阻擋 SPAM 留言的奮鬥史
 
Inside Bokete: Web Application with Mojolicious and others
Inside Bokete:  Web Application with Mojolicious and othersInside Bokete:  Web Application with Mojolicious and others
Inside Bokete: Web Application with Mojolicious and others
 
Md+wiki
Md+wikiMd+wiki
Md+wiki
 
Building Web Apps with Express
Building Web Apps with ExpressBuilding Web Apps with Express
Building Web Apps with Express
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
Express js
Express jsExpress js
Express js
 
Intro to Node
Intro to NodeIntro to Node
Intro to Node
 
Silex, the microframework
Silex, the microframeworkSilex, the microframework
Silex, the microframework
 
Express node js
Express node jsExpress node js
Express node js
 
Socket.io
Socket.ioSocket.io
Socket.io
 
REST API Laravel
REST API LaravelREST API Laravel
REST API Laravel
 
Developing apps using Perl
Developing apps using PerlDeveloping apps using Perl
Developing apps using Perl
 

Similaire à Where little posts make a mighty magazine

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developerEdureka!
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperEdureka!
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.Mike Brevoort
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express Jeetendra singh
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyUlrich Krause
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsVikash Singh
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsMarcelo Pinheiro
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0Thomas Chacko
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationBen Hall
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React NativeIan Wang
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with ExamplesGabriele Lana
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Sunny Gupta
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails DevsDiacode
 

Similaire à Where little posts make a mighty magazine (20)

soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Proposal
ProposalProposal
Proposal
 
Day in a life of a node.js developer
Day in a life of a node.js developerDay in a life of a node.js developer
Day in a life of a node.js developer
 
Day In A Life Of A Node.js Developer
Day In A Life Of A Node.js DeveloperDay In A Life Of A Node.js Developer
Day In A Life Of A Node.js Developer
 
Node.js - async for the rest of us.
Node.js - async for the rest of us.Node.js - async for the rest of us.
Node.js - async for the rest of us.
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
RESTful API In Node Js using Express
RESTful API In Node Js using Express RESTful API In Node Js using Express
RESTful API In Node Js using Express
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Electron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easyElectron - cross platform desktop applications made easy
Electron - cross platform desktop applications made easy
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js vs Play Framework
Node.js vs Play FrameworkNode.js vs Play Framework
Node.js vs Play Framework
 
Porting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability SystemsPorting Rails Apps to High Availability Systems
Porting Rails Apps to High Availability Systems
 
Docker serverless v1.0
Docker serverless v1.0Docker serverless v1.0
Docker serverless v1.0
 
Intro to PSGI and Plack
Intro to PSGI and PlackIntro to PSGI and Plack
Intro to PSGI and Plack
 
Real World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS ApplicationReal World Lessons on the Pain Points of Node.JS Application
Real World Lessons on the Pain Points of Node.JS Application
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React Native
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02Nodejsexplained 101116115055-phpapp02
Nodejsexplained 101116115055-phpapp02
 
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
MongoDB World 2018: Tutorial - Got Dibs? Building a Real-Time Bidding App wit...
 
Phoenix for Rails Devs
Phoenix for Rails DevsPhoenix for Rails Devs
Phoenix for Rails Devs
 

Dernier

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Dernier (20)

How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Where little posts make a mighty magazine

  • 1. Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded. From world to
  • 2. The task: Backend for real-time communication app
  • 5. Elegant language & environment 1. Beautiful Language: Dynamic, OO, linear
  • 6. ## # Distribute a system message # def find_and_distribute(message_id) message = Message.find(message_id) raise SystemError, "Message not found" if message.nil? message.start_distribution return message.to_json rescue SystemError log.error "[API] distribute fail: "#{e.message}” end
  • 7. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid Elegant language & environment
  • 8. class MediaRobotUser include Mongoid::Document # schema field :rss_url, type: String field :updated, type: DateTime field :update_freq, type: Integer, default: 5 # Validations validates :rss_url, :presence => true validates :update_freq, :presence => true def activate_user robot_queue = ”robot_update_#{self.id.to_s}" Resque.remove_schedule(robot_queue) schedule_options = { 'every' => '15m', 'custom_job_class' => “Bot::Jobs::UpdateMediaRobot", 'queue' => :update_media_robot, 'args' => self.id.to_s, } Resque.set_schedule(robot_queue, schedule_options) end end # class MediaRobotUser
  • 9. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid 3. Robust libraries: Community focus on libs selected for Rails Elegant language & environment
  • 10.
  • 11. 1. Beautiful Language: Dynamic, OO, linear 2. Super ORM/ODM: ActiveRecord & Mongoid 3. Robust libraries: Rails gives focus on library development 4. Killer server stack for API: Thin + Rack + Sinatra Elegant language & environment
  • 12. Dedicated async web server for Ruby apps Instead of complex Apache/Passenger setup, you download thin and just run your app with it. Layer between web servers and web frameworks De facto standard in Ruby world: choose any ruby web server, choose any ruby framework, throw own middleware into soup and it just works! Simple HTTP request handler on top of Rack No MVC bloat for a simple, RESTful API application, but want still use same robust libraries Rails apps use. Just write functionality for your GET /my/api endpoint and go!
  • 13. # Set Rails session to OAuth2 access token convert middleware use Auth::RailsSessionConverter # Set OAuth2 handler use Rack::OAuth2::Server # launch Sinatra REST API server require File.dirname(__FILE__) + '/app/access/restapi' map('/rest/vp5/') { run Access::RESTAPI } 2. Define Rack configuration (e.g. myrack.ru): 3. Run web server: 1. Write Sinatra web app: ## # API call to get backend version. # get '/system/version' do authenticate!('int_api_user') content_type :json status 200 return (JSON :data_api_version => 'proto v5.0') end $ bundle exec thin –R myrack.ru –p 9400 -e development start Ruby ≠ Rails! Sinatra, Resque and many other cool frameworks Could map other apps to different paths “homemade” middleware block hooked in! No fuzz
  • 14. The next task: Backend for Media App
  • 15. 2013
  • 16. So.. Let’s think about Culture for unsecure code? Born in 2011 – are the libs there? Don’t want that callback spaghetti! DB drivers and ODMs?Performance ? How to keep running in production?
  • 17. /** * Static content delivery */ staticDelivery: function (req, res) { var tmpDir = lzconf.filedbdir + "/tmp"; file.mkdir(tmpDir, '777’, function() { var fileSource = lzconf.filedbdir + "/" + req.params[0]; // do the work easyimg.rescrop(options, function(err, image) { console.log('Resized and cropped: ', image); // send file res.sendfile(tmpTarget, {maxAge: 604800}, function(err) { if (err) { … } // remove temp file fs.unlink(tmpTarget, function(err, success) { … }); }); }); }); }
  • 18. function myApiFunc(callback) { /* * This pattern does NOT work! */ try { doSomeAsynchronousOperation(function (err) { if (err) throw (err); /* continue as normal */ }); } catch (ex) { callback(ex); } } Source: http://www.joyent.com/developers/node/design/errors Whaaat? Cannot use try…catch??
  • 19. “Sadly, that seems to be the story of Node.JS and the frameworks that use it. Derby, Meteor, SocketStream– they all are relatively new and immature, and in some cases, lack critical functionality of a web framework or have serious issues with security. That sort of puts me, as a developer, in an odd position. I’ve determined Node.JS is a good platform for a project, but without reinventing the wheel, what framework do I use to speed up development?” – Andrew Munsell https://www.andrewmunsell.com/blog/the-odd- state-of-nodejs-and-its-frameworks
  • 20.
  • 21. “Sinatra inspired web development framework for node.js – insanely fast, flexible, and simple.” Yes! Powered by Connect
  • 23. “Next generation web framework for node js.”
  • 24. Why it rocks ECMAScript 6: Generators $ node --harmony > function* giveMeFruit() { ... yield "apple"; ... yield "banana"; ... } > var fruitMachine = giveMeFruit() > fruitMachine.next() { value: 'apple', done: false } > fruitMachine.next() { value: 'banana', done: false } > fruitMachine.next() { value: undefined, done: true } > fruitMachine.next() Error: Generator has already finished at GeneratorFunctionPrototype.next (native) … What an earth this has to do with a HTTP framework?
  • 25. Why it rocks co– “The ultimate generator based flow- control goodness for nodejs (supports thunks, promises, etc)” var co = require('co'); co(function *(){ console.log(“updating user...”); try { var user = yield Users.findOneById(‘123’).exec(); if (!user) throw new Error(“Cannot find user”); user.name = “juha”; yield Promise.promisify(user.save, user)(); } catch (err) { console.log(“Name update failed: ”, err); } })() This Mongoose finder returns a promise by default “Save” need to be transferred into promise first for yield Try…catch as it should be 
  • 26. Generator flow control (co) is the heart of Koa server Why it rocks
  • 27. var koa = require('koa’) , api = require('./v1/myApiModule’), ... app.use(mount(‘/api/v1’, api)); app.listen(8080); Why it rocks Additional middleware to handle routing, e.g. koa- mount Custom middleware upstream & downstream app.use(function *(next) { var start = new Date; yield next; var ms = new Date - start; this.set('X-Response-Time', ms + 'ms'); }); Many needed middleware libs already ported, such as * koa-session-mongo * koa-passport * koa-cors * koa-send app.use(session()); app.use(passport.username()); app.use(function *(next) { try { yield next; } catch (err) { this.status = err.status || 500; } }) More robust code
  • 29. var Router = require('koa-router') var API = new Router() API.get('/topics/:topicId', function *() { try { this.body = yield MySubSystem.getTopic({ id: this.params.topicId, filter: this.request.query.filter_by }); } catch (err) { if (err.name === "DocumentNotFoundError") { this.body = "Topic not found"; this.status = 404; } else { throw err; } } } Why it rocks
  • 30.
  • 31.
  • 32. Where little posts make a mighty magazine. Where readers become editors. Where giving inspiration is rewarded. Thank you!

Notes de l'éditeur

  1. From Ruby world to Node.js
  2. CMSs are not for realtime system Java felt more for enterprise level solution PHP language felt outdated and did not found suitable stack Rails MVC felt too heavy for API server purpose Pure Ruby with dedicated servers and framework was the choice
  3. Javascript famous for silently ignoring problems. Initially people did not handle CSRF. Sometimes neglected exception catching. Quickly written libs. No use of reverse proxy for caching and load balancing is needed.