SlideShare a Scribd company logo
1 of 37
Taming client-server
communication
Scott Andrews
About me
• engineer @ SpringSource / Pivotal
• contributor to cujoJS
• drifter
• application framework
• open source commercial
• client server
• front-end back-end
A brief word from my sponsor
• leader in Enterprise Java
• now part of Pivotal
• Spring
• Cloud Foundry
• Redis
• RabbitMQ & SockJS
• Groovy & Grails
• Pivotal Labs
How can browsers
communicate?
• HTTP (XMLHttpRequest)
• WebSockets
• WebRTC (are we there yet?)
How do applications
communicate from a browser?
• how should they communicate?
We use jQuery, duh
$.get('/usersList.php',
function (response) { ... });
We use jQuery, duh
$.get('/usersList.php').then(
function (response) { ... }
);
...not to start a holy war, but I like promises
What's wrong here?
$.ajax({
url: '/usersList.php',
data: { page: 1, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);
...lot of little nits, but it's not too bad
What's wrong here?
$.ajax({
url: '/usersList.php',
data: { page: 3, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);
$.ajax({
url: '/usersList.php',
data: { page: 5, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);$.ajax({
url: '/usersList.php',
data: { page: 4, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);
$.ajax({
url: '/usersList.php',
data: { page: 1, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);
$.ajax({
url: '/usersList.php',
data: { page: 2, count: 50 }
}).then(
function (response) { ... },
function (error) { ... }
);
Abstract the common bits
function loadUsers(pageNum) {
return $.ajax({
url: '/usersList.php',
data: { page: pageNum, count: 50 }
});
}
loadUsers(1).then(
function (response) { ... },
function (error) { ... }
);
Poor abstractions
• abstracts HTTP rather than embracing it
• it's not just jQuery
• every 'Ajax' lib suffers from this issue
• should abstract interacting with resources rather than
mechanics of making requests
rest.js
• very thin wrapper around a raw request/response
• XHR, Node, JSONP, IE XDomainRequest
• AMD and CommonJS/Node
• MIT licensed, part of cujoJS
How do I use rest.js?
var rest = require('rest');
-- or --
define(['rest'], function (rest) {
...
});
How do I use rest.js?
rest('/usersList.php').then(
function (response) { ... }
);
...wait a minute
Richardson (REST) Maturity Model
http://martinfowler.com/articles/richardsonMaturityModel.html
rest.js
• abstraction to work with resources, rather than just an
abstraction to make requests
• full access to all aspects of the request and response,
including response headers
• advanced behavior applied with interceptors
• configure behavior once, share
What makes rest.js different?
• Interceptors!
• apply advanced behavior to the request/response
• encapsulate configuration
• use what you need
What's an interceptor?
var client = rest.chain(basicAuthInterceptor, {
username: 'marisa',
password: 'koala'
});
client('/usersList.php').then(
function (response) {
... authenticated response...
}
);
What can interceptors do?
• almost anything
• hook into the request/response lifecycle
• augment or replace a request/response
• provide an alternate client
• detect and/or recover from errors
• abort the request
What can't interceptors do?
• alter a configured client
Provided interceptors
• Common: Default Request, Entity, Path Prefix, Location
• RESTful: Content negotiation, Hypermedia APIs
• Authentication: Basic, OAuth
• Error Detection and Recover: Error Code, Retry, Timeout
• Fallbacks: JSONP, XDomainRequest (IE), ActiveX XHR (IE)
Custom interceptors
return interceptor({
init: function (config) {
return config;
},
request: function (request, config) {
return request;
},
response: function (response, config, client) {
return response;
},
success: function (response, config, client) {
return response;
},
error: function (response, config, client) {
return response;
}
});
A real interceptor: basic auth
return interceptor({
request: function handleRequest(request, config) {
var headers, username, password;
headers = request.headers || (request.headers = {});
username = request.username || config.username;
password = request.password || config.password || '';
if (username) {
headers.Authorization =
'Basic ' + base64.encode(username + ':' + password);
}
return request;
}
});
Chaining interceptors
• extend a client applying behavior to requests/response
resulting in a new client
• client can be safely shared within an application
• clients are immutable
Chaining interceptors
var client = rest.chain(basicAuthInterceptor, {
username: 'marisa',
password: 'koala'
})
.chain(errorCodeInterceptor, { code: 500 })
.chain(mimeInterceptor, { mime: 'application/json' })
.chain(hateoasInterceptor);
Interceptors in practice
var client = rest.chain(basicAuthInterceptor, {
username: 'marisa',
password: 'koala'
})
.chain(errorCodeInterceptor, { code: 500 })
.chain(mimeInterceptor, { mime: 'application/json' })
.chain(hateoasInterceptor);
...I heard about this OAuth thing, can you use it instead of whatever we currently do?
Interceptors in practice
var client = rest.chain(oAuthInterceptor, {
clientId: 'myapp',
scope: 'read,write',
authorizationUrl: 'http://example.com/oauth',
redirectUrl: 'http://myapp.com/oauth'
})
.chain(errorCodeInterceptor, { code: 500 })
.chain(mimeInterceptor, { mime: 'application/json' })
.chain(hateoasInterceptor);
• replaced basic auth with OAuth
• request is authenticated under the hood
• other interceptors, consumers don't care
What about events?
• no problem
• let’s use WebSockets
• bidirectional communication
• server → client
• client → server
The problem with
WebSocket libraries
• abstracts sending and receiving of messages
• little support for interacting with messages
Enterprise
Integration
Patterns
• simple patterns for message oriented
programming
• don't let the enterprise word scare you
• widely deployed server side
msgs.js
• Enterprise Integration Patterns in action
• provides core messaging patterns
• adapters to other messaging APIs
• supports browsers (AMD) and Node.js
• MIT licensed, part of cujoJS
Hello World
var bus = require('msgs').bus();
bus.channel('lowercase');
bus.channel('uppercase');
bus.transform(
function (message) { return message.toUpperCase(); },
{ input: 'lowercase', output: 'uppercase' }
);
bus.outboundAdapter(
function (str) { console.log(str); },
{ input: 'uppercase' }
);
bus.send('lowercase', 'hello world'); // 'HELLO WORLD'
• transformer
• filter
• router
• splitter
• aggregator
• inboundAdapter
• outboundAdapter
• inboundGateway
• outboundGateway
Messaging primitives
• bus
• channel
• pubsubChannel
• exchangeChannel
• queueChannel
• subscribe
• unsubscribe
• tap
• untap
var bus = require('msgs').bus(),
webSocketServer = ...;
bus.pubsubChannel('fromClient');
bus.pubsubChannel('toClient');
webSocketServer.on('connection', function (connection) {
bus.nodeStreamGateway(connection, {
output: 'fromClient',
input: 'toClient'
});
});
bus.forward('fromClient', 'toClient');
Broadcast server
Scalable broadcast server
var bus = require('msgs').bus(),
redis = require('redis'),
webSocketServer = ...;
bus.pubsubChannel('fromClient');
bus.pubsubChannel('toClient');
webSocketServer.on('connection', function (connection) {
bus.nodeStreamGateway(connection, {
output: 'fromClient',
input: 'toClient'
});
});
bus.redisGateway(redis.createClient, 'circles',
{ output: 'toClient', input: 'fromClient' });
Let's not forget about the client
var bus = require('msgs').bus(),
SockJS = require('sockjs');
bus.channel('toServer');
bus.channel('fromServer');
bus.webSocketGateway(
new SockJS('/msgs'),
{ output: 'fromServer', input: 'toServer' }
);
...
Full source: https://github.com/know-cujojs/circles
See it running: http://cujojs-circles.cloudfoundry.com/
Thanks
Scott Andrews
@scothis
sandrews@gopivotal.com
cujoJS	

 http://cujojs.com/
rest.js	

 https://github.com/cujojs/rest
msgs.js	

 https://github.com/cujojs/msgs

More Related Content

What's hot

node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module DevelopmentJay Harris
 
vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습John Kim
 
Cache is King - RailsConf 2019
Cache is King - RailsConf 2019Cache is King - RailsConf 2019
Cache is King - RailsConf 2019Molly Struve
 
Introduction to rest.li
Introduction to rest.liIntroduction to rest.li
Introduction to rest.liJoe Betz
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Clientrahul patel
 
Puppet at janrain
Puppet at janrainPuppet at janrain
Puppet at janrainPuppet
 
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
 
[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2NAVER D2
 
Node Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyNode Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyBishan Singh
 
Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존동수 장
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.jsConFoo
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJSRan Mizrahi
 
DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks Felipe Prado
 
Hadoop sqoop2 server setup and application integration
Hadoop   sqoop2 server setup and application integrationHadoop   sqoop2 server setup and application integration
Hadoop sqoop2 server setup and application integrationRajasekaran kandhasamy
 
Node js introduction
Node js introductionNode js introduction
Node js introductionAlex Su
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedEspeo Software
 

What's hot (20)

Express js
Express jsExpress js
Express js
 
Intro to Sail.js
Intro to Sail.jsIntro to Sail.js
Intro to Sail.js
 
node.js Module Development
node.js Module Developmentnode.js Module Development
node.js Module Development
 
vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습
 
Cache is King - RailsConf 2019
Cache is King - RailsConf 2019Cache is King - RailsConf 2019
Cache is King - RailsConf 2019
 
Introduction to rest.li
Introduction to rest.liIntroduction to rest.li
Introduction to rest.li
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
 
Puppet at janrain
Puppet at janrainPuppet at janrain
Puppet at janrain
 
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
 
[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2[263] s2graph large-scale-graph-database-with-hbase-2
[263] s2graph large-scale-graph-database-with-hbase-2
 
Node Security: The Good, Bad & Ugly
Node Security: The Good, Bad & UglyNode Security: The Good, Bad & Ugly
Node Security: The Good, Bad & Ugly
 
Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존Java/Spring과 Node.js의공존
Java/Spring과 Node.js의공존
 
Building servers with Node.js
Building servers with Node.jsBuilding servers with Node.js
Building servers with Node.js
 
Dependency Injection @ AngularJS
Dependency Injection @ AngularJSDependency Injection @ AngularJS
Dependency Injection @ AngularJS
 
DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks DEF CON 23 - amit ashbel and maty siman - game of hacks
DEF CON 23 - amit ashbel and maty siman - game of hacks
 
2021laravelconftwslides11
2021laravelconftwslides112021laravelconftwslides11
2021laravelconftwslides11
 
Hadoop sqoop2 server setup and application integration
Hadoop   sqoop2 server setup and application integrationHadoop   sqoop2 server setup and application integration
Hadoop sqoop2 server setup and application integration
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Guide to Node.js: Basic to Advanced
Guide to Node.js: Basic to AdvancedGuide to Node.js: Basic to Advanced
Guide to Node.js: Basic to Advanced
 

Similar to Taming client-server communication

Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Servicevvatikiotis
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Webnickmbailey
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1Mohammad Qureshi
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsOhad Kravchick
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkRed Hat Developers
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009hugowetterberg
 
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
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングscalaconfjp
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Ngoc Dao
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsNeil Crookes
 
Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express MiddlewareMorris Singer
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in reactBOSC Tech Labs
 
Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureMark McGranaghan
 
Nginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksNginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksAdam Wiggins
 

Similar to Taming client-server communication (20)

Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Clojure and the Web
Clojure and the WebClojure and the Web
Clojure and the Web
 
Intro to node and mongodb 1
Intro to node and mongodb   1Intro to node and mongodb   1
Intro to node and mongodb 1
 
Android and REST
Android and RESTAndroid and REST
Android and REST
 
Building and Scaling Node.js Applications
Building and Scaling Node.js ApplicationsBuilding and Scaling Node.js Applications
Building and Scaling Node.js Applications
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech TalkHacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
Hacking the Mesh: Extending Istio with WebAssembly Modules | DevNation Tech Talk
 
Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009Services Drupalcamp Stockholm 2009
Services Drupalcamp Stockholm 2009
 
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
 
Java Technology
Java TechnologyJava Technology
Java Technology
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
Designing CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIsDesigning CakePHP plugins for consuming APIs
Designing CakePHP plugins for consuming APIs
 
Unit Testing Express Middleware
Unit Testing Express MiddlewareUnit Testing Express Middleware
Unit Testing Express Middleware
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
How to perform debounce in react
How to perform debounce in reactHow to perform debounce in react
How to perform debounce in react
 
Ring: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic ClojureRing: Web Apps in Idiomatic Clojure
Ring: Web Apps in Idiomatic Clojure
 
Nginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP TricksNginx: Accelerate Rails, HTTP Tricks
Nginx: Accelerate Rails, HTTP Tricks
 
Spine.js
Spine.jsSpine.js
Spine.js
 

Recently uploaded

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsAndrey Dotsenko
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 

Recently uploaded (20)

Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 

Taming client-server communication

  • 2. About me • engineer @ SpringSource / Pivotal • contributor to cujoJS • drifter • application framework • open source commercial • client server • front-end back-end
  • 3. A brief word from my sponsor • leader in Enterprise Java • now part of Pivotal • Spring • Cloud Foundry • Redis • RabbitMQ & SockJS • Groovy & Grails • Pivotal Labs
  • 4. How can browsers communicate? • HTTP (XMLHttpRequest) • WebSockets • WebRTC (are we there yet?)
  • 5. How do applications communicate from a browser? • how should they communicate?
  • 6. We use jQuery, duh $.get('/usersList.php', function (response) { ... });
  • 7. We use jQuery, duh $.get('/usersList.php').then( function (response) { ... } ); ...not to start a holy war, but I like promises
  • 8. What's wrong here? $.ajax({ url: '/usersList.php', data: { page: 1, count: 50 } }).then( function (response) { ... }, function (error) { ... } ); ...lot of little nits, but it's not too bad
  • 9. What's wrong here? $.ajax({ url: '/usersList.php', data: { page: 3, count: 50 } }).then( function (response) { ... }, function (error) { ... } ); $.ajax({ url: '/usersList.php', data: { page: 5, count: 50 } }).then( function (response) { ... }, function (error) { ... } );$.ajax({ url: '/usersList.php', data: { page: 4, count: 50 } }).then( function (response) { ... }, function (error) { ... } ); $.ajax({ url: '/usersList.php', data: { page: 1, count: 50 } }).then( function (response) { ... }, function (error) { ... } ); $.ajax({ url: '/usersList.php', data: { page: 2, count: 50 } }).then( function (response) { ... }, function (error) { ... } );
  • 10. Abstract the common bits function loadUsers(pageNum) { return $.ajax({ url: '/usersList.php', data: { page: pageNum, count: 50 } }); } loadUsers(1).then( function (response) { ... }, function (error) { ... } );
  • 11. Poor abstractions • abstracts HTTP rather than embracing it • it's not just jQuery • every 'Ajax' lib suffers from this issue • should abstract interacting with resources rather than mechanics of making requests
  • 12. rest.js • very thin wrapper around a raw request/response • XHR, Node, JSONP, IE XDomainRequest • AMD and CommonJS/Node • MIT licensed, part of cujoJS
  • 13. How do I use rest.js? var rest = require('rest'); -- or -- define(['rest'], function (rest) { ... });
  • 14. How do I use rest.js? rest('/usersList.php').then( function (response) { ... } ); ...wait a minute
  • 15. Richardson (REST) Maturity Model http://martinfowler.com/articles/richardsonMaturityModel.html
  • 16. rest.js • abstraction to work with resources, rather than just an abstraction to make requests • full access to all aspects of the request and response, including response headers • advanced behavior applied with interceptors • configure behavior once, share
  • 17. What makes rest.js different? • Interceptors! • apply advanced behavior to the request/response • encapsulate configuration • use what you need
  • 18. What's an interceptor? var client = rest.chain(basicAuthInterceptor, { username: 'marisa', password: 'koala' }); client('/usersList.php').then( function (response) { ... authenticated response... } );
  • 19. What can interceptors do? • almost anything • hook into the request/response lifecycle • augment or replace a request/response • provide an alternate client • detect and/or recover from errors • abort the request
  • 20. What can't interceptors do? • alter a configured client
  • 21. Provided interceptors • Common: Default Request, Entity, Path Prefix, Location • RESTful: Content negotiation, Hypermedia APIs • Authentication: Basic, OAuth • Error Detection and Recover: Error Code, Retry, Timeout • Fallbacks: JSONP, XDomainRequest (IE), ActiveX XHR (IE)
  • 22. Custom interceptors return interceptor({ init: function (config) { return config; }, request: function (request, config) { return request; }, response: function (response, config, client) { return response; }, success: function (response, config, client) { return response; }, error: function (response, config, client) { return response; } });
  • 23. A real interceptor: basic auth return interceptor({ request: function handleRequest(request, config) { var headers, username, password; headers = request.headers || (request.headers = {}); username = request.username || config.username; password = request.password || config.password || ''; if (username) { headers.Authorization = 'Basic ' + base64.encode(username + ':' + password); } return request; } });
  • 24. Chaining interceptors • extend a client applying behavior to requests/response resulting in a new client • client can be safely shared within an application • clients are immutable
  • 25. Chaining interceptors var client = rest.chain(basicAuthInterceptor, { username: 'marisa', password: 'koala' }) .chain(errorCodeInterceptor, { code: 500 }) .chain(mimeInterceptor, { mime: 'application/json' }) .chain(hateoasInterceptor);
  • 26. Interceptors in practice var client = rest.chain(basicAuthInterceptor, { username: 'marisa', password: 'koala' }) .chain(errorCodeInterceptor, { code: 500 }) .chain(mimeInterceptor, { mime: 'application/json' }) .chain(hateoasInterceptor); ...I heard about this OAuth thing, can you use it instead of whatever we currently do?
  • 27. Interceptors in practice var client = rest.chain(oAuthInterceptor, { clientId: 'myapp', scope: 'read,write', authorizationUrl: 'http://example.com/oauth', redirectUrl: 'http://myapp.com/oauth' }) .chain(errorCodeInterceptor, { code: 500 }) .chain(mimeInterceptor, { mime: 'application/json' }) .chain(hateoasInterceptor); • replaced basic auth with OAuth • request is authenticated under the hood • other interceptors, consumers don't care
  • 28. What about events? • no problem • let’s use WebSockets • bidirectional communication • server → client • client → server
  • 29. The problem with WebSocket libraries • abstracts sending and receiving of messages • little support for interacting with messages
  • 30. Enterprise Integration Patterns • simple patterns for message oriented programming • don't let the enterprise word scare you • widely deployed server side
  • 31. msgs.js • Enterprise Integration Patterns in action • provides core messaging patterns • adapters to other messaging APIs • supports browsers (AMD) and Node.js • MIT licensed, part of cujoJS
  • 32. Hello World var bus = require('msgs').bus(); bus.channel('lowercase'); bus.channel('uppercase'); bus.transform( function (message) { return message.toUpperCase(); }, { input: 'lowercase', output: 'uppercase' } ); bus.outboundAdapter( function (str) { console.log(str); }, { input: 'uppercase' } ); bus.send('lowercase', 'hello world'); // 'HELLO WORLD'
  • 33. • transformer • filter • router • splitter • aggregator • inboundAdapter • outboundAdapter • inboundGateway • outboundGateway Messaging primitives • bus • channel • pubsubChannel • exchangeChannel • queueChannel • subscribe • unsubscribe • tap • untap
  • 34. var bus = require('msgs').bus(), webSocketServer = ...; bus.pubsubChannel('fromClient'); bus.pubsubChannel('toClient'); webSocketServer.on('connection', function (connection) { bus.nodeStreamGateway(connection, { output: 'fromClient', input: 'toClient' }); }); bus.forward('fromClient', 'toClient'); Broadcast server
  • 35. Scalable broadcast server var bus = require('msgs').bus(), redis = require('redis'), webSocketServer = ...; bus.pubsubChannel('fromClient'); bus.pubsubChannel('toClient'); webSocketServer.on('connection', function (connection) { bus.nodeStreamGateway(connection, { output: 'fromClient', input: 'toClient' }); }); bus.redisGateway(redis.createClient, 'circles', { output: 'toClient', input: 'fromClient' });
  • 36. Let's not forget about the client var bus = require('msgs').bus(), SockJS = require('sockjs'); bus.channel('toServer'); bus.channel('fromServer'); bus.webSocketGateway( new SockJS('/msgs'), { output: 'fromServer', input: 'toServer' } ); ... Full source: https://github.com/know-cujojs/circles See it running: http://cujojs-circles.cloudfoundry.com/
  • 37. Thanks Scott Andrews @scothis sandrews@gopivotal.com cujoJS http://cujojs.com/ rest.js https://github.com/cujojs/rest msgs.js https://github.com/cujojs/msgs