Yohanes Mario [dot] com

my online scrapbook of scrambled thoughts

JavaScript is a confusing language. You can do OOP with it, you can do functional programming with it, and so on. A typical and modern way of encapsulating things in javascript is by creating an object. Objects in javascript are defined by a JSON notation (a single object throughout the runtime) or by creating what's known as a constructor function:

function Creature(legs) {
    this.legs = legs; // This is a public attribute

    this.speak = function(){ // This is a public method
        console.log("Hi!");
    };
}

var person = new Creature(2);
person.speak(); // console: Hi!

However, you don't have private or public modifiers in javascript. Everything added to this will result as a public member of that object. So, how do we create private members? The answer: closure. Closure is a concept in javascript which states that anything defined inside a closure (those curly braces) will stay inside it. Nothing from outside of the closure can access anything that's defined inside of the closure. So, we can make:

function Creature(legs) {
    this.legs = legs; // This is a public attribute
    var sound = "Hi!"; // This is a private attribute
    
    var makeSound = function(){ //This is a private method
        console.log(sound);
    };

    this.speak = function(){ // This is a public method
        makeSound();
    };
}

var person = new Creature(2);
person.speak(); // console: Hi!

I exploited this behavior to make sure that no one can mess with the internal states of my web applications by doing this:

$(document).ready(function(){
    // The rest of your code goes here
});

That way, no external javascript can mess with my internal states. The lesson is, never define your application states as globals, always use closure, be it in an object, or as simple as inside of an initial function. As always, happy blogging!

   Posted in Web        Yohanes Mario Chandra        0 Comments

While trying to create a simple web-based desk clock, I notice that not all computers are made equal in regards to the way they sync time. Since then, I've been trying to create a simple HTTP and JSON based ntp server to sync all of my clocks. The result is as follows:

var start = (new Date()).getTime();
$.ajax({
    url: 'http://time.yohanesmario.com/ntp',
    type: "GET",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
        var end = (new Date()).getTime();
        var responseTime = end-start;
        if (data!=null && data.milliseconds_since_epoch!=null) {
            var time = parseInt(data.milliseconds_since_epoch);
            
            // Calibrate ntp time
            time = time + (responseTime/2);
            
            // Calculate offset
            offset = end-time;
        }
    }
});

Notice that I add half of the response time to the time obtained from the NTP. This is because HTTP as a protocol consist of 2 part, request and response, each took half of the total time. And then, there is TLS.

TLS (more widely known as SSL or HTTPS) works very differently. It, under normal circumstances (TLS 1.2), took 2 round trip handshake before the actual HTTP protocol begin. So, in total, it took 3 round trip to complete an HTTPS request. That's why, the actual time it took for the HTTP response to actually reach the client is responseTime/6. We change our original code accordingly:

var start = (new Date()).getTime();
$.ajax({
    url: 'https://time.yohanesmario.com/ntp',
    type: "GET",
    cache: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data) {
        var end = (new Date()).getTime();
        var responseTime = end-start;
        if (data!=null && data.milliseconds_since_epoch!=null) {
            var time = parseInt(data.milliseconds_since_epoch);
            
            // Calibrate ntp time
            time = time + (responseTime/6);
            
            // Calculate offset
            offset = end-time;
        }
    }
});

This may help you, or may not. Either way, happy blogging!

   Posted in Web        Yohanes Mario Chandra        0 Comments

I've been relying on Apache and PHP for a very long time, and they have served me well. However, they do have disadvantages, and I feel that I need to keep up with new technologies in order to further my knowledge. Apache is built with old paradigms to handle concurrency, it uses one thread per connection. Thread is expensive, especially for a constrained environment like a web server. So, when there's another platform which offer high concurency with a fixed size of thread pool, I'm sold.

Enter NGINX (read: engine-x). It uses a limited size of thread pool, so it will never create unlimited number of threads. It uses a non-blocking model instead of the traditional blocking model which Apache uses (which is why they need one thread per connection in the first place). The only disadvantage it has is the lack of support compared to Apache. To use php on NGINX, you need to go the extra mile. But PHP is also reliant on old paradigms. It's still based on a file system structure, it still use one thread per execution of a script (which negates the benefit of NGINX), and it's painfuly slow. So, now what?

This is where Node.js comes in. Node.js is basically javascript which you can run on the server. Imagine that. You can have practically the same language for both client and server. And it also use non-blocking model, just as an added bonus. Granted, it only use a single thread to run everything, but it still performs better than PHP which uses multi-thread, and you still can run multiple Node.js worker processes if you really need to scale further. Mind-blown.

So, yes, I just recreated my blog engine from scratch using Node.js. And it took me significantly less time than if I were to recreate this blog using PHP from scratch. Node.js is that easy to use, if you consider javascript as an easy language. I certainly am.

That's all. As always, happy blogging!

   Posted in CMS        Yohanes Mario Chandra        0 Comments