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

Sunday, September 12, 2010

It Turns Out You Can Read the Node.js Source Code

‹prev | My Chain | next›

While working with the upcoming v0.5 branch of fab.js, I came across what seemed to be a bug (or undocumented regression) in node.js. Specifically, url.parse stopped parsing URLs without protocol schemes:
node> require('url').parse('//localhost:8124/foo')
{ href: '//localhost:8124/foo'
, pathname: '//localhost:8124/foo'
}
I fixed the issue by adding "http:" to the URL. I did the right thing by submitting a pull request to Jed.

Case closed. Or so I thought.

Jed closed the issue, not by accepting my patch, but by adding a third parameter to url.parse:
node> require('url').parse('//localhost:8124/foo', false, true)
{ href: '//localhost:8124/foo'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}
The second parameter is documented, but what is that third parameter? Maybe a better question is: how did Jed know about it? I googled for any information on url.parse and looked through the changelog... and saw nothing.

At this point, I could let it go and move on with my exploration of fab.js, but I have to know. How did Jed know? I'll ask if I cannot figure it out myself, but first, I do something I have never done before—ack though the node.js source.

I surely should have done this before, but as far as I know, node.js is a bunch of C code wrapped around the v8 engine (I am content to let my C skills wither). But this is my problem—"as far as I know".

In reality, there is loads of Javascript in the node.js source:
cstrom@whitefall:~/src/node-v0.2.1$ ls lib
assert.js dns.js http.js readline.js url.js
buffer.js events.js net.js repl.js utils.js
child_process.js file.js path.js string_decoder.js
crypto.js freelist.js posix.js sys.js
dgram.js fs.js querystring.js tcp.js
Damn. I cannot believe that I have spent this much time trying to improve my Javascript skills without even bothering to check if there was something in node.js that might help! Pretty dumb. I must make a mental note to always look through framework source code in the future—even if I suspect that I do not care for the language.

For now, I get started with my node.js exploration by reading through url.js. In there I find the answer to the new behavior:
function urlParse (url, parseQueryString, slashesDenoteHost) {

// ...

// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === "//";
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
out.slashes = true;
}
}

// ...
};
The commit that saw the introduction of the new behavior indicates that it was done to behave as expected in the most common use cases. The nice thing about it is that the behavior of url.parse(), when the third argument is true, does not change between node 0.2.0 and 0.2.1. Thus, I can update my table from yesterday:
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('//localhost:8124/foo', false, true)
{ href: '//localhost:8124/foo'
, 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'
}

node> require('url').parse('//localhost:8124/foo', false, true)
{ href: '//localhost:8124/foo'
, slashes: true
, host: 'localhost:8124'
, port: '8124'
, hostname: 'localhost'
, pathname: '/foo'
}
And that is why Jed wisely opted to make use of the third argument instead of my patch.

Good stuff. I am extremely disappointed in myself for never even bothering to look through the node.js source code. There is a wealth of learning in there that I so far ignored—for no good reason. Happily, I know about it now, so I can start making up for lost time.


Day #224

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