Monday, April 16, 2007

Adding Concurrency to Our Erlang Program

image



In our last thrilling installment, we used Erlang to fetch a book’s title and sales rank from Amazon. Now let’s extend this to fetch the data for multiple books, first one-at-a-time, and then in parallel.


A word from our lawyers: read your Amazon Terms of Service before trying this code. You may have limitations on the number of requests you can send per second or somesuch. This code is just to illustrate some Erlang constructs.

Let’s start with the function that fetches sales ranks in series. We’ll pass it a list of ISBNs, and it will return a corresponding list of {title, rank} tuples. For convenience, let’s define a function that returns a list of ISBNS to check. (Later, we can change this function to read from a database or a file). We’re editing our file ranks.erl.


  isbns() ->
[ "020161622X", "0974514004", "0974514012", "0974514020", "0974514039",
"0974514055", "0974514063", "0974514071", "097669400X", "0974514047",
"0976694018", "0976694026", "0976694042", "0976694085", "097451408X",
"0976694077", "0977616606", "0976694093", "0977616665", "0976694069",
"0976694050", "0977616649", "0977616657"
].

Users of our code call the fetch_in_series function. It uses the built-in lists:map function to convert our ISBN list into the result list.


  fetch_in_series() ->
lists:map(fun fetch_title_and_rank/1, isbns()).

The first parameter to lists:map is the function to be applied to each element in the ISBN list. Here we’re telling Erlang to call the fetch_title_and_rank function that we defined in the first article. The/1 says to use the version of the function that takes a single argument.


We need to export this function from the module before we can call it.


  -export([fetch_title_and_rank/1, fetch_in_series/0]).

Let’s fire up the Erlang shell and try it.


  1> c(ranks).
{ok,ranks}
2> ranks:fetch_in_series().
[{"The Pragmatic Programmer: From Journeyman to Master","4864"},
{"Pragmatic Version Control Using CVS","288118"},
{"Pragmatic Unit Testing in Java with JUnit","116011"},
. . .

“But wait!” I hear you cry. “Isn’t Erlang supposed to be good at parallel programming. What’s with all this fetch-the-results-in-series” business?”


OK, let’s create a parallel version. We have lots of options here, but for now let’s do it the hard way. We’ll spawn a separate (Erlang) process to handle each request, and we’ll write all our own process management code to coordinate harvesting the results as these processes complete.


Erlang processes are lightweight abstractions; they are not the same as the processes your operating system provides. Unlike your operating system, Erlang is happy dealing with thousands of concurrent processes. What’s more, you can distribute these processes across servers, processors, and cores within a processor. All this is achieved with a handful of basic operations. To send a tuple to a process whose process ID is in the variable Fred, you can use:


  Fred  ! {status, ok}

To receive a message from another process, use a receive stanza:


  receive 
{ status, StatusCode } -> StatusCode
end

There’s something cool about the receive code. See the line


    { status, StatusCode } -> StatusCode

The stuff on the left hand side of the arrow is a pattern match. It means that this receive code will only accept messages which are a two element tuple where the first element is the atom status. This particular receive stanza then strips out just the actual code part of this tuple and returns it. In general a receive stanza can contain multiple patterns, each with its own specialized processing. This is remarkably powerful.


There’s one last primitive we need. The function spawn takes a function and a set of parameters and invokes that function in a new Erlang process. It returns the process ID for that subprocess.


Let’s write a simple, and stupid, example. This module exports test/1. This function spawns a new process that simply doubles a value. Here’s the code—we’ll dig into it in a second.


  -module(parallel).
-export([test/1]).

test(Number) ->
MyPID = self(),
spawn(fun() -> double(MyPID, Number) end),
receive
{ answer, Val } -> { "Child process said", Val }
end.

double(Parent, Number) ->
Result = Number + Number,
Parent ! { answer, Result }.

Because we’re handling all the details ourselves, we have to tell the process running the double function where to send its result. To do that, we pass it two parameters: the first is the process ID of the process to receive the result, and the second is the value to double. The second line of the double function uses the ! operator to send the result back to the original process.


The original process has to pass its own process ID to the double method. It uses the built-in self()function to get this PID. Then, on the second line of the function, it invokes spawn, passing it an anonymous function which in turn invokes double. There’s a wee catch here: it’s tempting to write:


  test(Number) ->
spawn(fun() -> double(self(), Number) end),
...

This won’t work: because the anonymous function only gets executed once the new process is started, the value returned by self() will be that process’s ID, and not that of the parent.


Anyway, we can invoke this code using the Erlang shell:


  1> c(parallel).
{ok,parallel}
2> parallel:test(22).
{"Child process said",44}

Back to Amazon. We want to fetch all the sales ranks in parallel. We’ll start with the top-level function. It starts all the fetcher processes running in parallel, then gathers up their results.


  fetch_in_parallel() ->
inets:start(),
set_queries_running(isbns()),
gather_results(isbns()).

The first line of this method is a slight optimization. The HTTP client code that we use to fetch the results actually runs behind the scenes in its own process. By calling the inets:start method, we precreate this server process.


Here’s the code that creates the processes to fetch the sales data:


  set_queries_running(ISBNS) ->
lists:foreach(fun background_fetch/1, ISBNS).

background_fetch(ISBN) ->
ParentPID = self(),
spawn(fun() ->
ParentPID ! { ok, fetch_title_and_rank(ISBN) }
end).

The lists:foreach function invokes its first argument on each element of its second argument. In this case, it invokes the background_fetch function that in term calls spawn to start the subprocess. Perhaps surprising is the fact that the anonymous function acts as a closure: the values of ParentID andISBN in its calling scope are available inside the fun’s body, even though it is running is a separate process. Cool stuff, eh?


There’s an implicit decision in the design of this code: I decided that I don’t care what order the results are listed in the returned list—I simply want a list that contains one title/rank tuple for each ISBN. I can make use of this fact in the function that gathers the results. It again uses lists:map, but bends its meaning somewhat. Normally the map function maps an value onto some other corresponding value. Here we’re simply using it to populate a list with the same number of entries as the original ISBN list. Each entry contains a result from Amazon, but it won’t be the result that corresponds to the ISBN that is in the corresponding position in the ISBN list. For my purposes, this is fine.


  gather_results(ISBNS) ->      
lists:map(fun gather_a_result/1, ISBNS).

gather_a_result(_) ->
receive
{ ok, Anything } -> Anything
end.

Let’s run this:


  1> c(ranks).                              
{ok,ranks}
2> ranks:fetch_in_parallel().
[{"The Pragmatic Programmer: From Journeyman to Master","6359"},
{"Pragmatic Version Control Using CVS","299260"},
{"Pragmatic Unit Testing in Java with JUnit","131616"},
. . .

What kind of speedup does this give us? We can use the built-in timer:tc function to call our two methods.


 timer:tc(ranks, fetch_in_parallel, []).
{1163694, . . .
timer:tc(ranks, fetch_in_series, []).
{3070261, . . .

The first element of the result in the wallclock time taken to run the function (in microseconds). The parallel version is roughly 3 times faster than the serial function.


So, do you have to go to all this trouble to make your Erlang code run in parallel? Not really. I just wanted to show some of the nuts and bolts. In reality, you’d probably use a library method, such as thepmap function that Joe wrote for the Programming Erlang book. Armed with this, you could turn the serial fetch program to a parallel fetch program by changing


  lists:map(fun fetch_title_and_rank/1, ?ISBNS).

to


  lib_misc:pmap(fun fetch_title_and_rank/1, ?ISBNS).


Now that’s an abstraction!


Anyway, here’s the current version of the ranks.erl program, containing both the serial and parallel fetch functions.


  -module(ranks).
-export([fetch_title_and_rank/1, fetch_in_series/0, fetch_in_parallel/0]).
-include_lib("xmerl/include/xmerl.hrl").

-define(BASE_URL,
"http://webservices.amazon.com/onca/xml?Service=AWSECommerceService"
"&SubscriptionId=<your ID goes here>"
"&Operation=ItemLookup"
"&ResponseGroup=SalesRank,Small"
"&ItemId=").

isbns() ->
[ "020161622X", "0974514004", "0974514012", "0974514020", "0974514039",
"0974514055", "0974514063", "0974514071", "097669400X", "0974514047",
"0976694018", "0976694026", "0976694042", "0976694085", "097451408X",
"0976694077", "0977616606", "0976694093", "0977616665", "0976694069",
"0976694050", "0977616649", "0977616657"
].

fetch_title_and_rank(ISBN) ->
URL = amazon_url_for(ISBN),
{ ok, {_Status, _Headers, Body }} = http:request(URL),
{ Xml, _Rest } = xmerl_scan:string(Body),
[ #xmlText{value=Rank} ] = xmerl_xpath:string("//SalesRank/text()", Xml),
[ #xmlText{value=Title} ] = xmerl_xpath:string("//Title/text()", Xml),
{ Title, Rank }.

amazon_url_for(ISBN) ->
?BASE_URL ++ ISBN.


fetch_in_series() ->
lists:map(fun fetch_title_and_rank/1, isbns()).


fetch_in_parallel() ->
inets:start(),
set_queries_running(isbns()),
gather_results(isbns()).

set_queries_running(ISBNS) ->
lists:foreach(fun background_fetch/1, ISBNS).

background_fetch(ISBN) ->
ParentPID = self(),
spawn(fun() ->
ParentPID ! { ok, fetch_title_and_rank(ISBN) }
end).

gather_results(ISBNS) ->
lists:map(fun(_) ->
receive
{ ok, Anything } -> Anything
end
end, ISBNS).

Sunday, April 15, 2007

A First Erlang Program

image


One of the joys of playing at being a publisher is that I get to mess around with the technology in books as those books are getting written. Lately I’ve been having a blast with Joe Armstrong's new Erlang Book. At some point I’ll blog about the really neat way the Erlang database unifies the set-based SQL query language and list comprehensions (it’s obvious when you think about it, but it blew me away when I first read it). But I just wanted to start off with some simple stuff.


One of my standard Ruby examples is a program that fetches our book sales ranks from Amazon using their REST interface. I thought I’d try the exercise again in Erlang. In this first part we’ll write a simple Erlang function that uses the Amazon Web Services API to fetch the data on a book (identified by its ISBN). This data is returned in XML, so we’ll then use some simple XPath to extract the title and the sales rank.


My Erlang module is called ranks, and I store it in the fileranks.erl. Because I’m just playing for now, the interface to this module is simple: I’ll define a function calledfetch_title_and_rank. This returns a {title, rank} tuple. So, I started off with something like this:


  -module(ranks).
-export([fetch_title_and_rank/1]).

fetch_title_and_rank(ISBN) ->
{ "Agile Web Development with Rails", 1234 }.

The -module directive simply names the module. The next line tells Erlang that this module exports a function called fetch_title_and_rank. This method takes one parameter. (This idea of specifying the number of parameters seems strange until you realize that in Erlang the function signature is the function name and the parameter count. It is valid to export two functions with the same name if they take a different number of arguments—as far as Erlang is concerned they are different functions.)


Next we define the fetch_title_and_rank function. It takes a single parameter, the book’s ISBN. In Erlang, variable names (including parameters) start with uppercase letters. This takes a little getting used to. Just to make sure thinks are wired up correctly, let’s try running this code. In a command shell, I navigate to the directory containing ranks.erl and started the interactive Erlang shell. Once inside it, I compiled my module (using c(ranks).) and then invoke the fetch_title_and_rank method.


  dave[~/tmp 11:51:09] erl
Erlang (BEAM) emulator version 5.5.4 [source] ...

Eshell V5.5.4 (abort with ^G)
1> c(ranks).
./ranks.erl:11: Warning: variable 'ISBN' is unused
{ok,ranks}
2> ranks:fetch_title_and_rank("0977616630").
{"Agile Web Development with Rails",1234}

Let’s start wiring this up to Amazon.


To fetch information from Amazon using REST, you need to issue an ItemLookup operation, specifying what you want Amazon to return. In our case, we want the sales rank information, plus something called the small response group. The latter includes the book’s title. The URL you use to get this looks like this (except all on one line, and with no spaces):


http://webservices.amazon.com/onca/xml?
Service=AWSECommerceService
&SubscriptionId=<your ID goes here>
&Operation=ItemLookup
&ResponseGroup=SalesRank,Small
&ItemId=0977616630

The ItemID parameter is the ISBN of our book. Let’s write an Erlang function that returns the URL to fetch the information for an ISBN.


  -define(BASE_URL,
"http://webservices.amazon.com/onca/xml?" ++
"Service=AWSECommerceService" ++
"&SubscriptionId=<" ++
"&Operation=ItemLookup" ++
"&ResponseGroup=SalesRank,Small" ++
"&ItemId=").

amazon_url_for(ISBN) ->
?BASE_URL ++ ISBN.

This code defines an Erlang macro called BASE_URL which holds the static part of the URL. The functionamazon_url_for builds the full URL by appending the ISBN to this. Note that both the macro and the function use ++, the operator that concatenates strings.


We now need to find a way of sending this request to Amazon and fetching back the XML response. Here we bump into one of Erlang’s current problems—it can be hard to browse the library documentation. My solution is to download the documentation onto my local box and search it there. I tend to use both the HTML and the man pages. Figuring I wanted something HTTP related, I tried the following:


  dave[Downloads/lib 12:04:07] ls **/*http*
inets-4.7.11/doc/html/http.html
inets-4.7.11/doc/html/http_base_64.html
inets-4.7.11/doc/html/http_client.html
inets-4.7.11/doc/html/http_server.html
inets-4.7.11/doc/html/httpd.html
inets-4.7.11/doc/html/httpd_conf.html
inets-4.7.11/doc/html/httpd_socket.html
inets-4.7.11/doc/html/httpd_util.html

Opening up http.html revealed the http:request method.



request(Url) -> {ok, Result} | {error, Reason}


This says that we give the request method a URL string. It returns a tuple. If the first element of the tuple is the atom ok, then the second element is the result for the request. If the first element is error, the second element is the reason it failed. This technique of returning both status and data as a tuple is idiomatic in Erlang, and the language makes it easy to handle the different cases.


Let’s look a little deeper into the successful case. The Result element is actually itself a tuple containing a status, the response headers, and the response body.


So let’s take all this and develop our fetch_title_and_rank method a little more.


  fetch_title_and_rank(ISBN) ->
URL = amazon_url_for(ISBN),
{ ok, {Status, Headers, Body }} = http:request(URL),
Body.

We call our amazon_url_for method to create the URL to fetch the data, then invoke the http:requestlibrary method to fetch the result. Let’s look at that second line in more detail.


The equals sign in Erlang looks like an assignment statement, but looks are deceptive. In Erlang, the equals sign is actually a pattern matching operation—an assertion that two things are equal. For example, it is perfectly valid in Erlang to say


  6> 1 = 1.
1
7> 9 * 7 = 60 + 3.
63

So what happens when variables get involved? This is where it gets interesting. When I say


  A = 1.

I’m not assigning 1 to the variable A. Instead, I’m matching A against 1 (just like 9*7 = 60+3 asserts that the results of the two expressions are the same). So, does A match 1? That depends. If this is the first appearance of A on the left hand side of an equals sign, then A is said to be unbound. In this condition, Erlang says to itself “I can make this statement true if I give A the value 1,” which is does. From this point forward, A has the value 1 (in the current scope). If we say A = 1. again in the same scope in our Erlang program, A is no longer unbound, but this pattern match succeeds, because A = 1.is a simple assertion of truth. But what happens if we say A=2.?


  10> A = 1.
1
11> A = 1.
1
12> A = 2.

=ERROR REPORT==== 16-Apr-2007::12:32:36 ===
Error in process <0.55.0> with exit value: {{badmatch,2},[{erl_eval,expr,3}]}

** exited: {{badmatch,2},[{erl_eval,expr,3}]} **

We get an error: Erlang was unable to match the values on the left and right hand sides of the equals, so it raised a badmatch error. (Erlang error reporting is, at best, obscure.)


So, back to our HTTP request. I wrote


  { ok, {Status, Headers, Body }} = http:request(URL)

The left hand side matches a tuple. The first element of the tuple is the atom ok. The second element is another tuple. Thus the entire expression only succeeds if http:request returns a two element tuple with ok as the first element and a three element tuple as the second element. If the match succeeds, then the variables StatusHeaders, and Body are set to the three elements of that second tuple.


(An aside for Ruby folk: you can do something similar using an obscure Ruby syntax. The statement


  rc, (status, headers, body) = [ 200, [ "status", "headers", "body" ] ]

will leave headers containing the string "headers".)


In our Erlang example, what happens if http:request returns an error? In this case, the first element of the returned tuple will be the atom error. This won’t match the left hand side of our expression (because the atom error is not the same as the atom ok) and we’ll get a badmatch error. We won’t bother to handle this here—it’s someone else’s problem.


Let’s compile our program.


  1> c(ranks).
./ranks.erl:13: Warning: variable 'Headers' is unused
./ranks.erl:13: Warning: variable 'Status' is unused
{ok,ranks}

Erlang warns us that we have some unused variables. Do we care? To a point. I personally like my compilations to be clean, so let’s fix this. If you prefix a variable’s name with an underscore, it tells the Erlang compiler that you don’t intend to use that variable. As a degenerate case, you can use just a lone underscore, which means “some anonymous variable.” So, we can fix our warnings by writing either


  { ok, {_Status, _Headers, Body }} = http:request(URL),

or


  { ok, {_, _, Body }} = http:request(URL),

I mildly prefer the first form, as it helps me remember what those elements in the tuple are when I reread the program later.


Now we can recompile and run our code:


  1> c(ranks).
{ok,ranks}
2> ranks:fetch_title_and_rank("0977616630").
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><ItemLookupResponse
xmlns=\"http://webservices.amazon.com/AWSECommerceService/2005-10-05\">
<OperationRequest><HTTPHeaders><Header ...
... <SalesRank>1098</SalesRank>
... <Title>Agile Web Development with Rails (Pragmatic
Programmers)</Title>...
...

Cool! We get a boatload of XML back. (If you’re running this at home, you’ll need to substitute your own AWS subscription ID into the request string to make this work.) Now we need to extract out the title and the sales rank. We could to this using string operations, but wouldn’t it be more fun to use XPath? Another quick filesystem scan reveals the xmerl library, which both generates and parses XML. It also supports XPath queries. To use this, we first scan the Amazon response. This constructs an Erlang data structure representing the original XML. We then call the xmerl_xpath library to find the elements in this data structure matching our query.


  -include_lib("xmerl/include/xmerl.hrl").

fetch_title_and_rank(ISBN) ->
URL = amazon_url_for(ISBN),
{ ok, {_Status, _Headers, Body }} = http:request(URL),
{ Xml, _Rest } = xmerl_scan:string(Body),
[ #xmlText{value=Rank} ] = xmerl_xpath:string("//SalesRank/text()", Xml),
[ #xmlText{value=Title} ] = xmerl_xpath:string("//Title/text()", Xml),
{ Title, Rank }.

The -include line loads up the set of Erlang record definitions that xmerl uses to represent elements in the parsed XML. This isn’t strictly necessary, but doing so makes the XPath stuff a little cleaner.


The line


    { Xml, _Rest } = xmerl_scan:string(Body),

parses the XML response, storing the internal Erlang representation in the variable Xml.


Then we have the line


    [ #xmlText{value=Rank} ]  = xmerl_xpath:string("//SalesRank/text()", Xml),

The notation #xmlText identifies an Erlang record. A record is basically a tuple where each element is given a name. In this case the tuple (defined in that .hrl file we included) is called xmlText. It represents a text node in the XML. The xmlText record has a field called value. We use pattern matching to assign whatever is in that field to the variable Rank. But there’s one more twist. Did you notice that we wrote square brackets around the left hand side of the pattern match? Thats because XPath queries return an array of results. By writing the left hand side the way we did, we force Erlang to check that an array containing just one element was returned, and then to check that this element was a record of type xmlText. That’s pretty cool stuff—pattern matching extends down deep into the bowels of Erlang.


The last line of the method simply returns a tuple containing the title and the sales rank.


We can call it from the command line:


  1> c(ranks).
{ok,ranks}
2> ranks:fetch_title_and_rank("0977616630").
{"Agile Web Development with Rails (Pragmatic Programmers)","1098"}

That’s it for now. Next we’ll look at fetching the data for multiple books at once. In the meantime, here’s the full listing of our ranks.erl file.


  -module(ranks).
-export([fetch_title_and_rank/1]).
-include_lib("xmerl/include/xmerl.hrl").

-define(BASE_URL,
"http://webservices.amazon.com/onca/xml?" ++
"Service=AWSECommerceService" ++
"&SubscriptionId=<your id>" ++
"&Operation=ItemLookup" ++
"&ResponseGroup=SalesRank,Small" ++
"&ItemId=").


fetch_title_and_rank(ISBN) ->
URL = amazon_url_for(ISBN),
{ ok, {_Status, _Headers, Body }} = http:request(URL),
{ Xml, _Rest } = xmerl_scan:string(Body),
[ #xmlText{value=Rank} ] = xmerl_xpath:string("//SalesRank/text()", Xml),
[ #xmlText{value=Title} ] = xmerl_xpath:string("//Title/text()", Xml),
{ Title, Rank }.

amazon_url_for(ISBN) ->
?BASE_URL ++ ISBN.

Wednesday, March 28, 2007
















The coolest app you never knew was on your hard drive


If you use OS X, then you own an application that’ll waste hours of your time just sitting on your hard drive.


Say hello to Applications > Utilities > Grapher.


We needed a simple Fourier square wave for a book. Just type in the equations, and out it pops.


But the time wasting comes from playing with its example graphs.


Did I mention that they animate, and it can export Quicktime?

The RADAR Architecture: RESTful Application, Dumb-Ass Recipient

It Starts With Verbs and Nouns


Roy Fielding’s REST work showed us that the design of the interaction between a client and a server could make a major difference to the reliability and scalability of that application. If you follow a set of conventions embodied in REST when designing your application, is means that (for example) the network will be able to cache responses to certain requests, offloading work from both upstream network components and from the application.


But REST was about more than performance. It offered a way of separating the actions performed by your applications (the verbs) from the things acted upon (the nouns, or in REST terms, the resources). What’s more, REST said that the verbs that you use should apply consistently across all your resources.


When using HTTP, the HTTP verbs (such as GET, PUT, POST, and DELETE) are also the verbs that should be used with REST applications. This makes a lot of sense, because things like routers and proxies also understand these verbs.


One of the successes built using these principles is the Atom Publishing Protocol. Atom allows clients to fetch, edit, and publish web resources. Atom is probably most commonly applied to allow people to use local editors to create and maintain blog articles—client software on the user’s computer uses Atom to fetch existing articles and to save back edited or new articles.


Let’s look at how that happens with Atom.


I fire up my Atom-based local client. It needs to fetch the updated list of all the articles currently on the server, so it issues a GET request to a URL that represents the collection of articles: the verb is GET, and the resource is the collection.


   GET   /articles

What comes back is a list of resources. Included with each resource are one or two URIs. One of these URIs can be used to access that resource for editing. Let’s say I want to edit a particular article. First, my client software will fetch it, using the URI given in the collection:


   GET   /article/123

As a user of the editing software, I then see a nicely formatted version of the article. If I click the [EDIT]button, that view changes: I now see text boxes, drop down lists, text areas, and so on. I can now change the article’s contents. When I press [SAVE], the local application then packages up the changed article and sends it back to the server using a PUT request. The use of PUT says “update an existing resource with this new stuff.”


Browsers are Dumb


If you use a browser to interact with a server, you’re using a half-duplex, forms-based device. The host sends down a form, you fill in the form, and send it back when you’re ready. This turns out to be really convenient for people running networks and servers. Because HTTP is stateless, and because applications talk to browsers using a fire-and-forget model, your servers and networks can handle very large numbers of devices. This is exactly the architecture that IBM championed back in the 70s. The half-duplex, poll-select nature of 3270-based applications allowed mainframes with less processing power than a modern toaster to handle tens of thousands of simultaneous users. The browser is really not much better than a 3270 (except the resolution is better when displaying porn). (Recently, folks have been trying to circumvent this simplicity by making browser-based applications more interactive using technologies such as Ajax. To my mind, this is just a stop-gap until we throw the browser away altogether—Ajax is just lipstick on a pig.)


How well do browsers play in a RESTful world?


Well, for a start, they really only use two of the HTTP verbs: GET and POST. Is this a problem? Yes and no.


We can always hack around the lack of verbs by embedding the verb that you wanted to use somewhere in the request that you send to the server. It can be embedded in the URL that you use to access a resource or it can be embedded in the body of the request (for example as an element of the POST data). Both work, assuming the server understands the conventions. But both techniques also mean that you’re not using REST and the HTTP verb set; you’re simply using HTTP as a transport with your own protocol layered on top. And that means that the network is less able to do clever things to optimize your traffic.


But a browser talking HTML over HTTP is also lacking in another important area. It isn’t running any application functionality locally. Remember our Atom-based blogging client? It had smarts, and so it knew how to display an article for editing. Browsers don’t have that (without a whole lot of support in terms of bolted on Javascript or Flash). So, as a result, people using RESTful ideas to talk to browsers have to put the smarts back on the server. They invent new URLs which (for example) return a resource, but return it all wrapped up in the HTML needed to display it as a form for browser-based editing. This is how Rails does it. Using the Rails conventions, if I want to fetch an article for viewing on a browser, I can use


  GET   /article/1

If, instead, I want to allow the user to edit the resource, I issue


  GET  /article/1;edit

The application then sends down a form pre-populated with the data from that article. When I hit submit, the form contents are sent back to the server, along with a hidden field that tells the server to pretend that the HTTP POST request is actually a RESTful PUT request—the result is that the resource is updated on the server.


The ;xxx notation looks like it was tacked on. I think that in this case, looks aren’t deceiving—these modifiers really were something of an afterthought, added when it became apparent that a pure Atom-like protocol actually wouldn’t do everything needed in a real-world browser-based web application. That’s because the client of an Atom server is assumed to be more that just a display device. An Atom client would not say “fetch me this resource and (oh, by the way) send it down as a form so that I can edit it.” The client would just say GET, do what it had to do, then issue a PUT.


So, in pure REST, the client is a peer (or maybe even in charge) of the interchange. But when talking to a dumb browser, the client is no better than an intermediary between the human and the application. That’s why it was necessary to add things such as ;edit.


Client-independent Applications


One of the other benefits of designing your applications against the limited verbs offered by HTTP REST is that you can (in theory) support many different clients with the same application code. You could write blogging server that (for example) looked at the HTTP Accepts header when deciding what to send back to a client. The response to a GET request to /articles could be a nicely formatted HTML page if the client wants an HTML response, an XML payload if the client asks for XML, or an Atom collection if the client asks for application/atomcoll+xml. In Rails terms, this is handled by therespond_to stanza that is duplicated in each controller action of a RESTful server.


But the benefits run deeper than simply being able to serve up different styles of response.


The HTTP verb set maps (with a little URL tweaking) pretty nicely onto the database verb set. POST, GET, PUT, and DELETE get mapped to the database CRUD verbs: Create, Read, Update, and Delete.


So, in theory at least, you should be able to write your application code as a fairly thin veneer over a set of resources. The application exports the verbs to manipulate the resources and the clients have fun accessing them. This is similar to the vision of Naked Objects.


However, I personally think it was optimistic to try to treat the two styles of interaction (smart and dumb clients) using the same protocol. The ugliness of the ;xxx appendages was a hint.


I think there’s a lot of merit in following a CRUD-based model for interacting with your application’s resources. I’m not convinced all the hassle of bending dumb browser interactions into a REST-based set of verbs, and then extending those verbs to make it work, is worth the extra hassle. To put it another way, I believe the discipline and conventions imposed by thinking of your application interface as a RESTful one are worthwhile. They lead to cleaner and easier-to-understand designs. The hoops you have to jump through to implement it with a browser as a client seem to suggest that a slavish adherence to the protocol might be trying to push it too far.


An Alternative Model


Does that mean I’m down on the RESTful, CRUD based approach to application development? Not at all. For some categories of application, I think it’s a great way of structuring your code. But REST isn’t designed for talking to people. So let’s accept that fact when creating applications. And, while we’re at it, let’s take advantage of the fact that HTTP is such a flexible transport. Rather than trying to design one monolithic application than has both the CRUD functionality and the smarts to be able to talk HTML to end users, why not split it into two smaller and simpler applications?


image


Put the main application logic into a RESTful server. This is where all the CRUD-style access to resources takes place.


Then, write a second proxy server. This is an HTTP filter, sitting between dumb browsers and your core resources. When browser-based users need to interact with your resources, they actually connect to this proxy. It then talks REST to your main server, and interprets the RESTful responses back into a form that’s useful on the browser. And this filter doesn’t have to be a dumb presentation layer—there’s nothing to say that it can’t handle additional functionality as well. Things like menus, user preferences, and so on could all sit here.


Where does this filter sit? That depends. Sometimes it makes sense to have it running locally on the user’s own computer. In this case you’re back in a situation like the one we looked at with the blogging software. Sometimes it makes sense to have the proxy running on the network. In this case you gain some interesting architectural flexibility—there’s no rule that says you must colocate your REST and presentation servers. Potentially this can lead to better response times, lower network loads, and increased security.


With this approach, we can lose all the hacks we need to make to our URLs and POST data to make them act RESTfully. And we can lose all the ugly respond_to stanzas in our Rails server code. We might even be able to get better reuse, sharing both resource servers and presentation servers between applications.


Let’s call it RADAR. We have a RESTful Application talking to Dumb-Ass Recipients.


Does it work? I don’t know. You tell me.

Wednesday, March 21, 2007

SYWTWAB 7: Reviewers, And How Not to Kill Them

This is the seventh of a series of personal notes to people who may be thinking of writing (or who have embarked upon writing) a book. You’ll be able to find them all (eventually) by selecting the tag Writing A Book.




Writing a book is an intensely personal thing. You spend hour after hour nurturing it, turning raw words into something you can be proud of. You’ve done your best to convey your message, and to make a book that’s both accurate and entertaining. It’s gorgeous.


It’s really quite a shame that you have to show it to other people.


But you do.


image



And those other people don’t realize how much work you’re put in, and how subtly you’ve plotted it, and how many ideas you researched. They just want to tell you what’s wrong. That’s their job—they’re reviewers.


Your publisher will have their own policies when it comes to reviewing. Some have a book reviewed chapter by chapter (which seems strange, as good books are not written chapter by chapter). Some review content in chunks. Some wait until the end. And some use a beta-book process, where the general public can subscribe to the book as it is being developed.


Whatever the process, you’ll get reviews. And these can be tough to read. Let’s see how to handle them.


Start by remembering that every review comment is there because someone took the time to write it. The writer hoped to help make your book better. It may be painful, but take every review as something positive.


Each reviewer will have his or her own style, interests, level of experience, and so on. This is just what you want—if your publisher has done its job correctly, your reviewers will be representative of your target audience (with a couple of world experts thrown in to keep your content honest).


Some reviewers may seem to be terribly naive (or even just plain stupid). You’ll find yourself thinking “this guy just doesn’t get it.” And that’s the point. If a reviewer doesn’t get some point, or doesn’t understand something that you feel should be blindingly obvious, that’s an indication that you may have a problem with the book. After all, it’s your job as the author to make that technical detail obvious. So look hard at the reviewer’s comment and see where they’re coming from. Maybe you assumed that the world would interpret some phase or explanation one way, but the reviewer took it another way. Maybe changing one or two words would clear it up; maybe an extra paragraph of introduction; maybe a sidebar. Or maybe the section could be lost altogether or moved later in the book; it’s easy to introduce advanced material too early.


Other reviewers can came across as being incredibly arrogant. They seem to take almost vicious pleasure in finding fault. Their tone suggests that only an idiot could have made this kind of mistake. These reviewers suffer from what experts call penicranial inversion.


This type of reviewer is hard to deal with. You’ll feel defensive—after all, this person is apparently attacking you. Your natural reaction will be to dismiss what they say. But if you look past the aggressive wording, you may well find that the reviewer has a point. You shouldn’t have to take abuse from reviewers, but if you can rise above it, you may find gems buried in the crap.


Other reviewers like to copy edit. They find every little typo, complain about every breach of the punctuation rules, and note bad line breaks and other layout issues. Be careful when reacting to these reviewers. Obviously you can fix spelling issues, but you might want to chat with your publisher about punctuation—every publisher has a house style. And don’t sweat the layout stuff: your publisher should handle it for you (but you might want to double check the final proofs to double check that layout issues reported by reviewers have been fixed).


However, all these strange characters are extremes. You’ll probably find the majority of reviewers are supportive and helpful. Cherish these folks. If you have the opportunity to interact with them, do so. And be sure to thank particularly helpful reviewers somewhere in your book’s front matter.


Handling reviews can be tough. Try to remember as you grind your teeth that it is better to find these issues now, rather than after the ink has dried on the paper.



Sunday, March 18, 2007

Agile Mastery

I’m in London, having just finished presenting at QCon.




One of the tracks was called Reflecting on our Agile Journey - How do we reach Mastery? The more I think about that, the more the title worries me, because it seems to contain an implicit assumption—that mastery is some state that can be reached.


I think there are methodologies which can be mastered, where you can say “now I know it all.” I don’t believe agility is in that camp. For me, agility is all about the journey. Along the way, we’ll always be faced with forks in the road. The agile principles help us decide which to take. And we just carry on, enjoying the trip and doing our best along the way.



Sunday, March 11, 2007

SYWTWAB 5: Finding Your Voice

image





This is the fifth of a series of personal notes to people who may be thinking of writing (or who have embarked upon writing) a book. You’ll be able to find them all (eventually) by selecting the tag Writing A Book.


So far we’ve discussed the idea that a book is a narrative, and that the reader is the hero, undertaking a journey to learn new things (to boldly go…). I suggested that you might even want to start your book with an explicit story, something to draw the reader in. So just how do you write in such a way that the reader wants to join you? I don’t pretend to know, but there are some tricks that pragmatic authors use.


First and foremost, always remember that the book is about the reader, not the writer. Your job as author is to help the reader become proficient. You are a mentor, a guide. So always invite the reader along as you explore and explain.


The consistent use of pronouns is a great start. As the author, don’t try to hide behind a passive or stuffy voice. Don’t say “It is widely believed that…”. Don’t say “One could argue that…”. Just come out and say it: “I think that…”. Engage with your reader.


Your reader is a person too, so address them directly. Say things such as “You’ll need to install Xyz now” and “If you run the code now, you’ll see the following output.”.


But remember, you’re sharing a journey. So, whenever possible, try to use “we” and “our” to refer to the reader/author team. Don’t start a chapter with “In this chapter I’ll show you…”. Don’t start with “In this chapter you’ll find out…”. Instead, join the reader as they learn: “In this chapter we’ll see how…”.


Remember what I said about the Dreyfus model in SYWTBAW 3? Novices want to be told what to do. So don’t be afraid to use the imperative voice, particular early on the the book.


Here are a couple of paragraphs from the Rails book.



Back in xxxxx we sketched out the basic content of the products table. Now let’s turn that into reality. We need to create a database table and a Rails model that lets our application use that table.


The migration has a sequence number prefix (001), a name (create_products) and the file extension (.rb, because it’s a Ruby program). Let’s add the code to this file that creates the table in the database. Go to the db/migrate directory and open the file 001_create_products.rb. You’ll see two Ruby methods.



See how the reader and author share the journey: “We need to create”, “Let’s add the code”, and so on. At the same time, the reader is told what to do: “Go to the …” and “open the file”.


Layered on top of all these tricks with pronouns, the book has to be readable and engaging. You need to find a way of injecting energy and passion into your writing. You have to make people want to turn the page, to learn more about your subject. Clearly, technical knowledge helps. A good turn of phrase can make the content more interesting. Light, casual humor (particularly if it is off-beat or subtle) can keep the reader on his or her toes. Adding the occasional piece of trivia or background can add a little spice.


But all of this is predicated on one truth: the voice of a book has to be your voice. It has to be genuine; it has to be you. This is probably the most difficult challenge an author faces on a new book project.


So—how can you find this voice?


My best advice is to look at your book’s content and choose a chapter where you’re really comfortable with the technical material. Then just sit down and start writing. Write without reviewing what you’ve written. Don’t look back and correct stuff. Just write. Keep going for as long as you can. When you stop, save the file without rereading it. The next day, keep on writing. And continue the day after that. At some point, something will click in your head. You’ll find your writing style suddenly gels. Your prose will start to flow and the words will start to hang together well. You’ll know the feeling when it happens.


And when it does, here’s what you do. Save the file you’ve been working on, and promise yourself you won’t look at it again for a long, long time. Instead, choose another chapter and start writing. This time, you’re writing for real. Still keep the flow going, but now it’s OK (actually, it’s vital) to go back and read what you wrote. Ask the readers on your shoulder what they think. Because now you’re writing a book for real.


At some point you’ll have to revisit that original chapter. My advice? Just throw away the one you wrote initially and do it again. It’ll come out infinitely better than it would if you tried to make incremental improvements to your original prose.


When I write a new book, I follow this approach. I plan to throw away something like the first 30 or so pages. And, because I know I’m going to do it, it doesn’t worry me. I no longer have writer’s block. I no longer agonize over the voice in the first paragraph. I just churn it out until I feel comfortable, delete everything I wrote, and then start in for real.


In The Mythical Man Month, Fred Brooks advises project teams to expect to “throw the first one away.” That’s still good advice after 25 years, and it applies just as much to the writing process as it does to software development.


Give yourself time. Give your book a voice.