SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Rapid API development examples for
Impress Application Server (Node.js)
Timur Shemsedinov
Research Institute of System Technologies (UA, Kiev), MetaSystems Inc.
mailto:timur.shemsedinov@gmail.com https://github.com/tshemsedinov/impress
http://habrahabr.ru/users/marcusaurelius/ https://www.npmjs.org/package/impress
Impress Application Server is:
• Scaling transparent to applications
• Application isolation (memory configuration database)
• Deployment or update code without restart
• Highload serving static files from memory (gzip, js minification, etc.)
• URL-rewriting using RegExp, with internal redirection or sending
external HTTP-requests (reverse proxying)
• Virtual hosts with multi-domain support (e.g.: *.domain.com)
• Executable code and static caching in RAM
• TCP port multiplexing and demultiplexing between applications
• Server-Sent Events and WebSocket support
• Stateless API (REST) and stateful API (RPC) support with IP-sticky
and Cookie-sticky to associated processes and global state sync.
• Many other features: sessions, rotating logging, IPC and ZeroMQ,
database access drivers, etc.
Rapid API development examples
General principles:
• Request routing based on file system
• Each handler in separate file, handler inherit/override mechanism
• Handlers need not prepare request execution environment, such as
import/load libraries, establish db connections, build memory
structures, etc., request will come to ready application environment
and handler will contain just applied code
• Each application have own isolated context and in-memory state
• Long and batch workers in separate threads (forking by Impress
Application Server into parallel processes)
• Global cross-server interprocess communication based on system
IPC and ZeroMQ to translate events, synchronize state, use reactive
approach and actor-pattern
1. Simple JSON handler
/example/app/examples/simple/jsonPost.json/post.js
module.exports = function(client, callback) {
client.context.data = { a: 1 };
callback();
}
---------------------------------------------------------------
HTTP POST /example/app/examples/simple/jsonPost.json
{
"a": 1
}
2. Simple AJAX handler with template
/examples/simple/ajaxTest.ajax/get.js
module.exports = function(client, callback) {
client.context.data = {
parameterName: client.query.parameterName,
};
callback();
}
---------------------------------------------------------------
/examples/simple/ajaxTest.ajax/html.template
AJAX Request with parameter returning back in template<br>
parameterName: @parameterName@
---------------------------------------------------------------
HTTP GET
/examples/simple/ajaxTest.ajax?parameterName=parameterValue
AJAX Request with parameter returning back in template<br>
parameterName: parameterValue
3. Client-side example
/js/init.js
$.post('/examples/simple/jsonPost.json',
{ parameterName: "paramaterValue" },
function(res) {
console.log(res.valueLength);
}
);
---------------------------------------------------------------
HTTP POST /example/app/examples/simple/jsonPost.json
{
"status": 1,
"parameterValue": "paramaterValue",
"valueLength": 14,
"requestCounter": 3
}
---------------------------------------------------------------
Console:
14
4. File system access example
/examples/simple/fsAccess.json/get.js
module.exports = function(client, callback) {
var filePath = client.hostDir+client.path+'/test.txt';
fs.readFile(filePath, 'utf8', function(error, data) {
client.context.data = {
fileContent: data,
dataLength: data.length
};
callback();
});
}
---------------------------------------------------------------
HTTP GET /examples/simple/fsAccess.json
{
"fileContent": "?Example text file",
"dataLength": 18
}
5. HTTP-request from API handle example
/examples/simple/httpRequest.json/get.js
module.exports = function(client, callback) {
var req = impress.http.request({ hostname: 'google.com',
port: 80, path: '/', method: 'get' },
function(response) {
var data = '';
response.on('data', function(chunk) {data=data+chunk;});
response.on('end', function() {
client.context.data = data;
callback();
});
}
);
req.on('error', function(e) {
client.context.data = "Can't get page";
callback();
});
req.end();
}
6. MongoDB (read) access example
/examples/mongodb/getData.json/get.js
module.exports = function(client, callback) {
dbAlias.testCollection.find({}).toArray(
function(err, nodes) {
client.context.data = nodes;
callback();
}
);
}
---------------------------------------------------------------
HTTP GET mongodb/getData.json
[
{ "_id": "53547375894c3d3022000001" }
]
7. MongoDB write and metadata examples
/examples/mongodb/insertData.json/get.js
module.exports = function(client, callback) {
dbAlias.testCollection.insert(client.query, function(err) {
client.context.data = !err;
callback();
});
}
---------------------------------------------------------------
/examples/mongodb/getCollections.json/get.js
module.exports = function(client, callback) {
dbImpress.connection.collections(function(err, collections) {
var items = [];
for (var i = 0; i < collections.length; i++) {
items.push(collections[i].collectionName);
}
client.context.data = items;
callback();
});
}
8. SQL-query (MySql) access example
/examples/mysql/getCities.json/get.js
module.exports = function(client, callback) {
dbAlias.query(
'select * from City',
function(err, rows, fields) {
client.context.data = { rows:rows, fields:fields };
callback();
}
);
}
9. Async parallel resource access example
/examples/complex/getFsMongoRequest.json/get.js
module.exports = function(client, callback) {
impress.async.parallel({
file: function(callback) {
var filePath = client.hostDir+client.path+'/test.txt';
fs.readFile(filePath, 'utf8', function(error, data) {
callback(null, data);
});
},
request: function(callback) {
var req = impress.http.request({ hostname: 'google.com', port: 80,
path: '/', method: 'get' },
function(response) {
var data = '';
response.on('data', function(chunk) { data = data+chunk; });
response.on('end', function() { callback(null, data); });
}
);
req.on('error', function(e) {
callback(null, "Can't get page");
});
req.end();
},
...
...previous example end
/examples/complex/getFsMongoRequest.json/get.js
...
mongo: function(callback) {
dbAlias.testCollection.find({}).toArray(function(err, nodes) {
callback(null, nodes);
});
}
}, function(err, results) {
client.context.data = results;
callback();
});
}
---------------------------------------------------------------------------------
{
"mongo": [
{ "_id": "53547375894c3d3022000001" }
],
"file": "?Example text file",
"request": "<HTML><HEAD><meta http-equiv="content-type" content="text/html;
charset=utf-8">n<TITLE>302 Moved</TITLE></HEAD><BODY>n
<H1>302 Moved</H1>nThe document has movedn
<A HREF="http://www.google.com.ua/?gws_rd=cr&amp;
ei=OWVWU5nHOqOc4wTbjYDgBw">here</A>.rn</BODY></HTML>rn"
}
10. Stateful API handler example
/examples/memory/stateful.json/get.js
module.exports = function(client, callback) {
application.stateTest =
application.stateTest || { counter: 0, addresses: [] };
application.stateTest.counter++;
application.stateTest.addresses.push(
client.req.connection.remoteAddress
);
client.context.data = application.stateTest;
callback();
}
11. SSE handle example
/examples/events/connect.sse/get.js
module.exports = function(client, callback) {
client.sse.channel = 'TestEventStream';
callback();
}
---------------------------------------------------------------
/js/init.js
var sse = new EventSource("/examples/events/connect.sse");
sse.addEventListener("TestEventStream", function(e) {
console.dir({
event: e.event,
data: e.data
});
});
12. WebSocket handler example
/examples/events/connect.ws/get.js
module.exports = function(client, callback) {
var connection = client.res.websocket.accept();
connection.send('Hello world');
connection.on('message', function(message) {
connection.send('I am here');
});
connection.on('close', function(reasonCode, description) {
console.log('disconnected');
});
callback();
}
---------------------------------------------------------------
/js/init.js
ws = new WebSocket("ws://127.0.0.1:80/examples/events/connect.ws");
ws.onopen = function() {};
ws.onclose = function() {};
ws.onmessage = function(evt) {
console.log("Message from server: "+evt.data);
}
API and FS introspection screens
Deployment patterns
• Installation script with deployment recomendations
• Applications Server Configuration /config/*.js
• Start strategies (single, multiple, specialization, sticky)
• Multithreading parameters: cluster.js
• Network interfaces and port configuration: servers.js
• Sandboxes configuration, plugins and access
• Impress Applied Controller configuration: cloud.js
• Logging configuration: log.js
• Application configuration /applications/name/config/*.js
• Database access parameters: databases.js
• Virtualhosts: hosts.js
• URL-rewriting and reverse proxy configuration: routes.js
• Session parameters: sessions.js
• Static files and caching parameters: files.js
• Application specific configuration files
Server installation (node.js + Impress)
CentOS 6.5 (64bit) minimal
curl http://.../impress/install.sh | sh
---------------------------------------------------------------
#!/bin/bash
yum -y update
yum -y install wget
yum -y groupinstall "Development Tools"
cd /usr/src
wget http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz
tar zxf node-v0.10.26.tar.gz
cd node-v0.10.26
./configure
make
make install
ln -s /usr/local/bin/node /bin
ln -s /usr/local/bin/npm /bin
mkdir /impress
cd /impress
npm install impress
Application Server as Linux Daemon
If installing Impress into absolute path /impress
Run /impress/bin/install.sh for:
• Setup and configure as Linux daemon
• Run at system startup
• Auto-restart daemon workers on fails
Run /impress/bin/uninstall.sh for:
• Stop Application Server
• Remove from system startup
• Remove Daemon from system
After install as a service (daemon) you can use:
service impress start
service impress stop
service impress restart
service impress update
service impress status
Application Server Configuration
/config/cloud.js
module.exports = {
name: "PrivateCloud",
type: "standalone",
controller: "127.0.0.1",
pubSubPort: "3000",
reqResPort: "3001",
health: "2s"
}
---------------------------------------------------------------
/config/cluster.js
module.exports = {
check: "http://127.0.0.2/",
name: "C1",
cookie: "node",
strategy: "multiple", // single, specialization, sticky
workers: os.cpus().length,
gcInterval: 0
}
Network interfaces & ports config
/config/servers.js
module.exports = {
www: {
protocol: "http",
address: "127.0.0.1",
port: 80,
applications: ["example", "host2"],
nagle: true,
slowTime: "1s"
},
ssl: {
protocol: "https",
address: "127.0.0.1",
port: 443,
key: "example.key",
cert: "example.cer"
}
}
Plugins configuration
/config/plugins.js
module.exports = [
"db",
"db.schema",
"db.mongodb",
"db.memcached",
"db.mysql",
"db.mysql.schema",
"impress.log",
"impress.security",
"impress.security.mongodb",
"impress.mail",
"impress.uglify",
"impress.health",
"impress.cloud",
"impress.geoip",
"impress.websocket",
"impress.sse"
]
Logging and sandbox configuration
/config/log.js
module.exports = {
keepDays: 10,
writeInterval: "3s",
writeBuffer: 64*1024,
fileTypes: [ "access", "error", "debug", "slow" ]
}
---------------------------------------------------------------
/config/sandbox.js
module.exports = { modules: [
'global', 'console', 'process', 'impress',
'db', 'domain', 'crypto', 'geoip',
'os', 'Buffer', 'stream', 'nodemailer',
'net', 'http', 'https', 'dgram',
'dns', 'url', 'path', 'fs',
'util', 'events', 'iconv', 'querystring',
'zlib', 'async'
]}
Virtualhosts and URL-rewriting config
/applications/applicationName/config/hosts.js
module.exports = [
"127.0.0.1",
"mydomain.com",
"*.domainname.com",
]
---------------------------------------------------------------
/applications/applicationName/config/routes.js
module.exports = [
{ url: "/api/(one|two)/(.*)",
rewrite: "/example/[1].json?par1=[2]"
},
{ url: "/api/(name1|name2|name3)/(.*)",
rewrite: "/api/[1]/[2]",
host: "example.com",
port: 80,
slowTime: "1s"
}
]
Database access configuration
/applications/applicationName/config/databases.js
module.exports = {
mongoTest: {
url: "mongodb://hostName:27017/databaseName",
slowTime: "2s",
collections: ["collection1", "collection2"],
security: true,
alias: "alias1"
},
system: {
url: "mysql://user:password@localhost/dbName",
slowTime: 1000,
alias: "aliasName"
}
}
Session and static files serving config
/applications/applicationName/config/sessions.js
module.exports = {
anonymous: true,
cookie: "SID",
characters: "ABCDEFGH...fghijkl...456789",
length: 64,
persist: true,
database: "impress"
}
---------------------------------------------------------------
/applications/applicationName/config/files.js
module.exports = {
minify: false,
static: [
"*/css/*", "*/images/*", "*/js/*",
"*/favicon.ico", "*/favicon.png"
]
}
Examples: Demo Applications
Thanks for attention!
Questions please
Timur Shemsedinov
Research Institute of System Technologies (UA, Kiev), MetaSystems Inc.
mailto:timur.shemsedinov@gmail.com
http://habrahabr.ru/users/marcusaurelius/
https://www.npmjs.org/package/impress
https://github.com/tshemsedinov/impress

Weitere ähnliche Inhalte

Was ist angesagt?

실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례John Kim
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Ontico
 
Jolokia - JMX on Capsaicin (Devoxx 2011)
Jolokia - JMX on Capsaicin (Devoxx 2011)Jolokia - JMX on Capsaicin (Devoxx 2011)
Jolokia - JMX on Capsaicin (Devoxx 2011)roland.huss
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS ExpressDavid Boyer
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습John Kim
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Clientrahul patel
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven ProgrammingKamal Hussain
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?Demis Bellot
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkSadayuki Furuhashi
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화NAVER D2
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Christian Joudrey
 
Nodejs getting started
Nodejs getting startedNodejs getting started
Nodejs getting startedTriet Ho
 
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...ronwarshawsky
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageSATOSHI TAGOMORI
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadAll Things Open
 
50 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 201450 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 2014Arun Gupta
 
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...Ontico
 
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...Ontico
 

Was ist angesagt? (20)

실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
 
Jolokia - JMX on Capsaicin (Devoxx 2011)
Jolokia - JMX on Capsaicin (Devoxx 2011)Jolokia - JMX on Capsaicin (Devoxx 2011)
Jolokia - JMX on Capsaicin (Devoxx 2011)
 
All aboard the NodeJS Express
All aboard the NodeJS ExpressAll aboard the NodeJS Express
All aboard the NodeJS Express
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습vert.x 소개 및 개발 실습
vert.x 소개 및 개발 실습
 
Unirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http ClientUnirest Java Tutorial | Java Http Client
Unirest Java Tutorial | Java Http Client
 
Server Side Event Driven Programming
Server Side Event Driven ProgrammingServer Side Event Driven Programming
Server Side Event Driven Programming
 
What is the ServiceStack?
What is the ServiceStack?What is the ServiceStack?
What is the ServiceStack?
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?Introduction to Node.js: What, why and how?
Introduction to Node.js: What, why and how?
 
Nodejs getting started
Nodejs getting startedNodejs getting started
Nodejs getting started
 
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...
MongoDB performance tuning and load testing, NOSQL Now! 2013 Conference prese...
 
Data Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby UsageData Analytics Service Company and Its Ruby Usage
Data Analytics Service Company and Its Ruby Usage
 
Regex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language InsteadRegex Considered Harmful: Use Rosie Pattern Language Instead
Regex Considered Harmful: Use Rosie Pattern Language Instead
 
50 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 201450 features of Java EE 7 in 50 minutes at JavaZone 2014
50 features of Java EE 7 in 50 minutes at JavaZone 2014
 
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
Как Web-акселератор акселерирует ваш сайт / Александр Крижановский (Tempesta ...
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven TomacJavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
 
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
Как понять, что происходит на сервере? / Александр Крижановский (NatSys Lab.,...
 

Ähnlich wie Rapid API development examples for Impress Application Server / Node.js (jsfwdays 2014)

There is time for rest
There is time for rest There is time for rest
There is time for rest SoftServe
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
Clojure Web Development
Clojure Web DevelopmentClojure Web Development
Clojure Web DevelopmentHong Jiang
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
Spring-training-in-bangalore
Spring-training-in-bangaloreSpring-training-in-bangalore
Spring-training-in-bangaloreTIB Academy
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax IntroductionOliver Cai
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restfulknight1128
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 

Ähnlich wie Rapid API development examples for Impress Application Server / Node.js (jsfwdays 2014) (20)

Ajax
AjaxAjax
Ajax
 
There is time for rest
There is time for rest There is time for rest
There is time for rest
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
Clojure Web Development
Clojure Web DevelopmentClojure Web Development
Clojure Web Development
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Spring-training-in-bangalore
Spring-training-in-bangaloreSpring-training-in-bangalore
Spring-training-in-bangalore
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
 
08 ajax
08 ajax08 ajax
08 ajax
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
AJAX
AJAXAJAX
AJAX
 

Mehr von Timur Shemsedinov

How to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.jsHow to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.jsTimur Shemsedinov
 
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...Timur Shemsedinov
 
Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptTimur Shemsedinov
 
Node.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasksNode.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasksTimur Shemsedinov
 
Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021Timur Shemsedinov
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsTimur Shemsedinov
 
Node.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceNode.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceTimur Shemsedinov
 
Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3Timur Shemsedinov
 
Node.js middleware: Never again!
Node.js middleware: Never again!Node.js middleware: Never again!
Node.js middleware: Never again!Timur Shemsedinov
 
Race-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memoryRace-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memoryTimur Shemsedinov
 
Asynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingAsynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingTimur Shemsedinov
 
Information system structure and architecture
Information system structure and architectureInformation system structure and architecture
Information system structure and architectureTimur Shemsedinov
 

Mehr von Timur Shemsedinov (20)

How to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.jsHow to use Chat GPT in JavaScript optimizations for Node.js
How to use Chat GPT in JavaScript optimizations for Node.js
 
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
IT Revolution in 2023-2024: AI, GPT, business transformation, future professi...
 
Multithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScriptMultithreading in Node.js and JavaScript
Multithreading in Node.js and JavaScript
 
Node.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasksNode.js threads for I/O-bound tasks
Node.js threads for I/O-bound tasks
 
Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021Node.js Меньше сложности, больше надежности Holy.js 2021
Node.js Меньше сложности, больше надежности Holy.js 2021
 
Rethinking low-code
Rethinking low-codeRethinking low-code
Rethinking low-code
 
Hat full of developers
Hat full of developersHat full of developers
Hat full of developers
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.js
 
Node.js for enterprise - JS Conference
Node.js for enterprise - JS ConferenceNode.js for enterprise - JS Conference
Node.js for enterprise - JS Conference
 
Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3Node.js for enterprise 2021 - JavaScript Fwdays 3
Node.js for enterprise 2021 - JavaScript Fwdays 3
 
Node.js in 2021
Node.js in 2021Node.js in 2021
Node.js in 2021
 
Node.js middleware: Never again!
Node.js middleware: Never again!Node.js middleware: Never again!
Node.js middleware: Never again!
 
Patterns and antipatterns
Patterns and antipatternsPatterns and antipatterns
Patterns and antipatterns
 
Race-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memoryRace-conditions-web-locks-and-shared-memory
Race-conditions-web-locks-and-shared-memory
 
Asynchronous programming and mutlithreading
Asynchronous programming and mutlithreadingAsynchronous programming and mutlithreading
Asynchronous programming and mutlithreading
 
Node.js in 2020 - part 3
Node.js in 2020 - part 3Node.js in 2020 - part 3
Node.js in 2020 - part 3
 
Node.js in 2020 - part 2
Node.js in 2020 - part 2Node.js in 2020 - part 2
Node.js in 2020 - part 2
 
Information system structure and architecture
Information system structure and architectureInformation system structure and architecture
Information system structure and architecture
 
Node.js in 2020 - part 1
Node.js in 2020 - part 1Node.js in 2020 - part 1
Node.js in 2020 - part 1
 
Web Locks API
Web Locks APIWeb Locks API
Web Locks API
 

Kürzlich hochgeladen

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
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
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.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
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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
 

Kürzlich hochgeladen (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
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-...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
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
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
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
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.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 ...
 
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
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
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...
 

Rapid API development examples for Impress Application Server / Node.js (jsfwdays 2014)

  • 1. Rapid API development examples for Impress Application Server (Node.js) Timur Shemsedinov Research Institute of System Technologies (UA, Kiev), MetaSystems Inc. mailto:timur.shemsedinov@gmail.com https://github.com/tshemsedinov/impress http://habrahabr.ru/users/marcusaurelius/ https://www.npmjs.org/package/impress
  • 2. Impress Application Server is: • Scaling transparent to applications • Application isolation (memory configuration database) • Deployment or update code without restart • Highload serving static files from memory (gzip, js minification, etc.) • URL-rewriting using RegExp, with internal redirection or sending external HTTP-requests (reverse proxying) • Virtual hosts with multi-domain support (e.g.: *.domain.com) • Executable code and static caching in RAM • TCP port multiplexing and demultiplexing between applications • Server-Sent Events and WebSocket support • Stateless API (REST) and stateful API (RPC) support with IP-sticky and Cookie-sticky to associated processes and global state sync. • Many other features: sessions, rotating logging, IPC and ZeroMQ, database access drivers, etc.
  • 3. Rapid API development examples General principles: • Request routing based on file system • Each handler in separate file, handler inherit/override mechanism • Handlers need not prepare request execution environment, such as import/load libraries, establish db connections, build memory structures, etc., request will come to ready application environment and handler will contain just applied code • Each application have own isolated context and in-memory state • Long and batch workers in separate threads (forking by Impress Application Server into parallel processes) • Global cross-server interprocess communication based on system IPC and ZeroMQ to translate events, synchronize state, use reactive approach and actor-pattern
  • 4. 1. Simple JSON handler /example/app/examples/simple/jsonPost.json/post.js module.exports = function(client, callback) { client.context.data = { a: 1 }; callback(); } --------------------------------------------------------------- HTTP POST /example/app/examples/simple/jsonPost.json { "a": 1 }
  • 5. 2. Simple AJAX handler with template /examples/simple/ajaxTest.ajax/get.js module.exports = function(client, callback) { client.context.data = { parameterName: client.query.parameterName, }; callback(); } --------------------------------------------------------------- /examples/simple/ajaxTest.ajax/html.template AJAX Request with parameter returning back in template<br> parameterName: @parameterName@ --------------------------------------------------------------- HTTP GET /examples/simple/ajaxTest.ajax?parameterName=parameterValue AJAX Request with parameter returning back in template<br> parameterName: parameterValue
  • 6. 3. Client-side example /js/init.js $.post('/examples/simple/jsonPost.json', { parameterName: "paramaterValue" }, function(res) { console.log(res.valueLength); } ); --------------------------------------------------------------- HTTP POST /example/app/examples/simple/jsonPost.json { "status": 1, "parameterValue": "paramaterValue", "valueLength": 14, "requestCounter": 3 } --------------------------------------------------------------- Console: 14
  • 7. 4. File system access example /examples/simple/fsAccess.json/get.js module.exports = function(client, callback) { var filePath = client.hostDir+client.path+'/test.txt'; fs.readFile(filePath, 'utf8', function(error, data) { client.context.data = { fileContent: data, dataLength: data.length }; callback(); }); } --------------------------------------------------------------- HTTP GET /examples/simple/fsAccess.json { "fileContent": "?Example text file", "dataLength": 18 }
  • 8. 5. HTTP-request from API handle example /examples/simple/httpRequest.json/get.js module.exports = function(client, callback) { var req = impress.http.request({ hostname: 'google.com', port: 80, path: '/', method: 'get' }, function(response) { var data = ''; response.on('data', function(chunk) {data=data+chunk;}); response.on('end', function() { client.context.data = data; callback(); }); } ); req.on('error', function(e) { client.context.data = "Can't get page"; callback(); }); req.end(); }
  • 9. 6. MongoDB (read) access example /examples/mongodb/getData.json/get.js module.exports = function(client, callback) { dbAlias.testCollection.find({}).toArray( function(err, nodes) { client.context.data = nodes; callback(); } ); } --------------------------------------------------------------- HTTP GET mongodb/getData.json [ { "_id": "53547375894c3d3022000001" } ]
  • 10. 7. MongoDB write and metadata examples /examples/mongodb/insertData.json/get.js module.exports = function(client, callback) { dbAlias.testCollection.insert(client.query, function(err) { client.context.data = !err; callback(); }); } --------------------------------------------------------------- /examples/mongodb/getCollections.json/get.js module.exports = function(client, callback) { dbImpress.connection.collections(function(err, collections) { var items = []; for (var i = 0; i < collections.length; i++) { items.push(collections[i].collectionName); } client.context.data = items; callback(); }); }
  • 11. 8. SQL-query (MySql) access example /examples/mysql/getCities.json/get.js module.exports = function(client, callback) { dbAlias.query( 'select * from City', function(err, rows, fields) { client.context.data = { rows:rows, fields:fields }; callback(); } ); }
  • 12. 9. Async parallel resource access example /examples/complex/getFsMongoRequest.json/get.js module.exports = function(client, callback) { impress.async.parallel({ file: function(callback) { var filePath = client.hostDir+client.path+'/test.txt'; fs.readFile(filePath, 'utf8', function(error, data) { callback(null, data); }); }, request: function(callback) { var req = impress.http.request({ hostname: 'google.com', port: 80, path: '/', method: 'get' }, function(response) { var data = ''; response.on('data', function(chunk) { data = data+chunk; }); response.on('end', function() { callback(null, data); }); } ); req.on('error', function(e) { callback(null, "Can't get page"); }); req.end(); }, ...
  • 13. ...previous example end /examples/complex/getFsMongoRequest.json/get.js ... mongo: function(callback) { dbAlias.testCollection.find({}).toArray(function(err, nodes) { callback(null, nodes); }); } }, function(err, results) { client.context.data = results; callback(); }); } --------------------------------------------------------------------------------- { "mongo": [ { "_id": "53547375894c3d3022000001" } ], "file": "?Example text file", "request": "<HTML><HEAD><meta http-equiv="content-type" content="text/html; charset=utf-8">n<TITLE>302 Moved</TITLE></HEAD><BODY>n <H1>302 Moved</H1>nThe document has movedn <A HREF="http://www.google.com.ua/?gws_rd=cr&amp; ei=OWVWU5nHOqOc4wTbjYDgBw">here</A>.rn</BODY></HTML>rn" }
  • 14. 10. Stateful API handler example /examples/memory/stateful.json/get.js module.exports = function(client, callback) { application.stateTest = application.stateTest || { counter: 0, addresses: [] }; application.stateTest.counter++; application.stateTest.addresses.push( client.req.connection.remoteAddress ); client.context.data = application.stateTest; callback(); }
  • 15. 11. SSE handle example /examples/events/connect.sse/get.js module.exports = function(client, callback) { client.sse.channel = 'TestEventStream'; callback(); } --------------------------------------------------------------- /js/init.js var sse = new EventSource("/examples/events/connect.sse"); sse.addEventListener("TestEventStream", function(e) { console.dir({ event: e.event, data: e.data }); });
  • 16. 12. WebSocket handler example /examples/events/connect.ws/get.js module.exports = function(client, callback) { var connection = client.res.websocket.accept(); connection.send('Hello world'); connection.on('message', function(message) { connection.send('I am here'); }); connection.on('close', function(reasonCode, description) { console.log('disconnected'); }); callback(); } --------------------------------------------------------------- /js/init.js ws = new WebSocket("ws://127.0.0.1:80/examples/events/connect.ws"); ws.onopen = function() {}; ws.onclose = function() {}; ws.onmessage = function(evt) { console.log("Message from server: "+evt.data); }
  • 17. API and FS introspection screens
  • 18. Deployment patterns • Installation script with deployment recomendations • Applications Server Configuration /config/*.js • Start strategies (single, multiple, specialization, sticky) • Multithreading parameters: cluster.js • Network interfaces and port configuration: servers.js • Sandboxes configuration, plugins and access • Impress Applied Controller configuration: cloud.js • Logging configuration: log.js • Application configuration /applications/name/config/*.js • Database access parameters: databases.js • Virtualhosts: hosts.js • URL-rewriting and reverse proxy configuration: routes.js • Session parameters: sessions.js • Static files and caching parameters: files.js • Application specific configuration files
  • 19. Server installation (node.js + Impress) CentOS 6.5 (64bit) minimal curl http://.../impress/install.sh | sh --------------------------------------------------------------- #!/bin/bash yum -y update yum -y install wget yum -y groupinstall "Development Tools" cd /usr/src wget http://nodejs.org/dist/v0.10.26/node-v0.10.26.tar.gz tar zxf node-v0.10.26.tar.gz cd node-v0.10.26 ./configure make make install ln -s /usr/local/bin/node /bin ln -s /usr/local/bin/npm /bin mkdir /impress cd /impress npm install impress
  • 20. Application Server as Linux Daemon If installing Impress into absolute path /impress Run /impress/bin/install.sh for: • Setup and configure as Linux daemon • Run at system startup • Auto-restart daemon workers on fails Run /impress/bin/uninstall.sh for: • Stop Application Server • Remove from system startup • Remove Daemon from system After install as a service (daemon) you can use: service impress start service impress stop service impress restart service impress update service impress status
  • 21. Application Server Configuration /config/cloud.js module.exports = { name: "PrivateCloud", type: "standalone", controller: "127.0.0.1", pubSubPort: "3000", reqResPort: "3001", health: "2s" } --------------------------------------------------------------- /config/cluster.js module.exports = { check: "http://127.0.0.2/", name: "C1", cookie: "node", strategy: "multiple", // single, specialization, sticky workers: os.cpus().length, gcInterval: 0 }
  • 22. Network interfaces & ports config /config/servers.js module.exports = { www: { protocol: "http", address: "127.0.0.1", port: 80, applications: ["example", "host2"], nagle: true, slowTime: "1s" }, ssl: { protocol: "https", address: "127.0.0.1", port: 443, key: "example.key", cert: "example.cer" } }
  • 23. Plugins configuration /config/plugins.js module.exports = [ "db", "db.schema", "db.mongodb", "db.memcached", "db.mysql", "db.mysql.schema", "impress.log", "impress.security", "impress.security.mongodb", "impress.mail", "impress.uglify", "impress.health", "impress.cloud", "impress.geoip", "impress.websocket", "impress.sse" ]
  • 24. Logging and sandbox configuration /config/log.js module.exports = { keepDays: 10, writeInterval: "3s", writeBuffer: 64*1024, fileTypes: [ "access", "error", "debug", "slow" ] } --------------------------------------------------------------- /config/sandbox.js module.exports = { modules: [ 'global', 'console', 'process', 'impress', 'db', 'domain', 'crypto', 'geoip', 'os', 'Buffer', 'stream', 'nodemailer', 'net', 'http', 'https', 'dgram', 'dns', 'url', 'path', 'fs', 'util', 'events', 'iconv', 'querystring', 'zlib', 'async' ]}
  • 25. Virtualhosts and URL-rewriting config /applications/applicationName/config/hosts.js module.exports = [ "127.0.0.1", "mydomain.com", "*.domainname.com", ] --------------------------------------------------------------- /applications/applicationName/config/routes.js module.exports = [ { url: "/api/(one|two)/(.*)", rewrite: "/example/[1].json?par1=[2]" }, { url: "/api/(name1|name2|name3)/(.*)", rewrite: "/api/[1]/[2]", host: "example.com", port: 80, slowTime: "1s" } ]
  • 26. Database access configuration /applications/applicationName/config/databases.js module.exports = { mongoTest: { url: "mongodb://hostName:27017/databaseName", slowTime: "2s", collections: ["collection1", "collection2"], security: true, alias: "alias1" }, system: { url: "mysql://user:password@localhost/dbName", slowTime: 1000, alias: "aliasName" } }
  • 27. Session and static files serving config /applications/applicationName/config/sessions.js module.exports = { anonymous: true, cookie: "SID", characters: "ABCDEFGH...fghijkl...456789", length: 64, persist: true, database: "impress" } --------------------------------------------------------------- /applications/applicationName/config/files.js module.exports = { minify: false, static: [ "*/css/*", "*/images/*", "*/js/*", "*/favicon.ico", "*/favicon.png" ] }
  • 29. Thanks for attention! Questions please Timur Shemsedinov Research Institute of System Technologies (UA, Kiev), MetaSystems Inc. mailto:timur.shemsedinov@gmail.com http://habrahabr.ru/users/marcusaurelius/ https://www.npmjs.org/package/impress https://github.com/tshemsedinov/impress