SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례실시간 서비스 플랫폼 개발 사례
실시간 서비스 플랫폼 개발 사례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
 

La actualidad más candente (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.,...
 

Similar a 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
 

Similar a 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
 

Más de 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
 

Más de 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
 

Último

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptrcbcrtm
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 

Último (20)

SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Odoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting ServiceOdoo Development Company in India | Devintelle Consulting Service
Odoo Development Company in India | Devintelle Consulting Service
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
cpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.pptcpct NetworkING BASICS AND NETWORK TOOL.ppt
cpct NetworkING BASICS AND NETWORK TOOL.ppt
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 

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