<?xml version="1.0" encoding="utf-8" ?><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns="http://purl.org/rss/1.0/">
<channel rdf:about="http://www.croczilla.com/blog">
  <title>croczilla/blog</title>
  <link>http://www.croczilla.com/blog</link>
  <description></description>
  <dc:date>2010-04-17T08:34:00Z</dc:date>
  <dc:creator />
<items>
 <rdf:Seq>
    <rdf:li rdf:resource="http://www.croczilla.com/blog/20" />
    <rdf:li rdf:resource="http://www.croczilla.com/blog/19" />
    <rdf:li rdf:resource="http://www.croczilla.com/blog/18" />
    <rdf:li rdf:resource="http://www.croczilla.com/blog/17" />
   </rdf:Seq>
</items>
</channel>
<item rdf:about="http://www.croczilla.com/blog/20">
  <title>Stratified JavaScript in the Oni Rocket Web Server </title>
  <link>http://www.croczilla.com/blog/20</link>
  <description>It's been a while since I blogged about Stratified JavaScript - &quot;an experiment that allows us
to play with some concurrency features in JavaScript in a cross browser way&quot;, as ajaxian.com
explained it. Encouraged by the results of this experiment, I h...</description>
  <dc:subject />
  <content:encoded><![CDATA[<p>
It's been a while since I blogged about Stratified JavaScript - "an
experiment that allows us to play with some concurrency features in
JavaScript in a cross browser way", as <a href="http://ajaxian.com/archives/stratified-javascript-concurrency-features-in-javascript">ajaxian.com explained it</a>.
<p>
Encouraged by the results of this experiment, I have since teamed up
with my ex-Joost colleague Tom Germeau to found a startup, <a href="http://www.onilabs.com">Oni Labs</a>,
where we are taking the "stratified" idea further.
<p>
Our product, "Oni Rocket", is an asynchronous JS web server similar to
<a href="http://nodejs.org/">nodejs</a>, with the big difference that
Rocket can be programmed in a more structured, callback-less
'stratified' way. Like nodejs, we use Google's <a href="http://code.google.com/p/v8/">V8 JS engine</a> under the
hood.
<p>
On top of the web server we've also implemented a web application
framework which uses both client and server-side Stratified JavaScript
to make coding web applications a pure joy. SJS enables things like 
<a href="http://commonjs.org/specs/modules/1.0/">CommonJS's module system</a> on both client and server and makes non-blocking
bi-directional client-server communication very natural and easy. The
framework also includes "Oni Surface", a small JS UI toolkit
implementing cross-platform box layout, but of course everything is
also fully compatible with existing frameworks like <a href="http://jqueryui.com/">jQuery UI</a> or <a href="http://www.extjs.com/">ExtJS</a>.
<p>
It's all still a bit rough around the edges and won't be ready to be
released for another couple of months. In the meanwhile, here is a short video
showing how easy it is to code a little comet chat app in Rocket:
<p>
<object width="640" height="448"><param name="allowfullscreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=10983826&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1"></param><embed src="http://vimeo.com/moogaloop.swf?clip_id=10983826&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&color=00adef&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="640" height="448"></embed></object>
<p>
<a href="http://pc.de/pages/oni-rocket-web-server-be">Belorussian translation</a> provided by <a href="http://pc.de/">PC</a>.
]]></content:encoded>
  <dc:creator>alex</dc:creator>
  <dc:date>2010-04-17T08:34:00Z</dc:date>
</item>
<item rdf:about="http://www.croczilla.com/blog/19">
  <title>Building a Chumby-style feed reader using SJS</title>
  <link>http://www.croczilla.com/blog/19</link>
  <description>Stratified JavaScript (SJS) might still be work in progress, but that doesn't mean it can't be
used for building some (semi-)useful things. Consider e.g. the 'FeedChumby' RSS feed reader
which automatically cycles through the posts of some popular RS...</description>
  <dc:subject />
  <content:encoded><![CDATA[<p>
<img src="http://croczilla.com/~alex/feedchumby.png">
<br clear="all"></p>
<p>
<a href="http://www.croczilla.com/stratified/">Stratified
JavaScript</a> (SJS) might still be work in progress, but that doesn't mean
it can't be used for building some (semi-)useful things.
</p>
<p>
Consider e.g. <a href="http://croczilla.com/~alex/oni/stratified/samples/feedchumby4.html">
the 'FeedChumby' RSS feed reader</a> which automatically cycles through the posts
of some popular RSS feeds, 'slide-show' style - similar to the way in which a <a href="http://www.chumby.com">Chumby</a> cycles through its widget
stream.
</p>
<p>
In this blog post I will dissect the code for this webapp,
tutorial-style.
</p>

<p><b>Accessing feeds</b></p>

<p>
At its core, FeedChumby uses the <a href="http://code.google.com/apis/ajaxfeeds/">Google AJAX Feeds API</a>
which allows us to retrieve RSS feeds without having to worry about
any crossdomain issues and without requiring any server support from
our side. 
</p>
<p>
SJS gives us access to this API through the unassuming function
</p>
<pre>
  Ajax.Google.Feeds.loadFeed(url);
</pre>
<p>
which returns a JSON results object as described in the <a href="http://code.google.com/apis/ajaxfeeds/documentation/reference.html#JSON">Google documentation</a>.
</p>
<p>
Because we're using SJS, we can call this function synchronously - no
callback or other asynchronous construct needed. All the asynchronous
action is automatically choreographed behind the scenes: loading the
Google API if it hasn't been loaded yet, making sure the 'feeds'
module is loaded, and finally loading the actual feed itself. While
all of this is going on, the browser stays perfectly responsive.
</p>
<p>
Coupled with SJS's 'Ajax.DOM.waitForEvent' library function (which -
as one would expect from the name - waits for a particular DOM event),
loading and displaying a feed in response to a button click is then as
easy as this:
</p>
<pre>
  Ajax.DOM.waitForEvent("click", button);
  var result = Ajax.Google.Feeds.loadFeed(feed_url);
  renderResult(result);
</pre>
<p>
Here is a complete example: <a href="http://croczilla.com/~alex/oni/stratified/samples/google-feeds.html">google-feeds.html</a>
</p>
<p><b>Basic program structure</b></p>

<p>
By sticking 'loadFeed' into a loop, iterating over a few different
feeds and over individual feed posts, and pausing for a few seconds
after each post is displayed (using SJS's "hold()" primitive), we've
got the basic structure for our Chumby-style feed reader - again no
asynchronous constructs (like e.g. setTimeout) needed:
</p>
<pre>
  var feeds = [ "...slashdot...", "...digg...", "...elreg...", ... ];

  while (true) {
    for (var i=0; i&lt;feeds.length; ++i) {
      var result = Ajax.Google.Feeds.loadFeed(feed[i]);
      for (var j=0; j&lt;result.feed.entries.length; ++j) {
        renderFeedEntry(result.feed.entries[j]);
        
        hold(10000); // &lt;-- wait 10s before continuing with next post
      }
    }
  }
</pre>
<p>
Let's also add a button that allows the user to shortcut through the
10s waiting time. The easiest way to provide this sort of
functionality is by using SJS's '@' combinator (as described in <a href="http://www.croczilla.com/blog/17">an earlier blog post</a>, "A @ B" executes both A
and B in parallel, and returns as soon as either of them have finished
evaluating; at the same time cancelling the still pending expression): 
</p>
<pre>
  for (...) {
    ...
    hold(10000) @ Ajax.DOM.waitForEvent("click", nextButton);
  }
</pre>
<p>
As a little refinement, we can replace the 'hold(1000)' by code that
will provide the user with some UI feedback during the waiting period:
</p>
<pre>
  function countdown() {
    for (var i=0; i>0; --i) {
      counter.innerHTML = i;
      hold(1000);
    }
  }

  ...

  for (...) {
    ...
    countdown() @ Ajax.DOM.waitForEvent("click", nextButton);
  }
</pre>
<p>
Here is a complete example with the functionality so far: <a href="http://croczilla.com/~alex/oni/stratified/samples/feedchumby.html">feedchumby.html</a>
</p>

<p><b>Adding 'pause' functionality</b></p>
<p>
Again using '@' and 'Ajax.DOM.waitForEvent()', we can modify our
countdown() function to stop counting down while in a paused state:
</p>
<pre>
  var paused = false;

  function countdown() {
    var i=10;
    while (i>0) {
      counter.innerHTML = i;
      if (paused) {
        pauseButton.innerHTML = "Play";
        Ajax.DOM.waitForEvent("click", pauseButton);
        paused = false;
        pauseButton.innerHTML = "Pause";
      }
      (hold(1000), --i) @ 
      (Ajax.DOM.waitForEvent("click", pauseButton), paused=true);
    }
  }
</pre>
<p>
Note the '@' expression here. It combines the two simpler expressions
"(hold(1000), --i)", which waits for 1s and then decrements 'i', and
"(Ajax.DOM.waitForEvent("click", pauseButton), paused=true)", which
waits for a click on 'pauseButton' and then sets the variable 'paused'
to true. (In both 'normal' JavaScript and also SJS, for two expressions
A and B, "A,B" is an expression that means "execute first A and then
B".)
</p>
<p>
Here is the example with the pause functionality rolled in: <a href="http://croczilla.com/~alex/oni/stratified/samples/feedchumby2.html">feedchumby2.html</a>
</p>

<p><b>Adding birectional navigation</b></p>

<p>
To add functionality that allows the user to navigate back to the
previous post, we need to change our loop logic a little bit to
account for the situtation where we're moving past the beginning of a
feed to the previous feed. The gory details are here: <a href="http://croczilla.com/~alex/oni/stratified/samples/feedchumby3.html">feedchumby3.html</a>. 
</p>
<p>
Note the '@' expression in the main loop:
</p>
<pre>
  (countdown(), ++j) @ 
  (Ajax.DOM.waitForEvent("click", "next"), ++j) @
  (Ajax.DOM.waitForEvent("click", "previous"), --j);
</pre>
<p>
Previously we only waited for the countdown to finish or for the user
to click on the 'next' button. Now we're also waiting for clicks on
the 'previous' button, and we're incrementing/decrementing variable
'j' to communicate the direction of navigation.
</p>

<p><b>More embellishments</b></p>
<p>
The absence of any asynchronous constructs (callbacks, setTimeouts,
...) makes the code quite modular. It's easy to add little features
here and there without having to take a "global view" of the
application, and the '@' combinator relieves us from a great deal of
manual bookkeeping.
</p>
<p>
The final version of the FeedChumby adds a couple more small touches,
like e.g. an animated pause button, and it contains some CSS to make
the application more presentable:
<a href="http://croczilla.com/~alex/oni/stratified/samples/feedchumby4.html">feedchumby4.html</a>
</p>
<p>
I think FeedChumby is a pretty good example of the power of SJS for writing
Ajax-style applications. The real win, however, will only show in big
'mashup' style applications that access several different APIs
concurrently. Expect to see more demos coming along with APIs such as
the Google Translation API, Google Contacts, Facebook Connect, and others.
</p>
]]></content:encoded>
  <dc:creator>alex</dc:creator>
  <dc:date>2009-09-25T12:41:00Z</dc:date>
</item>
<item rdf:about="http://www.croczilla.com/blog/18">
  <title>Stratified JavaScript and Multitasking</title>
  <link>http://www.croczilla.com/blog/18</link>
  <description>In response to my earlier blog post on Stratified JavaScript, Jonathan Cook asked an
interesting question: &quot;[...] I am very interested in using SJS to eliminate the blocking
nature of heavy computation in nested loops. A hold(0) would seem to do this...</description>
  <dc:subject />
  <content:encoded><![CDATA[<p>
In response to my earlier blog post on Stratified JavaScript, Jonathan
Cook asked an interesting question:
</p>
<pre>
"[...] I am very interested in using SJS to eliminate the blocking
nature of heavy computation in nested loops.

A hold(0) would seem to do this, or perhaps a different method for
this purpose would be appropriate?"
</pre>
<p>
The short answer is, you don't need to call hold() or do anything
special at all. Just code your computation as you would in 'normal'
JavaScript, and SJS will take care of the rest; the UI will
automatically stay responsive while your computation is chugging
along.
</p>
<p>
Now for the slightly longer answer.
</p>
<p>
The SJS runtime contains a scheduler which preemptively schedules the
different strands of execution ('strata') of an SJS program. This
scheduler automatically yields control to the browser every so often,
and it ensures that individual strata get a fair timeslice. 
</p>
<p>
In other words, SJS implements a form of <i>preemptive multitasking</i>,
rather than <i>cooperative multitasking</i>. There is no need to manually
yield control like you would in e.g. Narrative
JavaScript/Strands; SJS automatically does it in the background.

<p>
Here's an example of a heavy computation in SJS; a program to calculate a
few hundred digits of Pi:
<br>
<a href="http://croczilla.com/~alex/oni/stratified/samples/pi.html">pi.html</a>
</p>
<p>
There are a couple of noteworthy things about this program:
</p>
<p>
Firstly, if you look at the source, there is no hold() or any other
special SJS primitive. It is just 'straight' JS code, which is being
preprocessed through the SJS compiler by virtue of sitting in a script
tag with type "text/sjs".
</p>
<p>
Secondly, it runs painfully slow. This is a consequence of the fact
that the SJS compiler doesn't perform any optimizations at all at this
point; every JavaScript function call or operator application is
converted into a potential yielding point, adding huge overhead to
programs which are heavy on mathematical calculations.
</p>
<p>
This situation will improve dramatically when we get around to making
the compiler smarter. A similar optimization in 
<a href="http://www.croczilla.com/oni">Oni</a> resulted in a 2 orders of magnitude improvement! 
</p>
<p>
In the meanwhile there is a workaround though: SJS code can freely
call 'normal' JavaScript code, so we can just move critical inner
loops into 'normal' JavaScript, as in this modified program:
<br>
<a href="http://croczilla.com/~alex/oni/stratified/samples/pi-faster.html">pi-faster.html</a>
</p>
<p>
You'll notice that this program runs <i>a lot</i> faster, while not
really adding much complexity - just one inner loop has been moved to
'straight' JavaScript. 
</p>
<p>
Just to prove that the preemptive scheduler works as advertised, here
are another couple of examples which add some SJS-specific features.
</p>
<p>
Firstly, this program adds an animation running in parallel to the Pi calculation: 
<br>
<a href="http://croczilla.com/~alex/oni/stratified/samples/pi-and-animation.html">pi-and-animation.html</a>
</p>
<p>
Secondly, and finally, this program adds a 'UI' for turning the animation on and off:
<br>
<a href="http://croczilla.com/~alex/oni/stratified/samples/pi-and-animation-and-events.html">pi-and-animation-and-events.html</a>
</p>
<p>
Take a look at the animation loop:
<p>
<pre>
  function animateLoop() {
    var elem = document.getElementById("toggle_animation");
    while (true) {
      waitForEvent("click", elem);
      elem.innerHTML = "Stop animation";
      animate() @ waitForEvent("click", elem);
      elem.innerHTML = "Restart animation";
    }
  }
</pre>
</p>
Isn't it beautiful? :-)
</p>
]]></content:encoded>
  <dc:creator>alex</dc:creator>
  <dc:date>2009-09-10T16:52:37Z</dc:date>
</item>
<item rdf:about="http://www.croczilla.com/blog/17">
  <title>Introducing Stratified JavaScript</title>
  <link>http://www.croczilla.com/blog/17</link>
  <description>Here's a sneak preview of a project I've been working on in my spare time for a while, and which is
nearing its first release: 'Stratified JavaScript' ('SJS') is a cross-browser extension to
JavaScript which adds some concurrency features to the lang...</description>
  <dc:subject />
  <content:encoded><![CDATA[<p style="background-color:yellow">This blog post is quite old now. Please see <a href="http://stratifiedjs.org">stratifiedjs.org</a> for more up-to-date information about SJS</p>
<p>
Here's a sneak preview of a project I've been working on in my spare
time for a while, and which is nearing its first release:
</p>
<p>
'Stratified JavaScript' ('SJS') is a cross-browser extension to
JavaScript which adds some concurrency features to the
language. Without going into too much detail, the main features
include:
</p>
<p>
<b>(1) The ability to pause execution</b>
</p>
<p>
The function
</p>
<pre>
  hold(time_ms);
</pre>
<p>
pauses execution of a piece of code for time_ms milliseconds. E.g.:
</p>
<pre>
  var elem = document.getElementById("animated_element");
  var x = 0;
  while (true) {
    elem.style.left = x; 
    x = (x + 10) % 200;
    hold(100);
  }
</pre>

(full sample: <a href="http://croczilla.com/~alex/oni/stratified/samples/animate.html">animate.html</a>)

<p>
Note that 'hold' doesn't busy wait. The browser's UI stays fully
functionally while this code executes.
</p>

<p>
<b>(2) Fork-Join Parallelism</b>
</p>

<p>
In conventional JavaScript, arguments to function calls are evaluated
sequentially. In Stratified JavaScript, they are evaluated concurrently:
</p>

<pre>
  function animate(elemname, duration_ms, step_ms) {
    var elem = document.getElementById(elemname);
    var start_time = new Date();
    var x = 0;
    do {
      elem.style.left = x;
      x = (x + 10) % 200;
      hold(step_ms);
    } while (duration_ms > new Date() - start_time);
  }

  function par(a, b) {
    alert("all done");
  }

  par(animate("animated_element_1", 10000, 100),
      animate("animated_element_2", 7000, 80));
</pre>

(full sample: <a href="http://croczilla.com/~alex/oni/stratified/samples/forkjoin.html">forkjoin.html</a>)

<p>
Here, the two 'animate' calls are being executed concurrently. Once they
both return, the body of 'par' gets called.
</p>

<p>
<b>(3) Exploratory parallelism</b>
</p>

<p>
Many concurrency problems fit into the pattern 
</p>

<p>
"Explore options a,b,c,... concurrently. Once one of them yields a satisfactory
result, return it and abort exploration of the remaining options."
</p>

<p>
Exploratory parallelism in Stratified JavaScript is embodied by the
'@' ('alt', 'alternatives') operator:
</p>

<pre>
  animate("animated_element_1", 10000, 100) @ 
  animate("animated_element_2", 7000, 80);

  alert("all done");
</pre>

(full sample: <a href="http://croczilla.com/~alex/oni/stratified/samples/alt.html">alt.html</a>)

<p>
This code pops up 'all done' after 7s (after the animation of
animated_element_2 has finished).  At the same time, the animation of
animated_element_1 will be aborted.
</p>

<p>
In many ways, exploratory parallelism forms the heart of Stratified
JavaScript. It is applicable to many situations which are very
cumbersome to express in conventional thread-based parallelism.
</p>

<p>
<b>(4) Suspend/Resume</b>
</p>

<p>
Most JavaScript programs live by asynchronous events, e.g. events
generated by button clicks, or asynchronous
XMLHttpRequests. Stratified JavaScript contains a generic mechanism
for converting these asynchronous constructs into synchronous ones:
</p>

<pre>
   suspend {
     ... resume() ...
   }
   retract {
     ...
   }
   finally {
     ...
   }
</pre>

<p>
This will be executed by first evaluating the code in the 'suspend'
block and then suspending execution.  Execution will resume when the
'resume' function defined in the suspend block is called. The optional
'retract' block will be executed if the current code is aborted before
'resume' was called. The optional 'finally' block will be executed in
either case; if execution was resumed, or if execution was aborted.
</p>

<p>
E.g., this is how an event listener could be 'synchronized':
</p>

<pre>
  function waitForEvent(event, elem) {
    suspend {
      var rv;
      var listener_func = function(e) {
        rv = e;
        resume();
      };
      elem.addEventListener(event, listener_func, false);
    }
    finally {
      elem.removeEventListener(event, listener_func, false);
    }
    return rv;
  }
</pre>

<p>
With this function we can now e.g. wait for a button click:
</p>

<pre>
  while (true) {
    waitForEvent("click", document.getElementById('button1'));
    alert("You clicked the button");
  }
</pre>

(full sample: <a href="http://croczilla.com/~alex/oni/stratified/samples/suspend.html">suspend.html</a>)

<p>
Or something more complicated:
</p>

<pre>
  function dump(message) {
    document.getElementById("output").innerHTML = message;
  }

  while (true) {
    var e = waitForEvent("click", document.getElementById('button1')) @
            waitForEvent("click", document.getElementById('button2')) @
            hold(5000);
    if (e)
      dump("You clicked button '"+e.target.id+"'");
    else
      dump("Click a button already!");
  }
</pre>
(full sample: <a href="http://croczilla.com/~alex/oni/stratified/samples/suspend2.html">suspend2.html</a>)

<p>
If all of this sounds similar to <a href="http://www.croczilla.com/oni">Oni</a>, that's because it is. Under the hood, Stratified JavaScript is executed by a runtime based on Oni. 
Everything that can be expressed in Stratified JavaScript can be written directly in Oni without going through any compilation stage. The advantage of Stratified JavaScript is that
it doesn't have the awkward functional syntax of Oni. 
</p>
]]></content:encoded>
  <dc:creator>alex</dc:creator>
  <dc:date>2009-08-27T19:25:53Z</dc:date>
</item>
</rdf:RDF>
