Code Samples from Practical Functional JavaScript 4

Posted by Oliver on October 02, 2008

The code samples from my talk at the Ajax Experience conference are now available here.

Each example runs itself when you load its page, at least in Safari and Firefox. This is something I first did for my talk at LL2. It’s the only way I’ve ever been able to keep sample code actually working1.

The full slide deck (including these code samples, but without the comments and the ability to run the code) is here.

These are from the final draft of the talk, but they’re really the first draft of this material. The audience was great, and I learned a lot about how to explain this from their questions during the presentation. I’m planning to reorganize and expand this the next time I get a free weekend to work on it.


1 A funny story about that: John Resig asked me after the talk whether I’d looked at Learn JavaScript. The truth is, I’d wanted to get by without any fancy slideware or sample scaffolding at all, but I needed a way to get formatted code into Keynote. I started out using a technique that Scott MacVicar came up with, and eventually added section breaks, and then “Previous” and “Next” buttons, until I’d eventually feature-creeped my way up to something pretty similar to John’s tool. Oh well.

Practical Functional JavaScript 2

Posted by Oliver on September 24, 2008

I’ll be giving a talk next Wednesday October 1 at The AJAX Experience, on “Practical Functional JavaScript”. This could be subtitled “distributing JavaScript across time and space”, or maybe just “how to do things with functions”1.

A couple of years ago I found that all the interesting AJAX programs that I wanted to write involved asynchronous communication with the server (or sometimes with a Flash plugin, or sometimes within the client but with a few seconds or minutes delay). Trying to think about and debug these programs made me feel like I was just learning how to program again (or hadn’t yet), and hurt my head. But now I can emerge, sadder but wiser, head fully healed, and with this talk in hand.

I’ll be covering:
  • Talking REST asynchronously to your server — without dipping into bleeding-edge technologies such as Comet and Bayeux.2
  • Deferred execution and lightweight multithreading without Google Gears. [3]
  • Messaging between the Flash and the HTML within a page. I’ll put this last so that if you aren’t interested in Flash you don’t have to worry about when to wake up.

This talk is really the flip side of functional javascript and sequentially. Those were non-production experiments to take functional javascript to an extreme. “Practical”, on the other hand, will be about real-world techniques I’ve used to write web sites such as Browsegoods, FanSnap, Style&Share, and the goWebtop Calendar, and that resulted in some of the JavaScript-related libraries here.

The main purpose of this talk is to be useful to practicing developers. But it should also be fun. AJAX lets you do a lot on the web that’s fun to look at and use. It can be fun to program too, and I’d like to get some of that across.

If you’re interested in the type of things I’ve posted here, but found that those zoomed through the material too quickly or that you wanted to see more of a connection to real-world production programming, then this is the talk for you.

The bad news: It’s at 8am. I promise not to think badly of you if you take a nap, and to make loud noises when it’s time for you to go your next talk.

Update: A draft of the talk is here. It doesn’t include most of the code samples.

Update 2: The final version with screenshots of all the code is here. I’ll publish a runnable version of the examples soon.

Update 3: The runnable examples are here.


1 With a nod to Austin — but you don’t have to get that, if you aren’t a linguistics geek.

2 COMET and Bayeaux are cool, but the server-side support can be scary.

3 Another cool technology, but for the typical occasional-use consumer-facing site, you can’t count on it.

jQuery Profile Plugin 1

Posted by Oliver on May 01, 2008

Yesterday I was profiling a page that used jQuery. The page took a long time to initialize. Firebug Profile (a great tool) told me that the time was in jQuery, but that wasn’t much help — the page initialization code had a lot of calls to jQuery, to bind functions to various page elements, and most of them were harmless.

Hence, jQuery.profile. Stick this in your page, call $.profile.start() to start profiling calls to $(selector), and then $.profile.done() to stop profiling and print out something like this:

Selector                 Count  Total  Avg+/-stddev
script, script, scri...    100    101ms  1.01ms+/-1.01
script                   200     58ms  0.29ms+/-0.53
html body #output        100     55ms  0.55ms+/-0.74
script, #output          100     54ms  0.54ms+/-0.73
#output                  100      6ms  0.06ms+/-0.24

Or just include ?jquery.profile.start query parameter in your page URL to begin profiling automatically as soon as the plugin is loaded.

The repository is on GitHub, so you can can comment here or fork it from there if you’ve got something to say.

A Mock for {set,clear}{Timeout,Interval}

Posted by Oliver on April 20, 2008

Here’s a potential JSSpec spec for Sequentially.trickle.map:

describe('Sequentially.trickle.map', {
  'should apply to all the elements': function() {
    Sequentially.trickle.map(
      ['a', 'b', 'c'],
       function(x) { return x + 1 },
       1,
       function(result) {
         value_of(result.join(',')).should_be('a1,b1,c1');
       });
    });
  }
});

This doesn’t work. The problem is that Sequentially.trickle.map is asynchronous (it defers most of its computation — including the invocation of the callback — via setTimeout). This means that should_be isn’t called until after the spec has returned. If it succeeds, this isn’t a problem, but if it fails, JSSpec can’t associate it with the failing spec — worse, JSSpec will have already have marked it successful.

Here’s the version that I actually used:

describe('Sequentially.trickle.map', {
  'should apply to all the elements': function() {
    withMockTimers(function() {
      Sequentially.trickle.map(
        ['a', 'b', 'c'],
         function(x) { return x + 1 },
         1,
         function(result) {
           value_of(result.join(',')).should_be('a1,b1,c1');
         });
      });
    }
});

withMockTimers temporarily replaces setTimeout and friends with its own deferred execution system, so that it can make sure to call them all before it returns. Get it here.

Limitations

This approach has its limits. It doesn’t mock new Date to pretend that more time has passed, so whether it works or not will depend on how your code uses the timers (if it keeps an interval running or re-submitting a timeout until an amount of time measured on new Date has passed, it will probably get a “script running slowly” error). And, I don’t know how kosher it is to replace setTimeout — this let me test against Firefox 2.0 and Safari 3.1; I haven’t tried on Opera and MSIE. Nonetheless, it got me what I wanted here — unit tests for the new methods in Sequentially.

(I’ve got a more involved implementation that patches the test suite to run callbacks within an emulation of the dynamic scope of the original test function, but it’s tricky, and I haven’t got it integrated with JSSpec — or any other browser JavaScript implementation — yet.)

Conquering the Busy Cursor with Sequentially

Posted by Oliver on April 20, 2008

What’s wrong with this function? (Hint: it’s meant to execute periodically on a JavaScript page.)

function updateExpirationText() {
  var now = new Date;
  products.forEach(function(item) {
    var expiresDate = item.expiresDate || Date.parse(item.expires),
        remaining = expiresDate - now,
        text = remaining < 0 ? 'expired' : msToDuration(remaining);
    $('item-' + item.id + ' .time-remaining').text(remaining);
  });
}

It’s a trick question. Maybe nothing’s wrong. But if products can get very long, or if the msToDuration is very slow, you’ve locked up the UI for a long time. At best, this makes for sluggish response; at worst, the page that contains this will trigger a “script running slowly” error, and the user will likely abort all the JavaScript on the page.

If this computation only needs to run once, and when (or before) the page loads, you can do it on the server. But often a computation depends on some aspect of the client state, that isn’t known when the page is requested. In this example, the computation depends on the current time (and the current time keeps changing). In another case, the computation might depend upon the values of some controls or other widgets on the page — if we’ve gone all AJAXy, and want to show the user an instant response, even if that means some client-side computation.

Here’s an alternative to the function above, that doesn’t lock up the page. It uses Sequentially.trickle.forEach, a new function in Sequentially. This function walks its second argument over some span of the first argument — up until 250ms has passed, in this case — and then sleeps for a frame (via setTimeout) before waking up to walk over the next span, until all is done. This gives time back to the browser (and to other setTimeout and setInterval threads), and avoids the “script running slowly” error. Note the one-line change: "products.forEach("” becomes "Sequentially.trickle.forEach(products,".

function updateExpirationText() {
  var now = new Date;
  Sequentially.trickle.forEach(products, function(item) {
    var expiresDate = item.expiresDate || Date.parse(item.expires),
        remaining = expiresDate - now,
        text = remaining < 0 ? 'expired' : msToDuration(remaining);
    $('item-' + item.id + ' .time-remaining').text(remaining);
  }, 250);
}

Sometimes you need to run some code after the iteration is done. In other words, sometimes you need to transform a function that looks like this:

  var startTime = new Date;
  array.forEach(function(item) { ... });
  console.info(new Date - startTime, 'elapsed');

(Here, the code that runs after the iteration just reports how long the iteration took.)

You can do that with a continuation function (or callback), the same as you would with an AJAX request:

  var startTime = new Date;
  Sequentially.trickle.forEach(array, function(item) { ... }, 250, k);
  function k() {
    console.info(new Date - startTime, 'elapsed');
  }

JavaScript being lexically scoped, you can refer to all the same variables from a nested function (@k@).

There’s a Sequentially.trickle.map too. Since the return value can’t contain the function application results yet when the function returns, you have to get them back from the callback. Before (the synchronous version):

  var results = array.map(function(item) { ... });
  console.info('Results:', results);

and after (asynchronous):

  var startTime = new Date;
  Sequentially.trickle.map(array, function(item) { ... }, 250, k);
  function k(results) {
    console.info('Results:', results);
  }

JCON: Ruby Gem for JSON type conformance

Posted by Oliver on April 17, 2008

JCON (the JavaScript Conformance gem) tests JSON values against ECMAScript 4.0-style type definitions
(PDF) such as string?, (int, boolean), or [string, (int, boolean), {x:double, y:double}?].

Usage

type = JCON::parse "[string, int]"
type.contains?(['a', 1])     # => true
type.contains?(['a', 'b'])   # => false
type.contains?(['a', 1, 2])  # => true

JCON also defines an RSpec matcher, conforms_to_js:

[1, 'xyzzy'].should conform_to_js('[int, string]')
[1, 2, 'xyzzy'].should_not conform_to_js('[int, string]')  # 2 isn't a string
{:x => 1}.should conform_to_js('{x: int}')

Use JCON together with the JavaScript Fu Rails plugin to test the argument values to functions in generated JavaScript:

# this will succeed if e.g. response contains a script tag that includes
#   fn("id", {x:1, y:2}, true)
response.should call_js('fn') do |args|
  args[0].should conform_to_js('string')
  args[1].should conform_to_js('{x:int, y:int}')
  args[2].should conform_to_js('boolean')
  # or:
  args.should conform_to_js('[string, {x:int, y:int}, boolean]')
end

Whence

Github for the sources.

Rubyforge for docs.

gem install jcon to install.

License and version

MIT License, of course.

JCON is at version 0.1 because it’s just a few days old and I had to guess about the ECMAScript 4.0 type syntax from the examples in the overview. I can’t imagine that I got everything right.

Three Small JavaScript Libraries 3

Posted by Oliver on April 15, 2008

Three small libraries, that I carry with me from project to project:

Fluently — Construction Kit for Chainable Methods

With Fluently, you can do this:

    var o = Fluently.make(function(define) {
      define('fn1', function() {console.info('called fn1')});
      define('fn2', function() {console.info('called fn2')});
      define('fn3', function() {return 3});
    });

to define an object with chained methods, that can be invoked thus:

  o.fn1().fn2() // calls fn1 and then fn2
  o.fn2().fn1() // calls fn2 and then fn1
  o.fn1().fn3() // returns 3 (an explicit 'return' breaks the chain)

You can also define modifiers, and aliases:

    var o = Fluently.make(function(define) {
      define('fn1', function() {console.info('called fn1')});
      define('fn2', function() {console.info('called fn2')});
      define.empty('and');
      define.alias('fn3', 'fn1');
      define.modifier('not');
    });
 
  o.fn3(); // same as o.fn1()
  o.fn1().and.fn2() // same as o.fn1().fn2()
  o.fn1().and.not.fn2() // options.not is set when fn2 is called

I used this to build a mock and spec construction kit. I don’t use Fluently to define the mocks; I use it to define the methods that define the mocks. Doing all this in one library made my head hurt, so I factored this part of it out.

Git Fluently from here.

MOP JS

MOP JS defines utilities for JavaScript metaprogramming. You don’t think you need it until you try asynchronous programming, where some methods don’t have enough information to operate until the response to another method’s asynchronous request have returned.

  MOP.delegate(target, propertyName, methods)

For each name in methods, defines a method on target with this
name, that delegates to the method of the propertyName property
of target with the same name.

  new MOP.MethodReplacer(object, methods)

When a new MethodReplacer is constructed, it replaces each method
on object by the method in methods with the same key value, if
such a method exists. A MethodReplacer has a single method,
restore, which restores each method to its pre-replacement
value.

  new MOP.QueueBall(object, methodNames)

When a new QueueBall is constructed, it replaces each method named
by methodNames with a method that enqueues the method call (the
name of the method and its arguments). A QueueBall has a single
method, replayMethodCalls, which plays back the method calls and
restores the methods.

  MOP.withMethodOverridesCallback(object, methods, fn)

Calls fn on object, within a dynamic scope within which the
methods in methods have temporarily replaced the like-named
methods on object. The scope is terminated by the argument to
the call to fn; this argument should be treated as a
continuation, and restores the methods.

  MOP.withDeferredMethods(object, methodNames, fn)

Calls fn on object, within a dynamic scope within which the
methods in methodNames have been enqueued. The scope is
terminated by the argument to the call to fn; this argument
should be treated as a continuation, and ends the queue, replaying
the methods.

See the specs for examples; git MOP JS from here.

Collections JS

Finally, the Collections library defines framework-independent JavaScript collection methods, for use in browser JavaScript and in ActionScript / OpenLaszlo. There are many libraries like this; this one is mine.

The Array and String methods extend the class prototype; the Hash methods use a proxying wrapper to avoid prototype pollution. The methods with the same names as the ECMAScript 1.6+ extensions have the same spec as those; the ones with the same name as prototype extensions have the same spec as those in the Prototype library; and there’s a few odds and ends such as String#capitalize.

I use this when I don’t want the overhead of Prototype, or want to use these functions in an environment that Prototype doesn’t run on, such as OpenLaszlo. It has some overlap with Functional, but isn’t nearly so radical — this can be an advantage.

Git Collections JS from here.

JavaScript Fu Rails Plugin 3

Posted by Oliver on April 14, 2008

JavaScript Fu extends Rails with a few facilities to better integrate JavaScript into Rails development:

1. The notes and statistics rake tasks compass JavaScript files in the public/javascript directory:

$ rake notes
public/javascripts/controls.js:
  * [782] [TODO] improve sanity check
$ rake stats
| Name                 | Lines |   LOC | Classes | Methods | M/C | LOC/M |
[...]
| JavaScript           |  7287 |  6322 |       0 |       0 |   0 |     0 |
[...]

2. The call_js RSpec matcher asserts that a string or response contains a script tag, that contains JavaScript that calls the named function or method:

response.should call_js('fn')
response.should call_js('fn(true)')
response.should call_js('gApp.setup')

If you pass a block to call_js, it’s called back with the argument list, parsed as though it were a JSON array:

# matches <script>fn(1, 'aString', {x:10,y:20})< /script>
response.should call_js('fn') do |args|
  args[0].should == 1
  args[1].should == 'aString'
  args[2].should == {:x => 10, :y => 20}
end

Use this with jcon to test for type conformance, using ECMAScript 4.0 type definitions. (Well, you can’t use it with jcon yet, because I haven’t released it — this is just a teaser. But you can peek.)

response.should call_js('fn') do |args|
  args[0].should conform_to_js('[Array, (int, boolean)]')
  args[1].should conform_to_js('{x: double, y: double}')
  # or just:
  args.should conform_to_js('[[Array, (int, boolean)], {x: double, y: double}]')
end

3. The page.onload page generator method generates code that executes the content
of the block upon the completion of page load:

page.onload do
  page.call alert', 'page loaded!'
end

These lines generate one of these (depending on whether the jRails plugin has been loaded):

Event.observe("window", "load", function() { alert("page loaded!"); });
$(document).ready(function() { alert("page loaded!"); });

Gitting It

JavaScript Fu is hosted on git. If you have git installed, you can clone it into your Rails directory thus:

git clone git://github.com/osteele/javascript_fu.git vendor/plugins/javascript_fu

If you’re running off Edge Rails (or, presumably, Rails > 2.0.2), you should be able to do this instead:

script/plugin install git://github.com/osteele/javascript_fu

Otherwise, you can simply download the tarball from here.

Update: changed the conform_to_js example so that it actually works with the (albeit unreleased) plugin..

FlashBridge: proxying Flash <-> OpenLaszlo

Posted by Oliver on April 13, 2008

I’ve updated my OpenLaszlo utility grab-bag to make browser <-> applet communication even easier. How easy?

Proxies

Put this in your browser JavaScript:

var gObject = {
  f: function() { console.info('gObject.f', arguments) },
  g: function() { console.info('gObject.g', arguments) }
};

And this in an OpenLaszlo applet:

var gObject = FlashBridge.createRemoteProxy('gObject', ['f', 'g']);
gObject.f(1, 2);
gObject.g(3);

When you run the applet code, it prints this to the browser console:

gObject.f [1,2]
gObject.g [3]

That’s right, Flash is invoking the function calls, but they’re executing in the browser.

Now switch these around — put the first block in the applet, and the second block in the browser JavaScript — and it still runs the same way, except that it’s the browser that invokes the functions, and they run in the applet (and print to the OpenLaszlo debug console, if the applet was compiled with debugging on).

(By the way, the full sources for the examples are here.)

Return Values

Callbacks, or continuations for return values, make it easy for the applet to operate on the return value from a call into the browser, even though these calls are asynchronous.

Put this in the browser:

var gService = {
  add: function(a, b) {
    logCall('gBrowserObject.add', arguments);
    return a+b;
  },
  error: function(msg) {
    logCall('gBrowserObject.error', arguments);
    throw msg;
  }
};

And this in the applet:

gBrowserObject.add(1, 2).onreturn(function(value) {
  console.info('1 + 2 -> ' + value);
});
gBrowserObject.error('error msg').onexception(function(value) {
  console.info('error !> ' + value);
});

The argument to onreturn is called (asynchronously) with the return value. The argument to onexception is called with the message from the exception, if an exception occurred.

Callbacks, unlike proxies, only work one direction — for calls from the applet to the browser. That’s not for a technical reason — I’ve just only needed it one direction so far.

Call Storage

Browser code can call into the applet even if the applet hasn’t initialized yet, and vice versa.

To implement this, each side of the bridge stores calls (and return value handlers) in a mailbox until it hears back that the other side has loaded. Once this happens, the mailboxes are flushed and the remote call methods switch to direct invocation.

This works around a couple of race conditions. First, the applet won’t generally have run its initialization code by the time the browser receives its load event, so a naive implementation of the bridge wouldn’t allow the browser to make calls into the applet until the browser had heard back that the applet had loaded — which is hard to detect. (It isn’t enough to wait for the object’s onload event, because this can trigger before the first frame of the movie plays, so the applet may still not have initialized enough to receive messages.) Conversely, depending on your page organization and initialization raindance, the applet might load before page side has registered — so the applet couldn’t call into the page until an unknown time.

Security Implications

FlashBridge, by default, allows the browser to call anything sitting in the applet, and vice versa. This increases the attack surface of your application, because it allows an embedded Flash applet to invoke any part of it. This means that an XSS can tunnel through your applet to gain access to any site with a crossdomain.xml file that allows your applet to connect to it — something that XSS on a pure JavaScript page can’t do.

It you prefer not to audit your application against this, you can call FlashBridge.secure to prevent it from accepting arbitrary calls, and then FlashBridge.register to register callins.

There’s no lockdown facility in the other direction — to lock down the browser JavaScript against calls from the Flash application. That’s because it’s trivial for a Flash application to invoke arbitrary JavaScript in the browser context — in fact, that’s how the applet -> browser communication is implemented, and if that were secured at the FlashBridge layer, the vulnerability would still be accessible one layer down.

Gitting It

All this is in the LzOsUtils project on GitHub, with examples here. Download it via the Download button, clone it via git clone git://github.com/osteele/lzosutils.git, or add it as a submodule to an existing git repo via git add submodule git://github.com/osteele/lzosutils.git.

FlashBridge is written for OpenLaszlo, but would probably run in straight Flash too. And it uses my own funky alternative to ExternalInterface for calling from Flash to the browser (since the built-in API is seriously broken), but it could be ported to run on top of Dojo or something pretty easily.

Synchronizing Client Models 6

Posted by Oliver on February 27, 2008

You’re implementing a client-server application. The client is in JavaScript. It contains a model class, Person. The model is backed by a server-side Person model, and a REST controller at /person. Periodically, the client updates the server’s model, but there can be client-side instances that don’t yet exist on the server, such as when a model is first created and the server hasn’t yet gotten the message.

I’ve written this code a few times now, in JavaScript, and in ActionScript. if If you write it the obvious way, you run into an interesting set of race conditions. Here’s the code, and the race conditions, and some ad-hoc solutions. In the next post, I’ll introduce a metaobject pattern, queue ball, that I’ve used to solve these race conditions in a more principled and re-usable fashion.

Note: As of 2008-02-28, none of this code has been tested. It’s all extracted from code that’s like the code here, but I haven’t copied and pasted these specific examples into an execution environment, which probably means they fail.

Getting Personal

Here’s the model, with some server proxy mojo mixed in:1

// creates a client-only instance
function Person(attributes) {
  this.attributes = attributes||{};
  // if a server mirror exists, this.id is set to its id 
}
 
// creates a client instance that is mirrored by a new server instance
Person.create = function(attributes) {
  var person = new Person(attributes);
  person.create();
  return person;
}
 
Person.prototype = {
  // creates a server instance for this client instance
  create: function() {
    jQuery.post('/person/create', this.attributes, function(data) {
      this.id = data.id;
    }.bind(this)); 
  },
 
  //  updates attributes of this instance, and, if it exists, its server mirror
  update: function(attributes) {
    Hash.merge(this.attributes, attributes);
    this.id && jQuery.post('/person/update/' + this.id, attributes);
  },
 
  // deletes this instance's server mirror
  remove: function() {
    this.id && jQuery.post('/person/delete', {id:this.id});
    delete this.id;
  }
}

This implementation uses jQuery for transport, and assumes a Hash.merge method from some collection library (say, Prototype’s). It creates a class by setting prototype directly, and it doesn’t detect or recover from XHR errors. All these choices are just to have something concrete to write about; they don’t affect the substance of this article.

A Day at the Races

Do you see the race conditions? There’s at least three: create+update, create+delete, and update+update.

Race Condition 1: Create then Update

function createThenUpdate() {
  var aPerson = Person.create();
  aPerson.update({name:'Edgar Dijkstra'});
}

The problem with createThenUpdate is that aPerson won’t have an id by the time update is called, so update won’t send the new values to the server. The call to create is synchronous, but the communication with the server, and therefore the call to the callback (that sets aPerson.id) is asynchronous, and therefore won’t occur until Person.create returns.

In detail:

  1. createUpdate calls Person.create
  2. Person.create calls new Person
  3. aPerson.create calls jQuery.post
  4. jQuery.post calls XMLHttpRequest.send (not shown)
  5. XMLHTTPRequest.send, jQuery.post, and aPerson.create return
  6. createUpdate calls aPerson.update
  7. [time passes]
  8. Client sends HTTP Request to server
  9. [more time passes]
  10. Client receives HTTP Response
  11. Callback in aPerson.create sets aPerson.id

Solution 1: Explicit Callbacks

One solution to this problem is to thread the code through callbacks (in effect, performing CPS conversion by hand). aPerson.create calls a callback function once it’s internal callback function is called, so Person.create takes a callback parameter too, and so on up the call chain. (In this case, the buck stops here.)

Let’s add a callback parameter to Person.create, that is called once the HTTP response to /person/create is received.

Person.create = function(attributes, callback) {
  var person = new Person(attributes);
  person.create(callback);
  return person;
}
 
Person.prototype = {
  // creates a server instance for this client instance
  create: function(callback) {
    jQuery.post('/person/create', this.attributes, function(data) {
      this.id = data.id;
      callback && callback();
    }.bind(this)); 
  }
}

Then we can rewrite createThenUpdate thus:

function createThenUpdate() {
  var aPerson = Person.create({}, function() {
    aPerson.update({name:'Edgar Dijkstra'});
  });
}

Adding the UI

It was easy to spot the race condition in createThenUpdate — and easy to fix it — because the calls to create and the update were in consecutive statements, within the same function. In the real world, they’re at the bottom of different call chains, as in this jQuery code that binds some model actions to an HTML view:2

$('#person create-button').click(function() {
  $(this).disable(); // avoid double-creation
  $('#person update-button').enable();
  gCurrentModel.create();
});
$('#person update-button').click(function() {
  gCurrentModel.update($('#person').serialize());
});

Click “create“, edit a field, and then click “update“. Sometimes the update will hit the server, sometimes it won’t: it depends on whether the response to the /person/create request has returned by the time you click the second button. We’ve just created an AJAX version of the 500-mile bug.

Let’s thread the callbacks through this code, in order to avoid enabling the “update” button until the callback is called:

$('#person create-button').click(function() {
  $(this).disable(); // avoid double-creation
  gCurrentModel.create({}, function() { $('#person update-button').enable() });
});
$('#person update-button').click(/* unchanged */);

This is awful! First, it requires you to weave callbacks through both your view and your model code.3 But worse, it’s a leaky abstraction. The view layer has to know about an arbitrary (from the outside) limitation — that you can’t call update until create has called its callback — of the model layer.

Solution 2: Implicit Callbacks

Another solution is to use a library such as Narrative JavaScript or JavaScript Strands, that does the CPS conversion (adds the callbacks) for you. I like this approach a lot, but I do a lot of work in contexts where those compilers aren’t applicable4, and many folks (often including, for these reasons and others, me) prefer to work in pure JavaScript. I therefore won’t go further down that path here.

Solution 3: Action Queue

Finally, we can add a queue to the model. With the modification below, calling update while the model is waiting for an id no longer drops server updates; it simply queues them for playback once the response to /person/create is received.

Person.prototype = {
  _updateQueue: null,
 
  create: function() {
    this._updateQueue = [];
    jQuery.post('/person/create', this.attributes, function(data) {
      this.id = data.id;
      while (this._updateQueue.length)
        this._sendUpdate(this._updateQueue.shift());
      delete this._updateQueue;
    }.bind(this));
  },
 
  // the caller must treat `attributes` as deep-frozen once
  // this method has been called
  update: function(attributes) {
    Hash.update(this.attributes, attributes);
    if (this.id)
      this._sendUpdate(attributes)
    else if (this._updateQueue)
      this._updateQueue.push(attributes);
  },
 
  _sendUpdate: function(attributes) {
    jQuery.post('/person/update/' + this.id, attributes);
  }
}

We can use a “method algebra” to optimize this a bit: It doesn’t matter how many times update is called while waiting for the create response — it only needs to send an update once. (The algebra is that there’s an operation +: update × updateupdate that can combine consecutive updates update1 + update2 = update3.)

Person.prototype = {
  _pendingUpdates: null,
 
  create: function() {
    this._pendingUpdates = {};
    jQuery.post('/person/create', this.attributes, function(data) {
      this.id = data.id;
      if (this._pendingUpdates) {
        this._sendUpdate(this. _pendingUpdates);
        delete this. _pendingUpdates;
      }
    }.bind(this));
  },
 
  update: function(attributes) {
    Hash.update(this.attributes, attributes);
    if (this.id)
      this._sendUpdate(attributes)
    else if (this._pendingUpdates)
      Hash.merge(this._pendingUpdates, attributes);
  },
 
  _sendUpdate: function(attributes) {
    jQuery.post('/person/update/' + this.id, attributes);
  }
}

I’m going to back off from this optimization, though. The reason is that it only works if the two calls to update are consecutive — when there are no intervening calls that also send messages that operate on the same instance. With a more full-featured API (with more actions that send messages to the server), this won’t generally be true.

For example, let’s extend Person with a setPermissions method. If we could ignore race conditions, this method might look like this:

Person.prototype = {
  _pendingUpdates: null,
 
  setPermissions: function(permissions) {
    this.permissions = permissions;
    this.id && jQuery.post('/person/set_permissions', {id:this.id, permissions:permissions});
  }
}

This naive implementation is vulnerable to a create+setPermissions race condition analogous to the create+update race condition that we just fixed, though. We can fix them both by generalizing the post-create queue, so that it can contain arbitrary actions, not just update records:

Person.prototype = {
  _pendingActions: null,
 
  create: function() {
    this._pendingActions = {};
    jQuery.post('/person/create', this.attributes, function(data) {
      this.id = data.id;
      while (this._pendingActions.length) {
        var action = this._pendingActions.shift();
        this[action.methodName].apply(this, action.arguments);
      }
      delete this._pendingActions;
    }.bind(this));
  },
 
  update: function(attributes) {
    Hash.update(this.attributes, attributes);
    if (this.id)
      this._sendUpdate(attributes);
    else if (this._pendingActions)
      this.pendingUpdates.push({methodName:'_sendUpdate', arguments:[attributes]);
  },
 
  _sendUpdate: function(attributes) {
    jQuery.post('/person/update/' + this.id, attributes);
  },
 
  setPermissions: function(permissions) {
    this.permissions = permissions;
    if (this.id)
      this._sendSetPermissions(permissions);
    else if (this._pendingActions)
      this.pendingUpdates.push({methodName:'_sendSetPermissions', arguments:[permissions]);
  },
 
  _sendSetPermissions: function(permissions) {
    jQuery.post('/person/set_permissions', {id:this.id, permissions:permissions});
  }
}

Race Condition 2: Create then Delete

function createThenDelete() {
  var aPerson = Person.create();
  aPerson.delete();
}

By now, you should be able to spot the problem here. The reasoning is exactly the same as for update: when delete is called, aPerson won’t yet have an id.

We could fix this with a callback:

function createThenDelete() {
  var aPerson = Person.create({}, function() {
    aPerson.delete();
  });
}

This has the attendant disadvantages of having to bake knowledge about the client-server protocol into Person’s clients, and having to thread callbacks through the UI. After all, it’s rare that we would create a Person simply to delete it; the more common case is that the creation and deletion would be at the bottom of different call chains — often initiated from outside the application, in response to user actions — such that it’s difficult to thread the first as a callback of the second. And note that, as with create+update, we can’t simply ignore the delete unless the server creation has responded: if we do this, we’ll occasionally drop a delete on the floor, because it was called after the create was sent, but before the response.

The best local solution is to build on the action queue solution above — by simply adding another method to the queue.

Person.prototype = {
  delete: function() {
    if (this._pendingActions)
      this.pendingUpdates.push({methodName:'_sendDelete');
    else
      delete this.id;
  },
 
  _sendDelete: function() {
    jQuery.post('/person/delete', {id:this.id});
    delete this.id;
  }
}

This works, but it should make you uncomfortable. We’re adding (almost) the same conditional to every single method.

Race Condition 3: Overlapping Updates

function updateThenUpdate(aPerson) {
  aPerson.update({name:'Edgar Djikstra'});
  aPerson.update({name:'Edgar Dijkstra'});
}

From looking at updateThenUpdate, it looks like the first call to update will occur before the second. And it does! (Duh.) And it looks like the misspelled name in the first call will be replaced by the correct name in the second call. And it will! (Well…on the client…read on.) Because: the first call to XMLHttpRequest.send (with the misspelled name) occurs before the second call to XMLHttpRequest.send (with the correction), and the client therefore sends the message with the misspelled name before it sends the message with the correction. But our run of good luck stops here. There is, unfortunately no guarantee about the order in which the server will receive these messages. Generally, the first message will be received before the second. Sometimes, they will arrive in the other order, and the misspelling will overwrite the correction.

There are two ways to fix this problem: by sequencing messages, or by holding outgoing messages (holding each outgoing message until the previous one returns). Sequencing messages is the higher-performance solution (it doesn’t hold up messages), but requires more work and involves switching both the client and the server from a straight REST API, which may not be possible5.

For simplicity, we’ll look at the second solution: holding outgoing messages. This solution has the advantage that the general-purpose solution to the other race conditions (presented in the next article) happens to implement it too. (In this article, we’ll implement with an explicit Serialized object instead.) Message sequencing doesn’t help with those other cases at all: the problem with them is that the second message is never sent, not that it’s sent out of order.

Here’s a quick-and-dirty implementation of the hold outgoing messages solution. The following code defines Serialized.post as a drop-in replacement for jQuery.post, that refuses to post data until the previous post has completed (successfully, or with an error).6

var Serialized = {
  queue: [], // arguments for pending 
  defer: false,
  post: function(url, data, callback, type) {
    if (this.defer) {
      this.queue.push(Array.prototype.slice.call(arguments, 0));
      return;
    }
    this.defer = true;
    jQuery.ajax({url:url, type:'POST', data:data, success:success, complete:complete.bind(this)});
    function complete() {
      if (this.queue.length)
        this.post.apply(this, this.queue.shift();
      this.defer = false;
    }
  }
}

Next Up: Queue Ball

I’d like to factor all those conditionals out of the Person methods. Then I’d like to extract the queue code from create, so that I can use it on update (to solve the update+update problem). Finally, there are some general-purpose techniques here, so I’d like to extract the whole mess from Person, where I can apply it to any model (or to code that has some of the same concerns, even if it’s not synchronized model code). But this post is already long enough, so I’ll just close with the promise to write that up, so that I have to do it.


1 Would you rather have code with a cleaner separation of concerns? Here it is. You’ll find that it doesn’t make the race conditions go away, but that it doesn’t change the set of techniques for solving them. (It does make the “explicit callbacks” solution even worse.) I’ve therefore stuck with the double-duty Person implementation in the body of this article, to make the code easier to follow.

function Person(attributes) {
  this.attributes = attributes || {};
  this.proxy = null;
}
 
Person.prototype = {
  create: function() {
    this.proxy = new PersonProxy();
    this.proxy.create(this.attributes);
  },
 
  update: function(attributes) {
    Hash.merge(this.attributes, attributes);
    this.proxy && this.proxy.update(attributes);
  },
 
  remove: function() {
    this.proxy.remove();
    delete this.proxy;
  }
}
 
function PersonProxy() {
  this.id = null;
}
 
PersonProxy.prototype = {
  create: function(attributes) {
    jQuery.post('/person/create', attributes, function() { this.id = id }.bind(this)); 
  },
 
  update: function(attributes) {
    this.id && jQuery.post('/person/update/' + this.id, this.attributes);
  },
 
  remove: function() {
    this.id && jQuery.post('/person/delete', {id:this.id});
    delete this.id;
  }
}

2 This implementation somewhat mixes the model with the view. It’s not the clearest code. It would be cleaner if it used listeners and reactive programming techniques — but the fact that it’s so explicit makes it easier to follow what’s going on.

3 I’ve used this approach, and it wipes the floor with using listeners or delegates or other unthreaded callbacks, where you have to store state in objects in order to match listeners with their context, but it’s still a pain to maintain.

4 CPS conversion introduces a lot of function allocations and invocations. I’ve been scared to try a system that introduces them globally, instead of letting me judiciously thread a few callbacks in by hand, when developing for a slow ECMAScript implementation such as Flash < 9 or MSIE. (I even use my own libraries sparingly in such a situation.)

5 XMPP preserves message order, by sending all the messages over a single stream. One could also add a sequence number to each message. The receiver (in this case, the server) should buffer messages that arrive out of order, so that it can process them in the order in which they occur. This is how a streaming protocol such as TCP is implemented: by adding sequence numbers and buffering on top of an unordered protocol such as IP. HTTP is implemented on top of TCP, but only uses TCP to preserve the order of packets within a message, so multiple HTTP requests (and responses) can get out of order again. It seems that keepalive might fix the problem, and that load balancers might re-introduce it, and that affinity might fix it again, but only if you can guarantee that your load balancer is properly configured. But I’m getting out of my depth here.

6 This code assumes that a request will never take longer than the client timeout setting to reach the server. Otherwise, complete could be called before the server receives the first message, the client would send the next message, and the server would process them out of order. That’s one reason I called this implementation quick-and-dirty.