📜 ⬆️ ⬇️

Ajax machine

Did the Netscape LiveScript developers know what impact their language, later renamed JavaScript, had on the face of the Internet — websites, or maybe they were firmly counting on it, but the fact remains that JavaScript is one of the most important and common languages ​​in the world.

While a motley company of languages ​​works on the server side in the face of php, perl, python, ruby, .net, java and many others, on the client side JavaScript exists literally in splendid isolation. In fact, from a small addition to html, JavaScript turned into a full member of the html + css + js gang, which often already commands the rest, glittering with a gold bracelet with the words “ajax” and making a disgruntled person $ () on occasion.

This material is not an attempt to comprehend the immensity; rather, it is an attempt to eat a good immense.

What is the article and for whom it is intended


In this article, I attempted to describe a comprehensive way to build Rich Internet Applications using JavaScript — the AJAX-Machine pattern. The target audience of the article is the RIA developers and their sympathetic programmers and managers. Today, the need for Rich Internet Applications arises in various areas of web development: browser games, personal managers, commodity and workflow systems, business process management systems — i.e. any web application that requires complex logic on the client side. In the RIA-form, even traditional desktop applications are often reincarnated: mail clients, IM, various editors, and even operating systems!

I want to immediately warn a respected reader that this material:

Everything else, I am sure that I am not a pioneer of the idea; I see my task in some systematization of the material and an attempt by modest forces to convey to the distinguished reader the essence of the idea. I would like to emphasize that the area of ​​competence of the article is only the development process of Rich Internet Applications; This article does not claim to interfere with the approach to the development of classic websites: portals, blogs, news feeds and others.
')
So, with the permission of the reader, let's start!

Do I need javascript for the web?



The reader may rightly note that I started the article with a very immodest paragraph, giving js the status of an important and very common language. Is this true in reality?

The fact is obvious that js is by default considered to be supported on a computer if there is a full-featured graphical browser there. At the moment - this is a huge number of computers. However, does js have a chance of being recognized by large companies, like a mature language and, in full, sufficient for writing the RIA? I offer the reader several arguments:

Who needs javascript?



Adobe AIR
Adobe AIR logoAIR (Adobe Integrated Runtime) is an application runtime environment that allows you to use HTML / CSS / JavaScript, Adobe Flash, and Adobe Flex to transfer web applications (RIAs) to desktops. AIR-applications can exchange information with the Internet, use some features of the OS on which they are launched (for example, work with a tray / dock), as well as store data locally using the SQLite database. In essence, AIR is a browser based on the WebKit engine, with specific features available through the JavaScript-API. Supported platforms: Microsoft Windows NT, Mac OS X, alpha version for GNU / Linux.
iphone
iPhoneThe iPhone is a family of mobile phones running on a modified MacOS X OS. Initially, the creator company, Apple, did not allow third-party developers to write native applications for the iPhone, offering to create optimized web applications (html + css + js). Only after some time came the iPhone SDK, which allowed to write full-fledged "desktop" programs, but the ability to create web applications has not disappeared, and is still relevant today.
Google gears
Google Gears logoGoogle Gears is an open source development from Google that allows the use of web applications offline. All popular browsers are supported :, Firefox, Internet Explorer, Safari (doubts arise with Opera, but they promised ) and, of course, Chrome. Gears is a special plugin that forces the browser to work with the local page cache (based on SQLite), periodically synchronizing the cache with an online source. A bridge between Gears and client code is thrown using JavaScript.
Mozilla prizm
Mozilla Prizm logoMozilla Prizm is a Mozilla development using the Firefox engine. In short, Prism, basically, allows you to do two things - create desktop shortcuts for websites and open them in independent environments (a separate browser process, with hidden system menus, etc.) as if it were a program on your computer. local pc. In conjunction with Google, Gears is able to compete with AIR from Adobe, or even vice versa, to give odds, because FF + GG has a cross-platform solution - 100% support for Linux, MacOS and Windows - and even open source.
Google v8
Google Chrome logoV8 is a high-performance JavaScript interpreter that implements the ECMA-262 standard. Works on Windows XP, Vista, Mac OS X 10.5 (Leopard) and Linux-based systems on IA-32 and ARM processors. Hint! V8 is implemented in C ++ and can be used as a stand-alone interpreter or as embedded in any C ++ application. Everyone knows that V8 is built into Chrome by default. It is claimed that the interpreter is very fast due to the translation of the code into on-the-fly processor instructions ( JIT ).
Tracemonkey
FireFox logoTraceMonkey - New fast JavaScript engine for Firefox, also based on the JIT principle. It works on x86, x86-64, and ARM processors - by the way, like the V8, it can fully work on some types of mobile devices. By all indications, it will appear in FF by the end of the year, although it can be tried right now.


What can javascript do?



In order not to get bogged down in the long description of all the paradigms that js supports, all of its capabilities, syntactic constructions and other things, I will give a few small examples. They are obviously not enough for acquaintance with the language, however, they will still help to form a certain idea of ​​the language.

The function can take an arbitrary number of arguments.
function add () {
var sum = 0;

for ( var i = 0; i <arguments.length; i ++) {
sum + = arguments [i];
}

return sum;
}

add (1,1,1,1,1); // returns 5
add (2, 3); // returns 5


The function can be called without any arguments.
function sayMyName (name) {
name = name || "unknown" ;
return 'My name:' + name;
}

sayMyName ( 'David' ); // returns 'My name: david'
sayMyName (); // returns 'My name: unknown'


Function as a first class object
function add (a, b) {
return a + b;
}

function sub (a, b) {
return a - b;
}

function doAction (action) {
return action (2, 1);
}

doAction (add); // returns 3
doAction (sub); // returns 1


Closures
function someAction () {
var firstAction = function () {
return 'Hello,' ;
}

var secondAction = function () {
return firstAction () + 'Habr!' ;
}

return secondAction;
}

var act = someAction ();
act (); // returns 'Hello, Habr!'


OOP with nuances Thank you Iskin
function Food (type) {
this .type = type;
}

var foo = new Food ( 'orange soda' );
var bar = new Food ( 'cheeses' );

foo.type; // returns 'orangeSoda'
bar.type; // returns 'cheeses'


Dynamic change of objects
function Food (type) {
this .type = type;
}

var foo = new Food ( 'orange soda' );
var bar = new Food ( 'cheeses' );

Food.prototype.say = function () {
return 'ORLY! This is' + this .type + '!' ;
}

foo.say (); // returns ORLY! This is orange soda!
bar.say (); // returns ORLY! This is cheeses!


For the language there are a large number of high-quality free libraries supported by many people around the world. The most popular ones are: JQuery , Prototype , Mootools , ExtJs , Yahoo UI . Any of these libraries right now is ready to become the basis for writing the RIA user interface. I apologize to the reader for the lack of description, unfortunately, this is a big topic for a separate article, so I’m citing only the links.

I hope these arguments are convincing enough to consider js an accepted, complete and convenient language suitable for writing RI applications. And now, if the dear reader did not fall asleep, I turn to the description of what the article was about.

AJAX machine


The concept of the pattern: We store all the logic on the server, form the entire interface at the client. The application created by the pattern implements a three-tier architecture . The application is loaded (all the html, css and js code occurs once, during the first access. Thanks to shiko_1st and jodaka



To make it easier for the reader to understand the essence, I will describe it briefly: the client browser makes a request for the application. He is immediately given the only html page, all styles, all the necessary js-code for the application and, possibly, all static graphics.

After loading the wireframe dom model of the document, JavaScript renders the interface; In addition, js manages communications with the outside world through ajax requests. In turn, the server is only engaged in issuing statics and processing ajax requests from the client. Ideally, the server should not be able to write to the output stream anything other than JSON.

The proposed architecture is depicted using the following scheme (depicted by my modest forces, may the reader forgive me):


The diagram has 3 levels, respectively:
  1. Green or Client Level. At this level, the application creates a user interface in the browser, processes user actions, and sends requests to the server. For this level, artists, designers and js-programmers work. Also, at the green level, there may be another server, in case you have opened the API for inter-server communication.
  2. Red or Protocol level. Red color symbolizes a critical area in the development of AJAX-machine - a good format for exchanging data will make the client and server independent of each other, easily distribute the load on several servers, add new features, without architecture modifications. The red level is provided by http (s) transport, the exchange is in the form of JSON packages. JSON was not chosen in vain: firstly, it is more compact in terms of the size of the transmitted data compared to pure XML, and secondly, it is the native data format for js.
  3. Blue or Server Level. The “server” languages ​​work here, as well as the programmers in these languages ​​:) The diagram attempted to depict a general view of a scalable solution, with a query router or (and) a load balancer and several servers. The router is the entry point ( Front Controller ) of the server, it also has to give statics. The blue level is the most flexible in terms of architecture, the level of an AJAX machine. For example, here you can put one very powerful server with FastCGI, or two servers with php, dividing the functionality between them, or in general, dozens of servers with the same functionality with Ruby. For the server, you can choose any language or even several different languages ​​that satisfy the tasks set, given that they will be required to display only the answers in the form of JSON and dynamic graphics, if there is a need for it.


Aspects


In the best traditions of bicycle construction, the reader who still loses interest can be offered a good way of modular division of logic - aspects. An aspect is a logically indivisible process that occurs with your application. To stop abstruse wording, I will give examples of aspects: “Registration”, “News”, “Authorization”, “Messages”. In the ideal case, one aspect should not know anything about the others, interacting only with the database or file system directly. A well-designed structure of aspects and connections between them allows to distribute the most "heavy" aspects of performance to different servers, or (and) allocate one aspect to several servers with load balancing between them.

A very interesting topic to think about, in the context of working with several database servers, however, it goes far beyond the scope of this article, as well as security, unfortunately. Regarding security, I just want to say a commonplace proven in practice: without a clear understanding by the whole team that the client is in the hands of the enemy, and the server is a besieged fortress, it’s better not to start a project without a backup, without a logging mechanism and without a good system administrator. For a large system, in my opinion, it is advisable to keep logs only in the database, but an experienced reader may have his own thoughts, which I hope he will share in the comments.

Database


All modern DBMSs allow writing and executing stored procedures, and the developer of a large system is contraindicated to neglect this possibility. Having developed clear rules for naming procedures and arguments, you can safely shift all heavy queries to the DBMS itself. It is not at all rational and extremely wasteful to receive a huge sample from the database server so that, after additional processing, to transfer three values ​​to the client. I want to assure a respected reader who is not familiar with the pleasures of stored procedures that:

Ajax machine script


JavaScript draws an authorization form for the user, the user enters a username and password, a JSON package of the form is sent to the server:
{
action: 'authorization' ,
status: 'request' ,
options: {
login: 'Vasiliy' ,
pass: '********'
}
}


The packet goes through the network to the router, which, at a minimum, checks the packet for the minimum and maximum allowable sizes and for the number of requests from a node per unit of time (to eliminate brute force). In case everything is good, it sends the data to the “Authorization” aspect (it can be a module, a class, a program, a separate server and something else), for example, in a queue, in the form:
{
action: 'authorization' ,
status: 'in_queue' ,
options: {
login: 'Vasiliy' ,
pass: '********'
},
date_in: '25082008-221500'
}


The aspect accepts data, and arranges its check for compliance of the packet fields with the reference ones. If everything is correct, he authorizes the user Vasiliy with the password ********, and sends the following packet to the client:
{
action: 'authorization' ,
status: 'authorize' ,
options: {
user_name: 'Vasiliy Pomidorov' ,
permission: 'super_user'
},
date_in: '25082008-221500' ,
date_out: '25082008-221501'
}

Js on the client side receives the package, displays some banal message in the form: “Welcome, Vasiliy Pomidorov” and unlocks additional actions for super_user.

All stages are logged strictly. In the case of non-critical problems with the package, such as: incorrect password / login, inaccessibility of some action for this user, etc., an information packet is sent to the client informing about the error:
{
action: 'authorization' ,
status: 'deny' ,
options: {
code: 99 // invalid login or password
},
date_in: '25082008-221500' ,
date_out: '25082008-221501'
}

In the case of a critical problem, for example: flood packages, constant various erroneous requests from a host, etc., more stringent measures should be taken: issue a warning or block an authorized user completely until clarification of circumstances, in extreme cases blocking by ip and subnet mask is applicable (in case of DoS / DDoS attacks).

Epilogue


First of all, thank you, reader, who managed to get through the rows of a little boring, but hopefully useful text - Thank you!

I would like to be sure that this material will really help someone to articulate their thoughts, others will be pushed onto the path of developers of Rich Internet Applications, and may even affect the creator of a brilliant and terribly unique startup (I hope myself)

It’s a pity, but there are a lot of interesting materials outside the article: here’s a comparison of JavaScript and Adobe Flash points, pros and cons of “big” web frameworks for creating RIAs, tacking between SOAP and REST, tasks and problems of creating a scripting system for automatic testing and deploying client js code, centralized use of microformats ...
Many, oh, how many interesting topics can be covered, described, commented out, discarded as useless or adopted, otkholivarit, in the end, on the pages of Habrahabr :) It's up to you, dear reader!

Source: https://habr.com/ru/post/40023/


All Articles