RPC - sloanyang/raspberrry2v8 GitHub Wiki

##RPC (Remote Procedure Call)

Each application runs in it's own isolate. Isolate is an isolated JavaScript environment with it's own heap and GC. To communicate, isolates can use RPC mechanism provided by the kernel. It's built on JavaScript promises.

###Why promises and not callbacks?

  1. Callbacks require at least twice as much RPC traffic. There are 5 packets when using callbacks: call, return, callback call, callback return, callback GCed. The last one is required to notify other side that the callback is no longer exists, so caller can release memory. For promises it's: call and resolve/reject (2 packets). Note: in future it might be possible to RPC over network.

  2. Callback needs to be exported to callee isolate.

  3. Required more memory. Callback could be called more than once. We need to keep it in memory until GC and notify caller when it's no longer used.

  4. Promises are in v8, hopefully, they will be very well optimized.

  5. There is no way to transparently turn synchronous function into asynchronous. Consider this code:

Isolate 1:

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

Isolate 2:

var promise = add(1, 2);

promise.then(function(sum) {

  // outputs "3"
  console.log(sum);
})

Using promises it's possible to RPC any function.

###ArrayBuffers

ArrayBuffer objects are zero-copy transferred (between local isolates on the same machine).

Isolate 1:

var buffer = new ArrayBuffer(128);

function getData() {
  return buffer;
}

// "buffer.byteLength == 0" after getData() call

Isolate 2:

getData().then(function(buffer) {

  // outputs "128"
  console.log(buffer.byteLength);
})

###Functions

It's possible to pass functions as RPC arguments.

Isolate 1:

function foo(name) {
  return "Hello " + name + "!";
}

function getFoo() {
  return foo;
}

Isolate 2:

getFoo().then(function(foo) {

  foo('World').then(function(str) {
    // outputs "Hello World!"
    console.log(str);
  });

})

###Asynchronous function call example

Isolate 1:

function foo() {
  return new Promise(function(resolve) {
    setTimeout(resolve, 2000);
  });
}

Isolate 2:

var promise = foo();

promise.then(function() {

  // outputs "Hello World!" after 2 seconds
  console.log('Hello World!');
})