Showing posts with label fabjs. Show all posts
Showing posts with label fabjs. Show all posts

Thursday, September 23, 2010

Conditional (fab) HTML Apps

‹prev | My Chain | next›

Up tonight, I would like to get rid of the idle timeout alert() in my (fab) game. I have already done this once when I was playing with express. Now I would like to do the same on version 0.5 of fab.js.

First up, I update the good-bye function in the client to redirect (instead of alert()-ing) to the login page with an appropriate message:
    var goodbye = function() { 
window.location = window.location.protocol + '//' +
window.location.host +
window.location.pathname +
'?message=You have been logged out.' ;
};
player_list = new PlayerList(me, room, {onComplete: goodbye});
In the express.js version of the code, I had used flash/session to accomplish this. There is no flash in fab (yet), so query strings will have to suffice.

With that, I need to grab the message out of the query string and insert it into the HTML. Since I am using (fab) HTML apps to render the HTML, I need to make the message display a (fab) app as well:
  (route, /^\/board/)
( HTML )
( head )
( BODY )
( info )
( FORM, { id: "login", method: "get" } )
// form stuff
()
( DIV, { id: "room-container" } )()
() // BODY

() // HTML
()
Fortunately, I am getting pretty good at this:
function info(write) {
return write(function(write, head) {
Logger.info(inspect(head));
return write;
});
}
Well, maybe not too good. I know how to write a (fab) app that gets called with a response (write) stream. I also know that returning that response stream with a callback will allow any other upstream apps (e.g. the FORM and other HTML apps) to write to the response stream as well. Lastly, I know that the callback in this situation is called with the response stream, the request header (head) and the request body (which I do not need).

What I do not know (or at least do not remember off the top of my head) is where in the head the URL and query string are buried. To find out I access the /board resource with a query string of foo=bar and see what Logger.info tells me:
[INFO] { method: 'GET'
, headers:
{ host: 'localhost:4011'
, connection: 'keep-alive'
, accept: 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5'
, 'user-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.8 Safari/534.7'
, 'accept-encoding': 'gzip,deflate,sdch'
, 'accept-language': 'en-US,en;q=0.8'
, 'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}
, url:
{ href: '//localhost:4011/board?foo=bar'
, slashes: true
, host: 'localhost:4011'
, port: '4011'
, hostname: 'localhost'
, search: '?foo=bar'
, query: 'foo=bar'
, pathname: ''
, capture: []
}
}
Ah, in the url.query property. I know how to extract query parameters. node.js provides a querystring parse function to accomplish this:
function info(write) {
return write(function(write, head) {
var q = require('querystring').parse(head.url.query);
if (q.message)
write('<div id="info">' + q.message + '</div>');

return write;
});
}
And it turns out, that is all I need. When the idle timeout is broadcast, the goodbye function is called in the client, which redirects to the login page with a message and I see:



Easy enough! I think I am finally getting the hang of the new version of fab.js.

Day #235

Tuesday, September 21, 2010

More DRY with fab.js v0.5

‹prev | My Chain | next›

Up tonight I try to put my new fab.accept—an app written for the upcoming v0.5 release of fab.js—to some good use. Currently in my (fab) game, I have a player /status route that looks like:
 ( route, /^\/status/ )
( accept.HTML )
( PRE )
( player_status )
()
()
( accept.PLAIN )
(undefined, {headers: { "Content-Type": "text/plain"}})
( player_status )
()
()
Depending on the requested content type, the status of the players in the game are served up as HTML or plain text. The problem is that the HTML being served up is very small. Ideally I would like to serve it up as part of the same HTML template that the main player board is using:
  (route, /^\/board/)
( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css",
media: "screen",
rel: "stylesheet",
type: "text/css" } )
// Lots more style and script
( BODY )
// The actual body of the request
But how to re-use that? Back when I was first messing about with DRYing up my HTML, I found that I could have two different routes inside the same template (a rather unique fab.js feature):
  ( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css",
media: "screen",
rel: "stylesheet",
type: "text/css" } )
// Lots more style and script
()
( BODY )

(route, /^\/board/)
// the game board HTML

()

(route, /^\/status/)
( PRE )
( player_status )
()
()
I can no longer make use of that because the plain text response cannot include the HTML + HEAD + BODY tags that wrap both routes. Instead, I need to re-use the HTML, but only when the /status resource is requesting HTML. It turns out the upcoming version version of fab.js makes this easy by squirreling away partials in a local variable:
with ( fab )
with ( html ) head =

( fab )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css",
media: "screen",
rel: "stylesheet",
type: "text/css" } )
// Lots more style and script
()
();
I can then use that partial in both the /board route:
  (route, /^\/board/)
( HTML )
( head )
( BODY )
( FORM, { id: "login", method: "get" } )
( LABEL )
( "Name" )
( INPUT, { type: "text", name: "player" } )
()
( INPUT, { type: "submit", value: "Play" } )
()
( DIV, { id: "room-container" } )()
() // BODY

() // HTML
()
...and in the player /status route (body only when the client accepts HTML):
  ( route, /^\/status/ )
( accept.HTML )
( HTML )
( head )
( BODY )
( PRE )
( player_status )
()
()
()
()
( accept.PLAIN )
(undefined, {headers: { "Content-Type": "text/plain"}})
( player_status )
()
( "not found", { status: 404 } )
()
That is a surprisingly effective way to get simple partial support. Once again, I am left thinking that there may just be something to this upcoming version of fabjs.


Day #233

Monday, September 20, 2010

An npm Package of My Very Own (fab.accept)

‹prev | My Chain | next›

I have yet to create a npm package of my own. The fab.accept (fab) app from the other day affords me the perfect opportunity. It is an extremely small app, but that is one of the ideas behind the upcoming version of fab.js—small, modular apps.

First, I create a github repository for fab.accept. With that, I am ready to get started building my node package.

During this process, I make extensive use of the npm help subsystem. For instance, I read through npm help json to figure out how to write my package.json file:
{ "name": "fab.accept"
, "version": "0.0.1"
, "author": "Chris Strom"
, "description": "Simple (fab) app to respond to Accept HTTP headers"
, "homepage": "http://github.com/eee-c/fab.accept"
, "engines": ["node >= 0.2.0"]
, "main": "lib/main" }
There is also a dependencies attribute supported by npm. I opt not to use that here because it would require a version of fab.js (0.5) that is not yet in the npm registry.

After creating a lib/main.js with the code from the other day, I am ready to install locally:
cstrom@whitefall:~/repos/fab.accept$ npm install .
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm info install fab.accept@0.0.1
npm info activate fab.accept@0.0.1
npm info build Success: fab.accept@0.0.1
npm ok
Nice! It took me a little while to root through the npm help json documentation to figure out what I needed, but once I had that sorted out, it was pretty easy to get my package ready to be installed.

After that, I use it in my (fab) game to make sure that it is working. I had left some debug code in there and accessed an array incorrectly. Once I have those issues resolved, I am ready to publish to the npm registry.

I am not sure what sort of authorization I need (do I need to send an email to get an account?). Only one way to find out:
cstrom@whitefall:~/repos/fab.accept$ npm publish .
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm ERR! Failed PUT response undefined
npm ERR! Error: Cannot insert data into the registry without authorization
npm ERR! See: npm-adduser(1)
npm ERR! at request (/home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/utils/registry/request.js:38:15)
npm ERR! at PUT (/home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/utils/registry/request.js:129:34)
npm ERR! at Object.publish (/home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/utils/registry/publish.js:49:7)
npm ERR! at /home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/publish.js:15:14
npm ERR! at /home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/cache.js:178:11
npm ERR! at cb (/home/cstrom/.node_libraries/.npm/npm/0.1.27-12/package/lib/utils/graceful-fs.js:28:9)
npm ERR! at node.js:769:9
npm ERR! try running: 'npm help publish'
npm ERR! Report this *entire* log at <http://github.com/isaacs/npm/issues>
npm ERR! or email it to <npm-@googlegroups.com>
npm not ok
Beautiful. It might not have worked, but it tells me exactly what I need to do:
cstrom@whitefall:~/repos/fab.accept$ npm adduser
Username: eee-c
Password:
Email: npm@eeecooks.com
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm info adduser Authorized user eee-c
npm ok
And now...
cstrom@whitefall:~/repos/fab.accept$ npm publish .
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm WARN Sending authorization over insecure channel.
npm WARN Sending authorization over insecure channel.
npm WARN Sending authorization over insecure channel.
npm info publish done with upload
npm info publish uploaded
npm ok
Damn, that was pretty easy. This npm stuff is all right!

The only thing left for me is to install from the npm registry to make sure it all works. Before I can do that, I need to remove my locally installed package:
cstrom@whitefall:~/.node_libraries$ npm rm fab.accept
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm info uninstall safe to uninstall: fab.accept-0.0.1
npm info uninstall fab.accept-0.0.1 complete
npm ok
I also need to remove the previously installed package from the cache:
cstrom@whitefall:~/.node_libraries$ npm cache clean
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm ok
If I do not remove from the cache, then I am not testing the downloaded package. I have no reason to believe that anything will not work, but, as long as I am testing this, I might as well test what I think I am testing.

With that, I can install from the npm registry:
cstrom@whitefall:~/.node_libraries$ npm install fab.accept
npm info it worked if it ends with ok
npm info version 0.1.27-12
npm info fetch http://registry.npmjs.org/fab.accept/-/fab.accept-0.0.1.tgz
npm info install fab.accept@0.0.1
npm info activate fab.accept@0.0.1
npm info build Success: fab.accept@0.0.1
npm ok
Success!

This npm is pretty darn cool. I went from no package to published package in a single night. I cannot ask for much more than that.


Day #232

Saturday, September 18, 2010

Spike fab.accept

‹prev | My Chain | next›

Up today, I would like to explore code re-use of (fab) apps in the upcoming version 0.5 of fab.js. In my (fab) game, I have a dashboard resource that returns that list of players currently in the room:
      (route, /^\/player_status/)
( PRE )
( player_status )
() // PRE
() // route
Looking at this is the browser, I see:



Simple enough.

Now that I think about it though, I really prefer to see this from curl. It is nice to have it in HTML so I would just as soon not have to choose from one or the other. Aha! Code reuse opportunity!

I create a new /status resource that produces a simple text response:
  ( route, /^\/status/ )
(undefined, {headers: { "Content-Type": "text/plain"}})
( player_status )
()
I can access that via curl and see:
cstrom@whitefall:~/repos/my_fab_game$ curl http://localhost:4011/status
bob
fred

Cool! Quick, dirty resuable (fab) apps are quick and easy to roll. But...

There is the problem of using two different routes to represent the same thing. I would much prefer requesting a single resource and inspectint Accept headers so that something like his would work:
  ( route, /^\/status/ )
( accept, "text/html" )
( PRE )
( player_status )
()
()
(accept, "text/plain")
(undefined, {headers: { "Content-Type": "text/plain"}})
( player_status )
()
()
For this, I will need to write a new (fab) app—fab.accept.

I start as simple as possible:
fab.accept = function() {
function accept( write, mime_type ) {
return fab.stream( function( yes ) {
return fab.stream( function( no ) {
return write( function( write, head ) {
// console.log(inspect(head));
return ( head.headers.accept == mime_type ? yes : no )( write, head );
})();

});
});
}

return accept;
}();
That is close to boiler-plate (fab) code for ternary apps. Like all (fab) apps, it returns a function (accept()) that also returns a function. To get the conditional branch, that function also returns a function. If the condition matches (e.g. the Accept header matches), then the first application,
denoted by the yes local variable, is executed. Otherwise, the no application is executed (e.g. the next fab.accept or a 404).

I did have to use a console.log() (commented out), but only because I can never remember the attributes of the headers in fab.js / node.js. With that, I am ready to test fab.accept from the command line. There is no easy way to get curl to request plain text or HTML. Instead, I need to set the "Accept" HTTP header attribute with the -H option:
cstrom@whitefall:~/repos/my_fab_game$ curl -H "Accept: text/html" http://localhost:4011/status
<pre>bob
fred

</pre>
Nice, the HTML version of the resource is served up in response to "Accept: text/html". Can I get the plaint text version?
cstrom@whitefall:~/repos/my_fab_game$ curl -H "Accept: text/plain" http://localhost:4011/status
bob
foo

Nice!

I still have to polish off fab.accept (and it would be nice to have some tests), but that is a nice stopping point for the night. It is pretty cool that it so easy to write these little things!


Day #230

Friday, September 17, 2010

How to Write Multiple Strings to a Single fab.stream

‹prev | My Chain | next›

I have been struggling a bit with an edge case of fab.stream—a (fab) app from the upcoming version 0.5 of fab.js. To explore that difficulty, I break down the problem into a very small (fab) app:
with ( fab )
with ( html )

( fab )

// Listen on the FAB port and establish the faye server
( listen, 0xFAB )

( PRE )
( callback_test )
() // /pre

();
As I found out last night, HTML (fab) apps that wrap content (like <pre>) do so by writing to the response stream, then reading from the upstream app response (e.g. callback_test above), then writing the closing tag to the response stream. The end result being that callback_test has upstream data in the response when it gets invoked.

It makes perfect sense but ended up causing trouble in certain situations. Specifically, when the upstream app writes multiple times to the response stream, then the HTML app will send multiple close tags.

This does not occur for simple apps. For instance if I grab a string foo from a function and write it to the response stream, then write the hard-coded string "bar" to the response stream like so:
function non_stream_test(write) {
var foo = function_that_returns_foo();
return write(foo)
("bar");
}
...It just works. Accessing this resource via curl returns:
cstrom@whitefall:~$ curl -N http://localhost:4011/
<pre>foobar</pre>
The foo + bar test is wrapped in the <pre> tag as expected.

Of course, I could also just as easily written to the response stream once like so:
function non_stream_test(write) {
var foo = function_that_returns_foo();
return write(foo + "bar");
}
My problem is that I think the first way is just so cool.

Anyhow.

As I mentioned, the above cases just work. Problems arise when dealing will callbacks—for example, looking up a list of players in a database. Since I am using Javascript, the database lookup expects to be called with function that it can invoke once it has retrieved the list of player. This is Javascript, so it is quite common.

In that case, I cannot return a write() of data. I only have access to the data inside the callback. Calling return inside the callback will return from the callback, not the function that originally requested the data. Fortunately, in v0.5 of fabjs, there is fab.stream to handle this.

Consider a silly callback that invokes the supplied function with a single argument, "foo":
function callback_with_foo(fn) { fn("foo") }
I can then get that value, along with "bar" by doing something like:
function callback_test(write) {
return write(function(write) {
return fab.stream(function(stream) {
callback_with_foo(function (foo) {
stream(write(foo));
stream(write("bar"));
stream(write());
});

});
});
}
This is the situation in which I will get a second closing <pre> tag:
cstrom@whitefall:~$ curl -N http://localhost:4011/
<pre>foo</pre>bar</pre>
Each stream(write()) still has the closing tag in the upstream just waiting to be sent back to the browser. And merrily sent it is.

For the past 3 nights, I have been banging my head against the proverbial wall trying to figure out a way around this. Today, it finally occurred to me that there is no need. I cannot think of a use case in which I would want to write twice in a callback and, even if I could, then it might warrant a bit more firepower than (fab) HTML apps. A perfectly cromulent solution is to simply accumulate the string data and then write it once:
function callback_test(write) {
return write(function(write) {
return fab.stream(function(stream) {
callback_with_foo(function (foo) {
stream(write(foo + "bar"));
stream(write());
});
});
});
}
(the second stream() with an empty write() signals to stream that it is done sending data)

With that, I get my properly wrapped text from a callback:
cstrom@whitefall:~$ curl -N http://localhost:4011/
<pre>foobar</pre>
Sometimes I can really obsess over very tiny, immaterial details. Such is my burden.

Tomorrow, I am definitely looking at something beside fab.stream!


Day #229

Thursday, September 16, 2010

The Case of the Extra Stream Data

‹prev | My Chain | next›

I continue my exploration of the upcoming version 0.5 of fab.js. I admit that I am getting a bit bogged down here, but I believe that understanding is slowing spreading. Hopefully tonight will prove to be a break through. Last night I explored the various degenerative cases of fab.stream. That provided some insight. Tonight I take a step back to see if I can apply that knowledge.

I continue to try to get my player_status (fab) app to embed itself inside HTML template apps:
      (route, /^\/player_status/)
( PRE )
( player_status )
() // PRE
() // route
That is a nice, easy-to-read representation of what I want to do. For the /player_status route, the output of the player_status (fab) app should be wrapped in a <pre> tag.

That is actually pretty easy to do—if the player data were static:
function player_status(write) {
return write("player_status 01")
("\n")
("player_status 02")
("\n")
("player_status 03")
("\n");
}
Here, player_status is a normal (fab) app, invoked with the write stream for the response. Invoking that stream with a string argument, "player_status 01", sends the data in the response and also returns the downstream listener in case there is more to say (i.e. "\n", "player_status 02", etc.).

With that, I get my expected 3 player statuses inside a <pre> tag:



My problem is that I need to grab the player status from CouchDB via node-couchdb. That means callbacks. Luckily, even in the infant stages of v0.5, fab.js supplies the fab.stream app to "hit the pause button" until the data is sent back.

How does this cause problems? Well, if I write multiple times to the fab.stream, I get output like this:



And HTML that ends with:
<pre>player_status 02</pre></body></html> 
</pre></body></html>player_status 03</pre></body></html>
</pre></body></html>player_status 01</pre></body></html>
</pre></body></html>
I get this even with simple versions without the callbacks, just multiple stream writes:
function player_status( write ) {
return write(function(write) {
return fab.stream(function(stream) {
stream(write("player_status 01"));
stream(write("\n"));
stream(write("player_status 02"));
stream(write("\n"));
stream(write("player_status 03"));
stream(write("\n"));
stream(write());degenerative
});
});
}
In all of the use-cases of fab.stream that I considered last night, I assumed that there was no queue—no initial list of data that would always be written after the explicit writes. That assumption is valid—the queue would be a second argument to fab.stream. Here, I am only supplying a single callback to be invoked—no queue.

My mistake was in not recognizing that there is a second way to build up the queue. The other means of building up the queue is through upstream data. Looking at the fab chain, there does not seem to be any upstream data:
      (route, /^\/player_status/)
( PRE )
( player_status )
() // PRE
() // route
The empty argument function calls should close the HTML tag (and the route) with no data, right? This is were I went wrong. The PRE (fab) app, like all HTML apps, actually creates upstream data beyond player_status. Thinking about it, it has to this in order to create the closing </pre> tag. These HTML (fab) apps write to the normal response stream, then reads from the player_status app while supplying that downstream data.

Taking a peak inside the fab.elem (fab) app, we can see where this occurs:
  function elem( name, isVoid ) {
return function( write, obj ) {
write = fab.concat( write )
write = write( "<" + name );
write = attrs( write )( obj )( ">" );

if ( isVoid ) return write;

return function read( arg ) {
if ( !arguments.length ) return write( "</" + name + ">" );

write = write.apply( undefined, arguments );
return read;

};
}
If the upstream app (player_status in this case) returns data, then write that data to the response. If the upstream is done with data (as indicated by no arguments), then write the closing tag.

The end result is that every time I stream new data back, these closing tags are coming along for the ride:
<pre>player_status 02</pre></body></html> 
</pre></body></html>player_status 03</pre></body></html>
</pre></body></html>player_status 01</pre></body></html>
</pre></body></html>
In the end, I can get away with (fab) apps with multiple streams only if I am sure that there is no upstream data on the way. Dang.

Armed with that knowledge, I do believe that I can resolve my issue, but I will leave that for tomorrow. I need to get some sleep before Ruby DCamp tomorrow.


Day #228

Wednesday, September 15, 2010

Simple fab.stream

‹prev | My Chain | next›

Up tonight, a brief investigation of fab.stream in fab.js v0.5:
fab.stream = function stream( write, queue ) {
queue = queue || [];

var length = queue.length;

function drain( write, req ) {
for ( var i = 0; i < length; ) {
write = write.apply( undefined, queue[ i++ ] );
}

return write;
};

return function read() {
if ( !arguments.length ) return write ? write( drain ) : drain;

queue[ length++ ] = arguments;
return read;
}
}
It takes a callback argument along with a queue of items that can be replayed. Depending on what the upstream app from which fab.stream reads does, the queue can be further increased. For my purpose tonight, the queue is empty as is the upstream app call and I am supplying a callback, which reduces the function to this:
fab.stream = function stream( write ) {
function drain( write ) {
return write;
};

return function read() {
return write( drain )
}
}
So, when I create a fab.stream thusly:
return fab.stream(function callback (stream) {
// stream stuff
})()
... fab.stream returns the read() function, which is evaluated immediately by the trailing open-close parenthesis after the fab.stream() invocation. This, in turn, returns the result of invoking the function callback(), supplying the drain function as the stream callback.

Thus, anytime I call stream inside the callback() function, I am actually returning whatever function/callback/value I supply to it:
return fab.stream(function callback (stream) {
stream("foo");
})()
...would return the string "foo".

That is a long way to go to get access to the string "foo", so obviously that is not the primary reason to use fab.stream. In this case, with no queue and no upstream apps, the reason to use fab.stream is to be able to return the value of yet another callback/async function:
node> function async(cb) { return cb("foo")}
node> fab.stream(function callback (stream) { return stream( async ( function(v) { return v } ) ) } ) ()
'foo'
Well, I don't think I understand my problem from last night any better at this point, but I do think I'm getting a grip on fab.stream.

Day #227

Tuesday, September 14, 2010

DRY HTML in Fab.js v0.5

‹prev | My Chain | next›

While rooting through the sample apps in the upcoming v0.5 release of fab.js, I noticed an interesting feature. It seems as though it is possible to re-use the new HTML (fab) apps by embedding routes inside of them. For instance, I can re-use the HTML head for multiple routes in my (fab) game:
with ( fab )
with ( html )

( fab )

// Listen on the FAB port and establish the faye server
( listen, 0xFAB, attach_faye )

( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css",
media: "screen",
rel: "stylesheet",
type: "text/css" } )
( SCRIPT, { src: "/javascript/jquery-min.js",
type: "application/javascript" } )()

// More javascript libs///

( SCRIPT, { type: "application/javascript" } )
( board_js_string )
()

()
( BODY )

(route, /^\/board/)

( FORM, { id: "login", method: "get" } )
( LABEL )
( "Name" )
( INPUT, { type: "text", name: "player" } )
()
( INPUT, { type: "submit", value: "Play" } )
()
( DIV, { id: "room-container" } )()
()

(route, /^\/player_status/)
( PRE )
( "player_status 01" )
( "\n" )
( "player_status 02" )
( "\n" )
( "player_status 03" )
( "\n" )
()
()

() // BODY
() // HTML
Checking out the second resource, /player_status, in the browser:



Nice! I get my header, "My (fab) Game", and my styles, but everything else comes from under the (route, /^\/player_status/) resource.

It is not all sunshine and roses, however. Ideally, I would like to embed my player_status (fab) app inside that resource:
      (route, /^\/player_status/)
( PRE )
( player_status )
()
// ...

function player_status(write) {
return write(function(write) {
return fab.stream(function(stream) {
// stream(write(undefined, { headers: { "Content-Type": "text/plain"} }));
players.all(function(list) {
list.forEach(function(player) {
stream(write(player._id + "\n"));
});
stream(write("\n"));
stream(write());
});
});
});
}
The player_status function was originally written as a standalone app. Now that it is embedded in HTML, I have to remove the "Content-Type" header stream write. Even with that, when I access the list of players, I get:



The player, "bob" shows up in the status section, but "fred" and "foo" are outside. Checking out the HTML, I find:
<pre>bob
</pre></body></html>foo
</pre></body></html>fred
</pre></body></html>
</pre></body></html>
Ew.

I have already seen that streaming text ("player_status 01", "player_status 02", etc.) works when re-using HTML (fab) apps. Is the problem with fab.stream, my use of fab.stream, or with dynamic functions? If it is either of the first two, I will have to defer investigation until another night, but I can convert the player_status (fab) app to a simple, dynamic app:
function player_status( write ) {
return function read( data ) {
return write("player_status 01")
("\n")
("player_status 02")
("\n")
("player_status 03")
("\n");
};
}
That produces the same results as my original, simple app—in other words, it works. Thus the problem is either in fab.stream or my use of fab.stream in player_status:
function player_status(write) {
return write(function(write) {
return fab.stream(function(stream) {
players.all(function(list) {
list.forEach(function(player) {
stream(write(player._id + "\n"));
});
stream(write("\n"));
stream(write());
});
});
});
}
I will pick up tomorrow with further investigation.


Day #226

Monday, September 13, 2010

HTML (fab) Apps in 0.5

‹prev | My Chain | next›

Up tonight, I would like to play about with the new HTML (fab) apps in the upcoming v0.5 of fab.js. I doubt I would use them for significant sized pages, but for small pages, they could very well be ideal.

I have a medium sized HTML page (~50 lines) in my (fab) game, so tonight, I hope to make a quick switch to (fab) html.

I start small, replacing the route to the game board with (fab) html that should produce the text "foo" in an <h1>:
  (route, /^\/board/)
( H1 )( "Foo" )()
()
Accessing that resource via curl, I do, indeed see the expected HTML:
<h1>Foo</h1>
Nice. I kinda like how the empty stream call closes the HTML tag. To wrap the H1 tag inside an <html> tag, I similarly need to open the tag, then close it with an empty function call:
  (route, /^\/board/)
( HTML )
( H1 )( "Foo" )()
()
()
I can then add <head> and <body sections to my page:
  (route, /^\/board/)
( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
()
( BODY )
( H1 )( "Foo" )()
()
()
()
A quick sanity check, and yes, I am getting the HTML I want:
<html><head><title>My (fab) Game</title></head><body><h1>Foo</h1></body></html>
Something that I have not done so far is adding attributes to tags. Again, I rather like how this is accomplished in fab.js v0.5:
  (route, /^\/board/)
( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css", media: "screen", rel: "stylesheet", type:"text/css" } )()
()
( BODY )
( H1 )( "Foo" )()
()
()
()
The resulting HTML:
<html><head><title>My (fab) Game</title><link href="/stylesheets/board.css" media="screen" rel="stylesheet" type="text/css"></head></html><body><h1>Foo</h1></body>
Nice. At this point, I am ready to replace the entire page. Mostly, I add javascript tags, but also some in-page javascript and some input fields:
  (route, /^\/board/)
( HTML )
( HEAD )
( TITLE )( "My (fab) Game" )()
( LINK, { href: "/stylesheets/board.css",
media: "screen",
rel: "stylesheet",
type: "text/css" } )()
( SCRIPT, { src: "/javascript/jquery-min.js",
type: "application/javascript" } )()

( SCRIPT, { src: "/javascript/json2.js",
type: "application/javascript" } )()

( SCRIPT, { src: "/faye.js",
type: "text/javascript" } )()

( SCRIPT, { src: "/javascript/raphael-min.js",
type: "application/javascript" } )()
( SCRIPT, { src: "/javascript/player.js",
type: "application/javascript" } )()
( SCRIPT, { src: "/javascript/player_list.js",
type: "application/javascript" } )()
( SCRIPT, { src: "/javascript/room.js",
type: "application/javascript" } )()

( SCRIPT, { type: "application/javascript" } )
( " var player_list; \
\
$(function() { \
var kv = location.search.substr(1).split(/=/); \
if (kv[0] == 'player' && kv[1]) { \
$('#login').hide(); \
\
// More player setup here... \
} \
}); \
\
" )
()


()
( BODY )
( FORM, { id: "login", method: "get" } )
( LABEL )
( "Name" )
( INPUT, { type: "text", name: "player" } )
()
( INPUT, { type: "submit", value: "Play" } )
()
( DIV, { id: "room-container" } )()
()
()
()
The in-page Javascript is a bit ugly. I really miss HERE docs at times like these. The one gotcha that I found while adding the remaining HTML was the ( INPUT ) app—it does not appreciate having a closing empty function call:
cstrom@whitefall:~/repos/my_fab_game$ ./game.js
[INFO] Starting up...
Caught exception: TypeError: Cannot call method 'apply' of undefined
at drain (/home/cstrom/.node_libraries/fab/index.js:28:21)
at read (/home/cstrom/.node_libraries/fab/index.js:6:27)
at Object.<anonymous> (/home/cstrom/repos/my_fab_game/game.js:185:4)
at Module._compile (node.js:462:23)
at Module._loadScriptSync (node.js:469:10)
at Module.loadSync (node.js:338:12)
at Object.runMain (node.js:522:24)
at Array. (node.js:755:12)
at EventEmitter._tickCallback (node.js:55:22)
at node.js:769:9
That, and other "closed" tags (AREA BASE BR COL COMMAND EMBED HR IMG INPUT KEYGEN LINK META PARAM SOURCE WBR) do not need the closing tags and cause confusion in deep (fab) structures.

But all in all, I rather like the new (fab) templating system. It is a cheap easy way to get HTML into my (fab) apps.


Day #225

Saturday, September 11, 2010

URL Parsing in Node.js 0.2.0/0.2.1

‹prev | My Chain | next›

I nearly finished my investigation into the new hotness that will be v0.5 fab.js last night. Up tonight, I plan to investigate the built-in HTML templating tools in the upcoming fab.js.

My initial thought on the new templating is that it could be very useful for small pages, but might get painful for more involved stuff. I have a medium sized HTML page in my (fab) game that ought to be a good starting point.

Unfortunately, when I try to access the server, I get nothing but 404s. Geez. I thought this worked the last time I was working with it. As far as git status is concerned, I have not made any changes. Could it be the new version (0.2.1) of node.js that I installed last night?

Ugh. Looks like there will be no investigation of HTML in fabjs tonight.

I begin troubleshooting with curl:
cstrom@whitefall:~$ curl -i http://localhost:4011/javascript/raphael.js
HTTP/1.1 404 Not Found
Content-Type: text/html
Connection: keep-alive
Transfer-Encoding: chunked

<p>ENOENT, No such file or directory './html//localhost:4011/javascript/raphael.js.html'</p>
Whoa. That is odd. It should be looking for just the raphael.js file, but it looks like it is trying to find /localhost:4011/javascript/raphael.js.html—everything after the HTTP protocol.

I add some spy code to see what the request URL is:
          console.log(inspect(head));
Checking the backend, I find:
{ method: 'GET'
, headers:
{ 'user-agent': 'curl/7.19.7 (i486-pc-linux-gnu) libcurl/7.19.7 OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15'
, host: 'localhost:4011'
, accept: '*/*'
}
, url:
{ href: '//localhost:4011/javascript/raphael.js'
, pathname: '//localhost:4011//raphael.js'
, capture: []
}
}
Pathname is "//localhost:4011//raphael.js"? What is going on there?

I find it hard to believe that a regression in node.js could have occurred, but I will start there. I set up the basic hello world app with some console debug statements to see what the URL and pathname are:
#!/usr/bin/env node

var http = require('http');

var inspect = require("sys").inspect;

http.createServer(function (request, response) {
console.log(request.url);
console.log(require('url').parse(request.url).pathname);


response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');
I then access http://localhost:8124/foo via curl and see the following in the server output:
cstrom@whitefall:~/tmp$ ./test.js
Server running at http://127.0.0.1:8124/
/foo
/foo
OK. That seems to work just fine.

Looking back in the fab.js code, I see that the head value is being set thusly:
        {
method: req.method,
headers: req.headers,
url: url.parse( "//" + req.headers.host + req.url )
}
Hunh. That seems like and strange URL to ask url.parse to parse. It also looks very much like the bogus pathname that I am seeing. I do believe that I am on to something here. I console.log that in my test nodejs server:
http.createServer(function (request, response) {
console.log(request.url);
console.log(require('url').parse(request.url).pathname);
console.log(require('url').parse( "//" + request.headers.host + request.url ));

response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
... and, sure enough, I get that odd-looking URL:
{ href: '//localhost:8124/foo'
, pathname: '//localhost:8124/foo'
}
Switching back to node 0.2.0, I see this instead:
{ href: '//localhost:8124/foo'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}
Aha! So something has changed in between node 0.2.0 and 0.2.1—parsing weird URLs.

A side-by-side comparison:
0.2.00.2.1
node> require('url').parse('/foo')
{ href: '/foo', pathname: '/foo' }

node> require('url').parse('//localhost:8124/foo')
{ href: '//localhost:8124/foo'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}

node> require('url').parse('http://localhost:8124/foo')
{ href: 'http://localhost:8124/foo'
, protocol: 'http:'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}
node> require('url').parse('/foo') 
{ href: '/foo', pathname: '/foo' }

node> require('url').parse('//localhost:8124/foo')
{ href: '//localhost:8124/foo'
, pathname: '//localhost:8124/foo'
}





node> require('url').parse('http://localhost:8124/foo')
{ href: 'http://localhost:8124/foo'
, protocol: 'http:'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}
I would hazard to guess that Jed opted for the odd URL so as not to presume a protocol scheme. Since that works fine with nodejs 0.2.0, but not 0.2.1, this not longer seems to be a viable option. Since the behaviors with an HTTP scheme are identical between the two versions, I opt for that in my fork of fab.js v0.5:
        {
method: req.method,
headers: req.headers,
url: url.parse( "http://" + req.headers.host + req.url )
}
And just like that, my (fab) game is working with node.js 0.2.1.

OK tomorrow I will fiddle with the HTML (fab) apps.


Day #223

Friday, September 10, 2010

Fab.js and POST Data

‹prev | My Chain | next›

First up today, I write a v0.5 fab.js app that reads from downstream (e.g. from the browser). I struggled last night, but Jed has pushed my in the right direction.

Oh, all right, he told me how to do it.

I continue working with the following application:
// Don't crash on errors
process.on('uncaughtException', function (err) {
console.log('[uncaughtException] ' + err.stack);
});

with ( require('fab') )

( fab )

// Listen on the FAB port
( listen, 0xFAB )

(prepend_hello)
(read_from_downstream)
(prepend_hello)
()

();
The prepend_hello (fab) apps do just that: prepend the text " hello " before whatever the previous app streams back. The read_from_downstream app should read whatever the downstream (the web client) sends / POSTs, and send it back.

So let's get started with the app:
function read_from_downstream(write) {
return write( function read(write, obj, body) {
body(function(chunk){
console.log("chunk: " + chunk);
}
);
return write;
});
}
To get access to POST data, I need to read from the body() stream. That requires a callback. For starters, I just use an anonymous function that logs the chunks of data being read.

After starting up the server, I POST to the server with curl:
cstrom@whitefall:~$ curl http://localhost:4011/ -d Bar 
hello hello
The output is as expected (" hello " prepended on itself)—the read_from_downstream app is just returning the write stream, which connects the streams above and below it together. Of more interest is the server output:
cstrom@whitefall:~/tmp$ ./test.js
chunk: Bar
chunk: undefined
The anonymous callback supplied to the body stream returns my POST data and then undefined. I need to keep that undefined in mind because calling write(undefined) is not the same as calling write().

Now to write the POST data in the response stream. Since I am using a callback to access the body stream, I need to accumulate all of the chunks in that callback before sending back in the response stream. That is the purpose to the fab.stream app—anything written to the stream will go into a queue to be released when write() is invoked. Thus, the app becomes:
function read_from_downstream(write) {
return write( function read(write, obj, body) {
return fab.stream(function(stream) {
body(function(chunk){
console.log("chunk: " + chunk);
chunk ? stream(write(chunk)) : stream(write());
});
});
});
}
If I have done everything correctly, my stack:
  (prepend_hello)
(read_from_downstream)
(prepend_hello)
()
Should prepend " hello " onto nothing, then prepend the POST data to that, then prepend " hello " onto that. And, that is just what I see in curl:
cstrom@whitefall:~$ curl http://localhost:4011/ -d Bar 
hello Bar hello
cstrom@whitefall:~$ curl http://localhost:4011/ -d Foo
hello Foo hello
With a minor success under my belt, I call it a night. I need to learn from the past week that pushing past simple success makes for a tired Chris. Up tomorrow: I will play with some of the new (fab) HTML apps.


Day #222

Thursday, September 9, 2010

Fun with Simple Fab Apps (in v0.5)

‹prev | My Chain | next›

I got over the hump with the new version (0.5) of fab.js. Tonight I would like to sanity check myself with what Jed describes as the very simplest v0.5 (fab) apps.

Again tonight, I will be using a fairly simple skeleton (fab) application:
// Don't crash on errors
process.on('uncaughtException', function (err) {
console.log('Runaway exception: ' + err.stack);
});

with ( require('fab') )

( fab )

// Listen on the FAB port
( listen, 0xFAB )

(prepend_hello)
(simplest_app)
(prepend_hello)
()

();

function prepend_hello(write) {
return function read(body) {
return write(" hello ")(body);
};
}
The prepend_hello() (fab) app will prepend the text " hello " to the current stream, which ought to aid in seeing what is happening.

First up, the simplest possible app, which should pass the stream back downstream:
function simplest_app(write) {
return write;
}
When I access the server via curl, I see:
cstrom@whitefall:~$ curl http://localhost:4011/ -d Foo
hello hello
Ah, interesting. I would have expected the write to short-circuit the stream, ignoring the last prepend_hello. Instead it does nothing—connecting the two streams, making no changes.

Next, I replace the simplest_app with the second simplest app:
function second_simplest_app(write) {
return write( "foo" );
}
Accessing the server via curl, I see:
cstrom@whitefall:~$ curl http://localhost:4011/ -d Foo
hello foo hello
Given the behavior of the simplest app, the behavior of the second simplest app is to be expected.

Last up tonight, I wonder how I might grab downstream body data. Ultimately, I am stumped. I can obtain the request header info with:
function read_from_downstream(write) {
return write( function read(write, obj, hunh) {
if (obj.body) return write(obj.body);
return write(obj.url.pathname);
});
}
But I am stumped how to re-read from the downstream app so that I could access the request body. From curl, I get:
curl http://localhost:4011/ -d Foo 
hello / hello
Ultimately, I am not too concerned. Fab is going to be changing quite a bit in the upcoming days, so this will get sorted out.

Day #221

Wednesday, September 8, 2010

Returning Write, Not Read

‹prev | My Chain | next›

Tonight I continue my exploration of the pre-release v0.5 of fab.js. Last night I got it working exactly like I wanted, but I did not understand why it worked. Since programming by coincidence is a cardinal sin of programming, I need to investigate a bit further.

To get understanding, I need to remove all my cruft and play with an absolute minimal (fab) application:
// Don't crash on errors
process.on('uncaughtException', function (err) {
console.log('Runaway exception: ' + err.stack);
});

with ( require('fab') )

( fab )

// Listen on the FAB port
( listen, 0xFAB )

( test )
()

();
I will be fiddling with the test (fab) app tonight. The simplest (fab) app, in v0.5, looks like:
function test(write) {
return function read() {
return write(" bar\n")(" baz\n");
};
}
Simple enough: the test (fab) app is called with a write function / stream. I can write data, which returns a copy of the write function to receive more data (e.g. " baz\n"), which returns another copy of itself to be returned when the read() function is invoked.

When accessing any resource on the running server, I see:
cstrom@whitefall:~$ curl http://localhost:4011/ -i
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

bar
baz
Nothing to surprising there.

The simplest form of (fab) app that I do not understand is this:
function test(write) {
return write(function(write) {
return write(" bar\n")(" baz\n");
});
}
Checking the output with this version in place, I see that it is working exactly the same as the previous version:
cstrom@whitefall:~$ curl http://localhost:4011/ -i
HTTP/1.1 200 OK
Connection: keep-alive
Transfer-Encoding: chunked

bar
baz
How is that possible?

In the canonical (fab) app example, I return a read() callback that will be invoked on incoming request and will be called with an upstream (further from the browser) response stream to decorate as it likes. In other words, I am returning a callback that will be invoked for possible upstream reading.

So how does the second example work?
function test(write) {
return write(function(write) {
return write(" bar\n")(" baz\n");
});
}
Invoking write() will always return a downstream write stream. If that downstream write stream is invoked like the previous read callback, how does that ever make it to the browser.

I cheat to get the answer. And by cheat, I raise an exception, by referencing an undeclared variable, inside the write() method's callback:
function test(write) {
return write(function(write) {
asdf;
return write(" bar\n")(" baz\n");
});
}
When I access the server with curl, I see this stacktrace in the backend:
Runaway exception: ReferenceError: asdf is not defined
at /home/cstrom/tmp/test.js:36:5
at read (/home/cstrom/.node_libraries/fab/index.js:186:18)
at drain (/home/cstrom/.node_libraries/fab/index.js:31:21)
at Server.<anonymous> (/home/cstrom/.node_libraries/fab/index.js:69:19)
at Server.emit (events:33:26)
at HTTPParser.onIncoming (http:830:10)
at HTTPParser.onHeadersComplete (http:87:31)
at Stream.ondata (http:762:22)
at IOWatcher.callback (net:494:29)
at node.js:764:9
The last stack point in (fab) proper is inside the fab.render app, which is used to stream data back to the browser:
fab.render = function( write ) {
var args = [].slice.call( arguments );

return function read( obj ) {
if ( obj && obj.apply ) {
args[ 0 ] = read;
return obj.apply( undefined, args );
}

write = write.apply( undefined, arguments );

return arguments.length ? read : write;
}
}
Ah! So by supplying the callback to write(), one defers the evaluation (via apply()) of that app until sending data back to the client. The read() function defined inside fab.render is then sent to the callback as args[0]. The callback thinks that it is writing:
function test(write) {
return write(function(write) {
return write(" bar\n")(" baz\n");
}
);
}
...and fab.render thinks that it is reading from an ordinary upstream app.

Good stuff. I believe that there is still a little more for me to wrap my brain around in the new v0.5 fabjs, but comprehension is beginning to spread.


Day #220

Tuesday, September 7, 2010

Upstream Apps in Fab.js v.0.5

‹prev | My Chain | next›

I crashed and burned last night trying to write my own v0.5 fab.js app for my (fab) game. Tonight I hope to do a bit better.

I am trying to provide a /player_status resource that will return a plain text representation of all the players currently in a room:
  (route, /^\/player_status/)
( player_status )
()
The players are all stored in CouchDB. To get all of them, I have an all callback method on the players object that can be used something like:
      players.all(function(list) {
list.forEach(function(player) {
console.log(player);
});
});
Although I kinda/sorta got things working last night, I am going to toss that work. I ended up with very weird stacktraces that leads me to believe that I am on the wrong track.

The normal skeleton of a (fab) app looks something like this:
    fab.myApp = function( write ) {
return function read( body ) {
var done;

// app logic here

return done ? write : read;
}
}
I cannot use that in this case because there are no upstream (further from the browser) apps to be read.

After much fiddling, I end up with this:
function player_status(write) {
return write(function(write) {
return fab.stream(function(stream) {
stream(write(undefined, { headers: { "Content-Type": "text/plain"} }));
players.all(function(list) {
list.forEach(function(player) {
stream(write(player._id + "\n"));
});
stream(write("\n"));
stream(write());
});
});
});
Amazingly, this works:
cstrom@whitefall:~$ curl http://localhost:4011/player_status -i
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

bob
I must confess that I am a little puzzled why it works. My best guess, the first line of the app body:
  return write(function(write) {
Behaves identically to (fab) middleware with an upstream app:
  (route, /^\/player_status/)
( middleware )
( upstream )
()
My player_status is writing back to the browser, reading from the supplied anonymous function.

The next line, I find bizarre:
    return fab.stream(function(stream) {
The fab.stream app queues up upstream messages to be sent back to the browser. The fab.stream app knows to send the entire queue when the upstream app signals the last of its output with an empty argument list. In this case, the anonymous function supplied as the argument to fab.stream serves as the upstream app (the signal to terminate is the last line:
      function(list) {
list.forEach(function(player) {
stream(write(player._id + "\n"));
});
stream(write("\n"));
stream(write());
});
The reason that I find this bizarre is that fab.stream takes a single argument—the downstream / write stream:
fab.stream = function stream( write, queue ) {
queue = queue || [];

//...

return function read() {
if ( !arguments.length ) return write ? write( drain ) : drain;

queue[ length++ ] = arguments;
return read;
}
}
In my working-through-a-small-miracle code, however, I am not supplying a write stream to the browser. I am supplying the opposite—an upstream app from which data will be read.

Somehow the read() function inside fab.stream, the function that is responsible for writing back downstream to the browser, is being supplied as the argument to the anonymous function that is supplied to fab.stream.

I believe that this is due to if-function-then-apply-with-arguments logic in the main fab app itself. fab.stream returns the read() function, which is then applied with the arguments to fab.stream—my fake downstream app in this case.

Ugh. Not sure about that explanation. I kinda/sorta think I understand, but that is not true understanding.

I think I'll sleep on in at this point and pick back up with more investigation tomorrow.

Day #219

Monday, September 6, 2010

Getting Started Writing v0.5 Fab.js Apps

‹prev | My Chain | next›

Today, I hope to write my first version 0.5 fab.js app. In my (fab) game, I would like a resource that lists the status of all players currently in the game.

To start with, I create a very simple resource:
  (route, /^\/player_status/)
( undefined, { headers: { "Content-Type": "text/plain"} } )
( "hello\n" )
()
It bothers me that I do not understand the undefined thing. But checking it with curl, I see that this is working:
cstrom@whitefall:~$ curl http://localhost:4011/player_status -i
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

hello
I will not be able to render my player_status inside function arguments—I need to iterate over all of my players. For that, I will need a v0.5 (fab) app. Walking before I run, I convert my "hello" arguments into the skeleton of my fab app:
function player_status(write) {
write = write(undefined, { headers: { "Content-Type": "text/plain"} } );
return function read() {
return write("hello\n");
};
}
A-ha! Now I see what the undefined argument is for—it is used to indicate that no body is being sent back in the response, just headers.

I replace my "hello" arguments with a call to player_status:
  (route, /^\/player_status/)
( player_status )
()
Then I start the app up and check out the response with curl:
cstrom@whitefall:~$ curl http://localhost:4011/player_status -i
curl: (52) Empty reply from server
There is no crash in my backend—no log output at all. Trying to access the game board is useless as well. It is as if the server is completely non-responsive, though in a non-crashy way.

It takes me quite a while to realize that I need to add an additional set of parentheses:
  (route, /^\/player_status/)
( player_status )
()
()
One set of parentheses finishes the player_status chain, the other completes the route chain. That is new to v0.5 and will take a bit of getting used to. Actually, no it won't. I think I have learned my lesson at this point.

Except...

When I try to convert player_status to dynamically return the list of players, I hit a problem. It seems as though the function is only evaluated at compile time, making it of little value for describing player statuses. Ugh.

I end up fiddling quite a bit and return to the player_status call without the trailing parentheses:
  (route, /^\/player_status/)
( player_status )
()
I then fake an upstream app from which player_status can read:
function player_status(write) {
write = write(undefined, { headers: { "Content-Type": "text/plain"} } );

return write(function(write) {
players.all(function(list) {
list.forEach(function(player) {
write = write(player._id + "\n");
});
return write();
}
);
});
That works from curl:
cstrom@whitefall:curl http://localhost:4011/player_status -i
HTTP/1.1 200 OK
Content-Type: text/plain
Connection: keep-alive
Transfer-Encoding: chunked

bob
But, I have an uncaught exception in my backend code:
Caught exception: TypeError: undefined is not a function
at CALL_NON_FUNCTION (native)
at Server.<anonymous> (/home/cstrom/.node_libraries/fab/index.js:78:8)
at Server.<anonymous> (/home/cstrom/.node_libraries/.npm/faye/0.5.2/package/faye-node.js:1819:22)
at Server.emit (events:33:26)
at HTTPParser.onIncoming (http:830:10)
at HTTPParser.onHeadersComplete (http:87:31)
at Stream.ondata (http:762:22)
at IOWatcher.callback (net:494:29)
at node.js:764:9
Sadly, I have to call it a night there. Up tomorrow: figure out where my disconnect lies.


Day #218

Sunday, September 5, 2010

Installing and Using Apps for Fab.js v0.5

‹prev | My Chain | next›

Up tonight, I would like to see if I can finish the conversion of my (fab) game to version 0.5 of fab.js. I (sort of) have faye working so the bulk of what is left is serving up static files.

Happily, Rick Olson has already created fab.static for use with fabjs v0.5 and npm-ified it. So I install it:
cstrom@whitefall:~/repos/my_fab_game$ npm install fab.static
npm it worked if it ends with ok
npm cli [ 'install', 'fab.static' ]
npm version 0.1.26
...

npm activate fab.static@0.1.0
npm build Success: fab.static@0.1.0
npm ok
Using it seems a simple matter of requiring the new module and adding a few routes:
var http = require('http'),
faye = require('faye'),
puts = require( "sys" ).puts,
inspect = require( "sys" ).inspect,
couchdb = require('node-couchdb/lib/couchdb'),
client = couchdb.createClient(5984, 'localhost'),
db = client.db('my-fab-game'),
fab = require('fab');

fab.static = require('fab.static');


//....

with ( fab )

( fab )

// Listen on the FAB port and establish the faye server
( listen, 0xFAB, attach_faye )

(route, /^\/javascript/)
(route, /^\/(.*)/)
// Stream javascript files from ./javascript
(static, "javascript", "text/javascript", "js")
()
('Not found!')
()

// Server HTML out of the html directory, relative to the root
// ("/") resource
(route, /^\/(.*)/)
// Stream HTML files from ./html
(static, "html", "text/javascript", "html")
()

()
Starting up the game backend, however, I find:
cstrom@whitefall:~/repos/my_fab_game$ ./game.js

node.js:275
throw new Error("Cannot find module '" + request + "'");
^
Error: Cannot find module 'fab.static'
at loadModule (node.js:275:15)
at require (node.js:411:14)
at Object.<anonymous> (/home/cstrom/repos/my_fab_game/game.js:17:14)
at Module._compile (node.js:461:23)
at Module._loadScriptSync (node.js:468:10)
at Module.loadSync (node.js:338:12)
at Object.runMain (node.js:521:24)
at node.js:751:10
Bah!

So is this an npm thing (e.g. npm does not work with packages that have periods)? Or is this a fab.static issue?

No matter what it is, it makes sense to check out my ~/.node_libraries directory to see what is going on there:



Hrm... No fab.static. I see fab in there, but no fab.static. So I fork it. In my local copy of fab.static, I check out the package.json file:
cstrom@whitefall:~/repos/fab.static$ cat package.json 
{ "name": "fab.static"
, "version": "0.1.0"
, "author": "technoweenie"
, "engines": ["node >= 0.2.0"]
, "main": "./lib"
}
I have always seen or used a filename (minus the extension) for the "main" attribute. I know that manynode.js things will automatically read from index.js, but perhaps this is not one of them.

So I change "main" to include the full module ID:
cstrom@whitefall:~/repos/fab.static$ cat package.json 
{ "name": "fab.static"
, "version": "0.1.0"
, "author": "technoweenie"
, "engines": ["node >= 0.2.0"]
, "main": "./lib/index"
}
I install my local copy:
cstrom@whitefall:~/repos/fab.static$ npm install .
npm it worked if it ends with ok
npm cli [ 'install', '.' ]
npm version 0.1.26
...

npm activate fab.static@0.1.0
npm build Success: fab.static@0.1.0
npm ok
That seems to have worked, but then again so did the first install. The difference is that fab.static is now in my ~/node_libraries:



Reading through npm-json, I almost think it ought to work with "main": "./lib":
In fact, "main" is just sugar around setting a module named "index".
Clearly, it does not quite work like that. Ah well, I know that it definitely works with "main": "./lib/index".

Best of all, the game is now fully functional again. There may just be something to this new, extreme modular fabjs after all! Aside from a minor packaging issue, I was able to install and use a fab app very quickly tonight.

There is still the dashboard that is not quite working, but that gives me an excuse to write a (fab) app of my own. Tomorrow.

Day #217

Saturday, September 4, 2010

Faye with Fab (v0.5)

‹prev | My Chain | next›

After looking through the new v0.5 brannch of fab.js last night, I'd like to see if I can get it working with my (fab) game tonight.

I am building branches upon branches in my (fab) game's repository as I explore different things. Most recently, I have been working on an express branch which was a branch of a faye branch. To experiment with fabjs, I need to switch back to the faye/fabjs branch. I cherry pick some of the node-couchdb / CouchDB work that blossomed after I started on the express branch. I do not know if I will end up using fab or express, but I definitely want CouchDB.

Anyhow, I cherry pick everything, fix a few things that leaked though, and am ready to try things out:
cstrom@whitefall:~/repos/my_fab_game$ ./game.js 
[INFO] Starting up...

/home/cstrom/repos/my_fab_game/game.js:75
( fab )
^
ReferenceError: listen_with_faye is not defined
at Object.<anonymous> (/home/cstrom/repos/my_fab_game/game.js:75:1)
at Module._compile (node.js:461:23)
at Module._loadScriptSync (node.js:468:10)
at Module.loadSync (node.js:338:12)
at Object.runMain (node.js:521:24)
at node.js:751:10
OK. That was to be expected. The listen_with_faye (fab) app was part of my fork only. I cannot cherry pick that in my fork because the code structure changed so radically in fabjs between v0.4 and v0.5, but I can copy the code directly into the main index.js file of v0.5 fabjs.

Or I could if the fab.listen app had not changed so much. The latest version looks something like this:
fab.listen = function( write, port ) {
var url = require( "url" );

return fab.stream( function read( stream ) {
require( "http" )
.createServer( listener( stream ) )
.listen( port );

return stream( write );
});

function listener( stream ) {
// ...
}

}
The main problem here is not the switch to streams (though that does make a direct patch from my existing listen_with_faye impossible). No, the main problem is going to be that listener. It is big. Since it is hidden inside fab.listen, I cannot get access to it from elsewhere.

I can either cargo-code the entire app to a new version of listen_with_faye or tweak the v0.5 fab.listen directly. I ain't cargo coding, so I opt for the latter.

I could add a faye client directly in the fab.listen function. I am just playing at this point, so that would not be out-of-the-question. Still, it would be better to keep things as close to upstream as possible, especially with so many changes anticipated.

So I opt to supply an additional callback argument to be used to attach things to the server:
fab.listen = function( write, port, fn ) {
var url = require( "url" );

return fab.stream( function read( stream ) {
var server = require( "http" )
.createServer( listener( stream ) );

if (fn) fn(server);

server.listen( port );

return stream( write );
});

function listener( stream ) {
//....
}
}
One of the problems with callback code is, to what does the callback apply? Here, I want it to apply to the server that I am establishing so that I can attach a faye listener. I might just as well want to attach it to something in the listener function inside fab.listen. More likely, I might pass in a callback for the server.listen so that I could establish my server-side faye clients once the sockets are in place. Would the third argument end up being an object literal (hash) of possible callbacks? If so, testing become a big pain. Ick.

For now, I am none too concerned. I just want to get it working. But if I end up sticking with fab, I'll need something like that and will have to convince Jed it is worth the hassle. Problems for another day. For now, let's see if that works.

Back in my (fab) game, I create the faye listener (which had been in my old fab.listen_with_faye) and attach it via the callback:
function attach_faye(server) {
var faye_server = new faye.NodeAdapter({
mount: '/faye',
timeout: 45
});

faye_server.attach(server);

// attach the extension ensuring player messages come from the same
// client that originally added player to the room
faye_server.addExtension(serverAuth);
}

with ( require( "fab" ) )

( fab )

// Listen on the FAB port and establish the faye server
( listen, 0xFAB, attach_faye )

// Lots and lots of (fab) code commented out here because it no longer
// works with v0.5

()
I start up my server and switch over to node-repl. If the faye listener was attached to the server, then I ought to be able to attach a client, subscribe to a channel, and then publish a message to it:
cstrom@whitefall:~/repos/my_fab_game$ node-repl
Type '.help' for options.
(The REPL can also be started by typing 'node' without arguments)
node> var faye = require("faye");
node> var client = new faye.Client("http://localhost:4011/faye");
node> var sub = client.subscribe("/foo", function(message) { console.log(message) });
node> client.publish("/foo", "test 123");
node> test 123
Nice! When I publish a message to the "/foo" faye channel, the subscription receives the message and console.logs it as expected.

Most of the commented out, v0.4 (fab) code was static file serving. I seem to recall that a static file server has already been written for v0.5, so I may investigate that tomorrow. Or, if I'm feeling crazy, I may explore some of those HTML fab apps instead...


Day #216

Sunday, August 22, 2010

Something is Swallowing Errors

‹prev | My Chain | next›

Something in the node.js / fab.js / faye stack in my (fab) game is swallowing errors silently. Tonight I hope to track down the culprit so that I mitigate problems in the future.

So I start with node.js. In node-repl, I create a function designed to cause a stack trace (by accessing properties on an undefined variable), then invoke it:
node> function invalid() { asdf.foo.bar; return 42; }
node> invalid()
ReferenceError: asdf is not defined
at invalid (repl:1:22)
at repl:1:1
at REPLServer.readline (repl:84:17)
at Stream.<anonymous> (repl:47:19)
at Stream.emit (events:25:26)
at IOWatcher.callback (net:378:14)
at node.js:204:9
OK, backtrace. So it is not node.js swallowing errors.

Let's try fab.js. I create a dirt-simple (fab) app that ought to crash in exactly the same way:
  ( /^\/crash_me/ )
( function() {
asdf.foo.bar;
this({body:"foo"})();
} )
Accessing the this resource with curl:
strom@whitefall:~/repos/my_fab_game$ curl -i http://localhost:4011/crash_me
curl: (52) Empty reply from server
...seems to crash the server. Sure enough, checking back in the backend, I find:
cstrom@whitefall:~/repos/my_fab_game$ ./game.js
/home/cstrom/repos/my_fab_game/game.js:61
asdf.foo.bar;
^
ReferenceError: asdf is not defined
at Function.<anonymous> (/home/cstrom/repos/my_fab_game/game.js:61:5)
at /home/cstrom/.node_libraries/fab/apps/fab.path.js:41:21
at Server.<anonymous> (/home/cstrom/.node_libraries/fab/apps/fab.nodejs.js:18:17)
at Server.<anonymous> (/home/cstrom/.node_libraries/.npm/faye/0.5.2/package/faye-node.js:1851:22)
at Server.emit (events:32:26)
at HTTPParser.onIncoming (http:813:10)
at HTTPParser.onHeadersComplete (http:88:31)
at Stream.ondata (http:745:22)
at IOWatcher.callback (net:373:31)
at node.js:204:9
Again, that crashes just like I expect it to.

So was it frustration-induced imagination that errors were being swallowed? Maybe it was caused in faye. I setup a simple subscription that will, again crash, then publish to that channel:
node> var faye = require("faye");
node> var client = new faye.Client("http://localhost:4011/faye");
node> client.subscribe("/foo", function () { puts("here 1"); asdf.foo.bar; puts("here 2"); });
node> client.publish("/foo", "foo");
node> here 1

Ah ha!

I hit my first print STDERR statement, but not my second. This is effectively how I had to debug my faye subscriptions last night—puts output before a line potentially causing a backtrace, then puts immediately after. Eventually, I track down the error.

It is good to know that I need to start with faye (last night, I thought it could be anywhere in my code). Still, it would be nice if I could have a little more help. Will the debug log level in faye help?
node> faye.Logging.logLevel = 'debug';

node> client.publish("/foo", "foo");
2010-08-22 21:14:07 [INFO] [Faye.Client] Calling deferred actions for "xpvtabh47g1a14frlitfwjuo7"
2010-08-22 21:14:07 [INFO] [Faye.Client] Client "xpvtabh47g1a14frlitfwjuo7" queueing published message to "/foo": "foo"
node> 2010-08-22 21:14:07 [DEBUG] [Faye.Transport] Client "xpvtabh47g1a14frlitfwjuo7" sending message to "http://localhost:4011/faye": [{"channel":"/foo","data":"foo","clientId":"xpvtabh47g1a14frlitfwjuo7","id":"1eje88w1kego8iao5wsy2ehkr0"}]
2010-08-22 21:14:07 [DEBUG] [Faye.Transport] Client "xpvtabh47g1a14frlitfwjuo7" received from "http://localhost:4011/faye": [{"id":"1eje88w1kego8iao5wsy2ehkr0","clientId":"xpvtabh47g1a14frlitfwjuo7","channel":"/foo","successful":true}]
2010-08-22 21:14:07 [DEBUG] [Faye.Transport] Client "xpvtabh47g1a14frlitfwjuo7" received from "http://localhost:4011/faye": [{"id":"nmb3fzfima6l1q3nz3jyh9ne4","clientId":"xpvtabh47g1a14frlitfwjuo7","channel":"/meta/connect","successful":true,"advice":{"reconnect":"retry","interval":0,"timeout":45000}},{"channel":"/foo","data":"foo","clientId":"xpvtabh47g1a14frlitfwjuo7","id":"1eje88w1kego8iao5wsy2ehkr0"}]
2010-08-22 21:14:08 [INFO] [Faye.Client] Closed connection for "xpvtabh47g1a14frlitfwjuo7"
2010-08-22 21:14:08 [INFO] [Faye.Client] Client "xpvtabh47g1a14frlitfwjuo7" calling listeners for "/foo" with "foo"
here 1
2010-08-22 21:14:08 [INFO] [Faye.Client] Calling deferred actions for "xpvtabh47g1a14frlitfwjuo7"
2010-08-22 21:14:08 [INFO] [Faye.Client] Initiating connection for "xpvtabh47g1a14frlitfwjuo7"
2010-08-22 21:14:08 [DEBUG] [Faye.Transport] Client "xpvtabh47g1a14frlitfwjuo7" sending message to "http://localhost:4011/faye": [{"channel":"/meta/connect","clientId":"xpvtabh47g1a14frlitfwjuo7","connectionType":"long-polling","id":"9ln0pm1ne24t417ym55kwdhzjl"}]
...
Sadly no. Just a bunch of information about the connection.

So there it is. Faye is swallowing exceptions and not crashing. I appreciate the latter, but the former bit me several times last night. The print STDERR / puts output that I have here is the only thing that saw me through last night. I hope for a better way than this, so I will explore that tomorrow.


Day #203

Friday, August 20, 2010

Ugly Hack to Extend Fab.js Faye

‹prev | My Chain | next›

Tonight, I continue my efforts to ensure that player movement messages in my (fab) game can only come from the faye client that originally added the player to the game. In other words, if I enter the room as player Bob, I should not be able to broadcast to the game that player Fred quit.

The trouble facing me is that the faye server is established inside my custom fab.js app, listen_with_faye (a send-up of the built-into-fabjs listen function):
with ( require( "fab" ) )

( fab )

// Listen on the FAB port and establish the faye server
( listen_with_faye, 0xFAB )

...
If the faye server is completely encapsulated in that function, how can I add an extension to it?

Hmmm.... If I export that faye server from the listen_with_faye (fab) app, that ought to do the trick. I export that (using the commonjs convention) in the fab app:
var _faye_server = new faye.NodeAdapter({
mount: '/faye',
timeout: 45
});

exports.faye_server = _faye_server;
Then, in the my (fab) game backend, I import it:
faye_server = require( "fab/apps/fab.nodejs.listen_with_faye" ).faye_server;

var serverTap = {
incoming: function(message, callback) {
puts("here2");
return callback(message);
}
};

faye_server.addExtension(serverTap);
Nice and easy. Except it does not work—there is no output whatsoever from the backend when faye messages are published. Hmmmm...

What if I add my serverTap extension directly in the (fab) app?
exports.app = function( port ) {
var extension;
port.call( function( obj ){ port = obj.body; } );

return function( app ) {
var server = require( "http" )
.createServer( fab.nodejs( app ) );

_faye_server.attach(server);

server.listen(port);

var serverTap = {
incoming: function(message, callback) {
puts("here1");
return callback(message);
}
};
_faye_server.addExtension(serverTap);


return app;
};
};
That works as expected. When faye messages are published, I now see:
here1
here1
here1
here1
here1
After much head scratching, I eventually realize that my import in the backend:
    faye_server = require( "fab/apps/fab.nodejs.listen_with_faye" ).faye_server;
...is pulling in a separate instance of the faye server than is being used to actually connect to the fabjs server.

Ick.

I briefly toy with the idea of fiddling with singletons, but I have no idea if that can work in commonjs land. Besides: singleton.

Instead, I implement a completely different kind of bad hack. Along with the port number, I also allow the faye extension to be supplied in the listen_with_faye app:
exports.app = function( port ) {
var extension;
port.call( function( obj ){
if (typeof obj.body === 'number') {
port = obj.body;
}
else {
port = obj.body.port;
extension = obj.body.extension;
}

} );

return function( app ) {
var server = require( "http" )
.createServer( fab.nodejs( app ) );

_faye_server.attach(server);

server.listen(port);

if (extension) addExtension(extension);

return app;
};
};
Bleck. Well, that is a bit much, but it does work. When I start up my server as:
var serverTap = {
incoming: function(message, callback) {
puts("here2");
return callback(message);
}
};


with ( require( "fab" ) )

( fab )

// Listen on the FAB port and establish the faye server
( listen_with_faye, { port: 0xFAB, extension: serverTap } )

...
Moving around a bit, I find that I am finally hitting my serverTap extension:
cstrom@whitefall:~/repos/my_fab_game$ ./game.js
here2
here2
here2
...
At this point, my brain is pretty well fried, so I am hard pressed to come with a better way to accomplish this. If nothing else, the listen_with_faye (fab) app with an object is serviceable. I may leave this as-is for a bit so that I can get on with the business of securing my messages.

But first, sleep.


Day #201