Showing posts with label nodejs. Show all posts
Showing posts with label nodejs. Show all posts

Thursday, September 11, 2014

A Lockfile to Prevent Double NodeJs Generators


The problem: a NPM post-install generator is running when updating packages. I can work around this on test servers—as I found last night, I check to see if the install process is being run from an interactive shell. But, after I implemented and tested that solution, I realized that I likely solved the wrong problem.

The problem is not that my generator is being run under test—which is the problem that I solved. The problem is that my generator is being run after it has already been run.

The point of the package in question, eee-polymer-tests it twofold. First, it generates simple test code and setup for new Polymer elements. Second, it provides the necessary dependencies to run those tests. But really, once the generator has run once, it is no longer of any use (unless I wanted to run it manually to start fresh).

Initially, I had thought to check for the existence of the Spec file. That will not work because neither the test server nor a human performing a simple npm install should have to know the name of the element for which the generator has already been run.

So, in the end, a lockfile seems the best approach. When the generator runs, in addition to creating Karma configuration and Jasmine specs, I will create a dot file in the application. The generator can then cue on that dotfile to know that the generator had already been run.

Once I settle on the approach, the implementation is easy. I define a global to hold the lockfile name:
var DOTFILE = '.eee-polymer-tests-generated';
Then I exit (successfully) if the lockfile exists:
parseCommandLine();

if (fs.existsSync(DOTFILE) && !force) {
  console.log('The spec generator has already been run. Won\'t overwrite without --force.');
  process.exit(0);
}
I already support the --force command-line argument for when this script is run directly from the terminal. If that flag is not present (after parsing the command line) and if the lockfile is present, then I exit gracefully.

And last, I generate the lockfile during the normal generate() process of this generator script:
function generate() {
  ensureTestDirectory();
  if (okKarmaConf()) generateKarmaConf();
  if (okPolymerSetup()) generatePolymerSetup();
  if (okTestSkeleton()) generateTestSkeleton();
  if (okBower()) generateBower();
  generateDotFile();
}
// ...
function generateDotFile() {
  fs.openSync(DOTFILE, 'w');
}
And that is all there is to it. I remove yesterday's interactive terminal check—this lockfile supersedes it. This works from an interactive command-line. A first run generates the lockfile:
npm install ~/repos/eee-polymer-tests
npm WARN package.json parent-events@ No README data
|
> eee-polymer-tests@0.0.1 postinstall /home/chris/repos/polymer-book/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

What is the name of the Polymer element being tested? x-parent
Generating test setup for: x-parent
....
$ git status
On branch master
Untracked files:
  (use "git add ..." to include in what will be committed)

        .eee-polymer-tests-generated
And subsequent runs report that there is nothing new to generate:
$ npm install ~/repos/eee-polymer-tests
The spec generator has already been run. Won't overwrite without --force
And it still works on my CI server:
...
[TEST] book/code-js/parent_events 
> eee-polymer-tests@0.0.1 postinstall /var/lib/jenkins/jobs/Patterns in Polymer/workspace/book/code-js/parent_events/node_modules/eee-polymer-tests
> ./generator.js

The spec generator has already been run. Won't overwrite without --force.

Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.052 secs / 0.049 secs)

Success!
Finished: SUCCESS
I am not 100% thrilled with generating an artifact like my lockfile. I think it is the best approach given my requirements. Now to generate a few more tests for Patterns in Polymer!


Day #180

Wednesday, September 10, 2014

Clean, Working Jenkins Tests for Polymer Elements


I wound up yesterday thinking that the only way to run Karma tests under Jenkins on my Linode was to upgrade from Debian 6 to Debian 7. So that is what I do.

This is more work than I am inclined to do for a CI server—especially when there are so many good CI services to be purchased. But, then again, it never hurts to keep things up-to-date. The instructions for upgrading Debian 6 to 7 from Linode work quite nicely, thank you very much.

Once I have that installed, making it through the last step of the Jenkins/Karma/Polymer test setup—installing Chrome—is easy enough:
$ sudo dpkg -i ~/Downloads/google-chrome-stable_current_i386.deb
Selecting previously unselected package google-chrome-stable.
(Reading database ... 55887 files and directories currently installed.)
Unpacking google-chrome-stable (from .../google-chrome-stable_current_i386.deb) ...
dpkg: dependency problems prevent configuration of google-chrome-stable:
 google-chrome-stable depends on libappindicator1; however:
  Package libappindicator1 is not installed.
Well, of course I needed one last yak. But, after installing that missing dependency (first correcting the broken Chrome install):
$ sudo apt-get -f install
$ sudo apt-get install libappindicator1
I can now get Chrome installed:
$ sudo dpkg -i ~/Downloads/google-chrome-stable_current_i386.deb
(Reading database ... 57351 files and directories currently installed.)
Preparing to replace google-chrome-stable 37.0.2062.120-1 (using .../google-chrome-stable_current_i386.deb) ...
Unpacking replacement google-chrome-stable ...
Setting up google-chrome-stable (37.0.2062.120-1) ...
Processing triggers for man-db 
Yay!

More importantly, I finally have a passing Jenkins build:



No really, it is passing:



And it is reproduceable as well, which is always a bonus. Actually, that is kind of a must for CI.

I am not quite done, however. My eee-polymer-tests package, which provides reasonable default NPM dependencies for testing Polymer elements (Karma, Jasmine, Bower, etc) also generates skeleton test code. If run with no arguments, as is done with a NPM install from a CI server, eee-polymer-tests code will query the developer for the name of the element being tested. In fact, it is doing so in my Karma run:
> eee-polymer-tests@0.0.1 postinstall /var/lib/jenkins/jobs/Patterns in Polymer/workspace/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

What is the name of the Polymer element being tested? 
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
├── colors@0.6.2
├── minimist@1.1.0
└── bower@1.3.9
The readline module that is doing this seems to know that this is being run in a non-interactive process—it does not wait for an answer nor does it run any of the code that would generate testing code after an answer.

Still, I would like to save it the trouble (and myself some concern). The way to accomplish this seems to be via the tty module in Node. With it, I can interrogate a file descriptor like STDIN to see if it is associated with a terminal:
var fs = require('fs');
var readline = require('readline');
var tty = require('tty');

if (element) {
  generate();
}
else if (tty.isatty(process.stdin)) {
  queryForElementName();
}
else {
  console.log('Nothing to generate.');
}
In this case, if STDIN is not a TTY, then it is not coming from an interactive session and I do nothing. All that needs to happen is to install the normal Karma, Bower, etc. dependencies.

That works just fine:
> eee-polymer-tests@0.0.1 postinstall /var/lib/jenkins/jobs/Patterns in Polymer/workspace/book/code-js/parent_child/node_modules/eee-polymer-tests
> ./generator.js

Nothing to generate.
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
├── colors@0.6.2
├── minimist@1.1.0
└── bower@1.3.9 
I may still have a problem on my hand. Readers of the book that I am testing here, Patterns in Polymer, might want to run the tests themselves. But if they try to npm install like my test code is doing, they will be prompted for an element because they will be running the command in an interactive shell.

Looks like I am going to need a lockfile mechanism of some sort for this. Tomorrow.

Day #179

Thursday, September 4, 2014

Generating Code from NPM that Installs Bower(!)


I have my eee-polymer-tests testing package for custom Polymer elements in pretty good shape. It will install and configure the necessary Karma configuration and skeleton tests to run a single, generated test on a Polymer element (which passes!). But...

My approach assumes two things: that the element definition is located in the elements subdirectory of the current package and that Bower is being used to install Polymer and its dependencies. Neither is a particularly poor assumption. The elements subdirectory is my personal preference, but I like it because it keeps my custom elements separate from any apparatus used to maintain the code. The Polymer project itself uses Bower for its elements, so I am OK sticking with it.

But, unlike all of the other checks that I have in eee-polymer-tests:
What is the name of the Polymer element being tested? click-sink

Generating test setup for: click-sink
[WARN] File exists: karma.conf.js. (use --force to overwrite)
[WARN] File exists: test/PolymerSetup.js. (use --force to overwrite)
[WARN] File exists: test/ClickSinkSpec.js. (use --force to overwrite)
I am not checking for the proper elements subdirectory, nor the Polymer + Bower configuration.

Testing for the existence of the elements directory is pretty straight-forward after my previous efforts:
function okElements() {
  if (!fs.existsSync('elements')) {
    var message = '[WARN] There is no elements subdirectory for Polymer elements. Tests will fail!';
    console.log(message.red);
    return false;
  }
  return true;
}
Checking for the existence of the bower.json is pretty much the same, except for the filename. I can even read the NPM module's package.json, which is what is running the generator in eee-polymer-tests, and write a corresponding bower.json if it does not already exist:
  var npmJson = JSOaN.parse(fs.readFileSync('package.json'));
  var bowerJson = {
    "name": npmJson.name,
    "version": "0.0.0",
    "description": npmJson.description,
    "ignore": [
      "**/.*",
      "node_modules",
      "bower_components",
      "test",
      "tests"
    ],
    "dependencies": {
      "polymer": "Polymer/polymer"
    }
  };
This gives me the brilliant idea to install Bower as part of eee-polymer-tests and ensure that Polymer is installed. Installing Bower is easy enough with NPM—it is, after all, the JavaScript package manager that is installed with the NPM JavaScript package manager. I add it to the list of eee-polymer-tests' dependencies:
{
  "name": "eee-polymer-tests",
  // ...
  "dependencies": {
    "colors": ">0.0",
    "minimist": ">0.0",
    "bower": ">0.0"
  },
  "peerDependencies": {
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
To actually install, it turns out that Bower has an API:
var bower = require('bower');
function generateBower() {
  // ...
  bower.commands
    .install(['Polymer/polymer'], { save: true }, { /* custom config */ })
    .on('end', function (installed) {
        console.log(installed);
     });
}
Which works quite as expected. Well, the installed object that is logged is just an empty object literal, but it does save changes to the bower.json file that is currently installed.

As cool as that is, I lean toward not using it. I have no idea if any besides myself will have use for eee-polymer-tests. Generating a simple test structure with it is one thing (and will be quite helpful), but I already install bower out of habit. I will likely file this under “good to know,” but focus elsewhere. Like actually writing some new tests tomorrow.

Update: Ah, the heck with it. I added bower generation after all: bfe13c3.

Day #173

Tuesday, September 2, 2014

Better CLI in NPM Generators


Unsure of the best way to deal with existing files in eee-polymer-tests, I opt for a warn / force-overwrite approach. That is, when this NPM package attempts to overwrite existing Polymer test files of the same name, it should warn the developer of the problem, but make no changes. If a developer really wants to overwrite these files, she can either manually move them out of the way or use an option like --force.

So far, I have been able to build eee-polymer-tests with pure Node.js. Both of tonight's needs require their own packages. To warn users, I need to output the messages in yellow so that the problem is as obvious as possible. So far, my generators has accepted a single argument (the name of the Polymer element being tested), but I will need something a little more sophisticated to handle command-line options.

A quick search reveals colors and minimist (not minimalist) as my best bets for coloring strings on the command line and parsing the command line, respectively. So I add them to my package.json:
{
  "name": "eee-polymer-tests",
  "version": "0.0.1",
  "description": "Sane Polymer test setup (including generator)",
  "scripts": {
    "postinstall" : "./generator.js"
  },
  "homepage": "https://github.com/eee-c/eee-polymer-tests",
  "dependencies": {
    "colors": ">0.0",
    "minimist": ">0.0"
  }
}
In the generator script, I then require both:
var fs = require('fs');
var readline = require('readline');
var parseArgs = require('minimist');
require('colors');
For each of the files being generated, I add a conditional "ok-to-generate":
function generate() {
  ensureTestDirectory();
  if (okKarmaConf()) generateKarmaConf();
  if (okPolymerSetup()) generatePolymerSetup();
  if (okTestSkeleton()) generateTestSkeleton();
}
I factor out the check / warn logic common to each of these "ok-to-generate" function into a private _okOverwrite() function that checks for the existence of the file and colorizes a warning if the file already exists:
var KARMA_CONF = 'karma.conf.js';
// ...
function okKarmaConf() {
  return _okOverwrite(KARMA_CONF);
}

function _okOverwrite(filename) {
  if (!fs.existsSync(filename)) return true;

  var message = '[WARN] File exists: ' + filename + '.' +
                ' (use --force to overwrite)';
  console.log(message.yellow);
  return false;
}
That, combined with last night's readline generator works quite nicely:



The --force option is easy enough, thanks to minimist. I parse the command as:
function parseCommandLine() {
  if (process.argv.length <= 2) return;
  var argv = parseArgs(process.argv.slice(2), {
    'boolean': 'force'
  });
  if (argv._.length != 1) return;

  element = argv._[0];
  force = argv.force;
}
If there are no arguments, then the element variable is not set (and last night's readline solution will kick in). But, if there are arguments, I set the element value and, optionally, the force value.

Since I have already consolidated all of the ok-to-overwrite checking in a single place, I only have one place to update to accommodate the force value:
function _okOverwrite(filename) {
  if (!fs.existsSync(filename)) return true;

  if (force) {
    var message = 'Force overwrite: ' + filename + '.';
    console.log(message);
    return true;
  }

  var message = '[WARN] File exists: ' + filename + '.' +
                ' (use --force to overwrite)';
  console.log(message.yellow);
  return false;
}
With that, my generator still works as a post-install step and it also works directly from the command-line—optionally overwriting existing files if I really, really want to:



I am reasonably satisfied with that solution, so this may mark the end of initial development on eee-polymer-tests. There is still a minor issue with extremely small test files (like the generated spec) failing on rare occasions. I will have a look at that tomorrow. After that, it is time to finish off any remaining chapters in Patterns in Polymer that lack the kinds of tests that eee-polymer-tests can generate.

Day #171

Monday, September 1, 2014

Postinstall NPM Scripts with Output in the Working Directory


After last night's efforts on eee-polymer-tests, I can wipe my current Polymer (JS) testing install (NPM packages, tests, setup, and Karma config), install, generate new test setup, and run passing tests:
# Delete existing test install...
$ rm -rf karma.conf.js node_modules test

# Install eee-polymer-tests and dependencies..
$ npm install
karma-jasmine@0.2.2 node_modules/karma-jasmine
karma@0.12.23 node_modules/karma
karma-chrome-launcher@0.1.4 node_modules/karma-chrome-launcher
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests

# Generate new setup and sample test...
$ ./node_modules/eee-polymer-tests/generator.js click-sink

# Run tests...
$ karma start
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket ra4z9IfQR4BW8onHkNhy with id 82158706
Chrome 37.0.2062 (Linux): Executed 1 of 1 SUCCESS (0.046 secs / 0.041 secs)
That is going to be a huge help as I work through the remainder of Patterns in Polymer, adding tests to any book code that do not already have them. But there are still a couple of outstanding issues that I would like to knock off first. One of them is more an annoyance, but it will have to be dealt with: the small sample test tends to be so small that the Karma tests don't fully initialize Polymer before running, causing errors. Another problem is that I have not really accounted for the pre-existence of any of the generated files. The last problem is that I never seem to remember to run the generator manually.

I think I will work the problems in reverse order, since the last two are somewhat related by virtue of being NPM code. I can solve the last problem by making the script part of the install, which is done with one of the package lifecycle hooks in NPM. In this case, I make my eee-polymer-tests/generator.js script a post-install script:
{
  "name": "eee-polymer-tests",
  "version": "0.0.1",
  "description": "Sane Polymer test setup (including generator)",
  "scripts": {
    "postinstall" : "./generator.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  // ...
}
When I install, this script is run, but it fails.

It fails because it expects STDIN input to describe the element name:
var element = process.argv[2];
But there is no STDIN as part of a lifecycle script. I need a way to block for input. For that, I make use of the experimental Readline. Readline needs access to both input and output in order to read input and prompt for it:
var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});
Using a readline instance is easy, thanks to the question() method:
rl.question("What is the name of the Polymer element being tested? ", function(answer) {
  element = answer.replace(/[<>]*/g, '');

  console.log("Generating test setup for: ", element);
  generate();
  console.log("Done!");

  rl.close();
});
Once I have my answer, I assign it to a global element variable for use in the templates being generated. After my generator does its thing, I tell the user that everything is ready and close the readline object.

And that works great. My generator is run after install and all of the code is generated correctly. Except...

It installs the generated code in the node_modules/eee-polymer-tests subdirectory instead of in the directory from which I called npm install. The whole point of this testing setup is to generate sane defaults and structure for my Polymer elements. So I need Jasmine tests and Karma configuration directly inside my Polymer elements—not inside the node_modules directory.

I am unsure if there is a proper way to get this working, but I solve it by checking the process.cwd() and then changing directories if this is being run from node_modules/eee-polymer-tests:
if (/node_modules\/eee-polymer-tests/.test(process.cwd())) {
  // Need to run the generator from the element package, not from the
  // installed node module
  process.chdir('../..');
}
And that does the trick. Now I can go from a clean Polymer install to passing tests with a single command:
$ rm -rf karma.conf.js node_modules test

$ npm install
> eee-polymer-tests@0.0.1 postinstall /home/chris/repos/polymer-book/book/code-js/parent_events/node_modules/eee-polymer-tests
> ./generator.js

What is the name of the Polymer element being tested? click-sink
Generating test setup for:  click-sink
Done!

karma-jasmine@0.2.2 node_modules/karma-jasmine
karma@0.12.23 node_modules/karma
karma-chrome-launcher@0.1.4 node_modules/karma-chrome-launcher
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests

$ karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket SOOfrLj5phVcYX11idm1 with id 77662837
Chrome 37.0.2062 (Linux): Executed 1 of 1 SUCCESS (0.06 secs / 0.054 secs)
I still need to decide how to deal with pre-existing files of the same name as those being generated. I thought I had a good idea how to do that, but got mired in details tonight. Hopefully approaching it fresh will resolve things tomorrow. Then I need to see if I can resolve the spurious first run test failure in the generated code. That will no doubt be annoying and tedious since it does not happen all the time. If I am very lucky, I will have a brain wave that makes me understand why that happens and how to fix it. But I leave both tasks for another night.


Day #170

Sunday, August 31, 2014

NPM Script to Generate Polymer Test Setup


Up today, I continue my efforts to build something of a testing solution for Polymer elements. The built-in testing Dart solutions have been more than up to the task with Polymer.dart, but the JavaScript testing setup has proved trickier. To resolve the various annoyances, I have what I think is a relatively simple approach, but with some definite opinions. This seems ideal for extracting into a node.js package, if only to ease my own Polymer testing.

Last night, I extracted a bunch of the Karma configuration out into eee-polymer-tests. Now that it is a GitHub project, I can specify it as a development dependency in custom Polymer elements:
{
  "name": "parent-events",
  "devDependencies": {
    "eee-polymer-tests": "eee-c/eee-polymer-tests"
  }
}
After npm install (following the traditional rm -rf node_modules), I have Karma, Jasmine, and other testing requirements as well as settings from eee-polymer-tests:
$ rm -rf node_modules
$ npm install
karma-chrome-launcher@0.1.4 node_modules/karma-chrome-launcher
karma@0.12.23 node_modules/karma 
karma-jasmine@0.2.2 node_modules/karma-jasmine
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
$ ls -l node_modules/eee-polymer-tests
total 16
-rw-r--r-- 1 chris chris 2022 Aug 31 01:06 karma-common.conf.js
-rw-r--r-- 1 chris chris 1078 Aug 31 01:06 LICENSE
-rw-r--r-- 1 chris chris 1340 Aug 31 22:02 package.json
-rw-r--r-- 1 chris chris  306 Aug 31 01:06 README.md
Thanks to NPM peer dependencies, the Karma and Jasmine packages are installed for easy use in my element's tests. Thanks to the karma-common.conf.js from last night, my own karma.conf.js is nothing more than:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // ...
  }));
};
With no other setup required, my tests still pass:
$ karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket B3i3n_dnKrvjoYei80Jc with id 60115395
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.076 secs / 0.072 secs)
That is pretty good, but I would like to be able to generate some of the testing code that is currently required to make all of this work:
.
├── bower.json
├── elements
│   └── click-sink.html
├── index.html
├── karma.conf.js
├── package.json
└── test
    ├── ClickSinkSpec.js
    └── PolymerSetup.js
The bower.json file exposes a hidden dependency on Bower. The only real consideration for Bower is that my tests expect Polymer dependencies to be installed in bower_components. I will defer consideration of that until another day.

For now, I would like to write a script that creates the other three files in the list. I start with test/PolymerSetup.js, which is nearly boilerplate except for the inclusion of the main Polymer element at the very end of the file:
// Delay Jasmine specs until Polymer is ready
var POLYMER_READY = false;
beforeEach(function(done) { /* wait for polymer-ready */ });

// 1. Load Polymer before any code that touches the DOM.
var script = document.createElement("script");
script.src = "/base/bower_components/platform/platform.js";
document.getElementsByTagName("head")[0].appendChild(script);

// 2. Load component(s)
var link = document.createElement("link");
link.rel = "import";
link.href = "/base/elements/click-sink.html";
document.getElementsByTagName("head")[0].appendChild(link);
I am unsure if there are any standard templating solutions for Node.js (a quick search did not turn one up), so regular expressions it is!

I create a templates/PolymerSetup.js file in eee-polymer-test that is identical to the current setup from my working tests. The only change is a mustache-like placeholder for the element name:
// Identical up to...
// 2. Load component(s)
var link = document.createElement("link");
link.rel = "import";
link.href = "/base/elements/{{element-name}}.html";
document.getElementsByTagName("head")[0].appendChild(link);
I would prefer that eee-polymer-tests be installed globally (i.e. with npm install -g), but that is not going to be an option because of last night's peer dependencies. Instead, this will be run as:
$ ./node_modules/eee-polymer-tests/cli.js click-sink
Given that execution path, the template path will be ./node_modules/eee-polymer-tests/templates/PolymerSetup.js. There is probably a way to determine this path relative to the currently executing script, but I will leave that for another day.

I just want to be able to read the template and write the template with the element applied. The read should look something like:
#!/usr/bin/env node

var element = process.argv[2];

var fs = require('fs');
fs.readFile('./node_modules/eee-polymer-tests/templates/PolymerSetup.js', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  writeSetup(data);
});
The writeSetup() can then do the opposite with writeFile():
function writeSetup(template) {
  var content = template.replace(/\{\{element-name\}\}/g, element);
  fs.writeFile('./test/PolymerSetup.js', content);
}
That takes care of globally replacing the {{element-name}} template placeholder (thanks to the g modified on the regular expression).

And that seems to do the trick. I run that code—overwriting the current PolymerSetup.js—and re-run the tests to find everything still passing.

This seems quite promising for my needs. I am unsure if anyone else will find it similarly useful, but I am definitely filling a need of my own here. I think tomorrow I will continue with this, adding in some overwrite protection. That aside, this is already quite close to what I need.


Day #169

Saturday, August 30, 2014

A Package for Common Polymer Testing


I was unable to get polymer-test-tools to work well with a custom Polymer of my own. The effort was not completely wasted as I learned a ton. The most interesting thing that I learned is that I have some definite opinions on what ought to be included in a general purpose Polymer testing tool. Enough, possibly, to write my own.

My Polymer element setup usually looks something like:
.
├── test
│   ├── PolymerSetup.js
│   └── ClickSinkSpec.js
├── package.json
├── karma.conf.js
├── index.html
└── elements
    └── click-sink.html
I have my element(s) in the elements subdirectory, the tests in the tests subdirectory, a package.json that includes Karma and Jasmine dependencies and a Karma configuration file. Also of note is is that I have very specific test setup that goes into test/PolymerSetup.js to enable testing with Polymer.

For a first pass at a testing tool (generator? template? not sure yet?), I initialize a git and npm repository:
➜  repos  mkdir eee-polymer-tests
➜  repos  cd !$
➜  repos  cd eee-polymer-tests
➜  eee-polymer-tests  git init
Initialized empty Git repository in /home/chris/repos/eee-polymer-tests/.git/
➜  eee-polymer-tests git:(master) npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sane defaults.

See `npm help json` for definitive documentation on these fields
and exactly what they do.

Use `npm install  --save` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
name: (eee-polymer-tests)
version: (1.0.0) 0.0.1
description: Sane Polymer test setup (including generator)
entry point: (index.js)
test command:
git repository: https://github.com/eee-c/eee-polymer-tests
keywords: polymer testing karma jasmine
author: Chris Strom
license: (ISC) MIT
To build this up, I would like to slowly replace parts in my working tests with this NPM package. Unfortunately, I do not know how to do this quickly with NPM since it does not support local filesystem dependencies. Well, that's not entirely true, NPM does support npm link, but I am unsure how to get that to install dependencies.

And, in the case of eee-polymer-tests, I need to include karma-jasmine and karma-chrome-launcher as peer dependencies. I specify those in my package.json:
{
  "name": "eee-polymer-tests",
  // ...
  "peerDependencies": {
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
As peer dependencies, these will be installed in my Polymer application the same as if I had listed them as direct dependencies (or development dependencies):
{
  "name": "parent-events",
  "devDependencies": {
    "karma-jasmine": "~0.2.0",
    "karma-chrome-launcher": ">0.0"
  }
}
The only way I can get my Polymer application to honor my local package's peer dependencies—at least the only way that I can figure out tonight—is to add my local package as a pre-install script to my Polymer element's package.json:
{
  "name": "parent-events",
  "scripts": {
    "preinstall": "npm install /home/chris/repos/eee-polymer-tests/"
  }
}
That actually seems to work:
$ npm install
> parent-events@ preinstall /home/chris/repos/polymer-book/book/code-js/parent_events
> npm install /home/chris/repos/eee-polymer-tests/
...
karma-chrome-launcher@0.1.4 node_modules/karma-chrome-launcher

karma@0.12.23 node_modules/karma
└── ...

karma-jasmine@0.2.2 node_modules/karma-jasmine

eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
And...
$ ls node_modules
eee-polymer-tests  karma  karma-chrome-launcher  karma-jasmine
Most importantly, my Karma tests still pass:
karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket wzCHNN5LnCOMY2-V4ELH with id 70589859
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.068 secs / 0.061 secs)
Next up, I need to borrow from a trick I learned from polymer-test-tools. I need to move my common testing setup for karma into the NPM package, but still allow developers a means to override the common stuff. Directly from polyer-test-tools, I create karma-common.conf.js in the eee-polymer-tests NPM package:
exports.mixin_common_opts = function(karma, opts) {
  var all_opts = {
    //  Common settings go here...
  };
  for (var key in opts) {
   all_opts[key] = opts[key];
  }
  return all_opts;
};
The common setting are mostly the defaults from the Karma generator. The ones specific to my preferred Polymer testing setup include the testing framework to use:
    // frameworks to use
    frameworks: ['jasmine'],
A means to facilitate fixure loading if needed:
    /**
     * Compile HTML into JS so that they can be used as templates
     */
    preprocessors: {
      'test/*.html': 'html2js'
    },
And the list of files to include for testing or to serve (but not directly execute):
    /**
     * Don't include Polymer HTML and JS because Polymer is very
     * particular about the order in which they are added. Serve them,
     * but defer loading to the test setup. Include test HTML
     * fixtures.
     */
    // list of files / patterns to load in the browser
    files: [
      'test/PolymerSetup.js',
      {pattern: 'elements/**', included: false, served: true},
      {pattern: 'bower_components/**', included: false, served: true},
      'test/**/*Spec.js'
    ],
Back in my Polymer element, the karma.conf.js then becomes simply:
module.exports = function(config) {
  var common = require('./node_modules/eee-polymer-tests/karma-common.conf.js');

  config.set(common.mixin_common_opts(config, {
    // Specialization could go here, but none needed!
  }));
};
I do not need to override any of the default settings. Furthermore, I think the common options would likely suit just about any elements that I have created so far. Famous last words, I am sure.

Anyhow, trying it out, I find:
$ karma start --single-run
ERROR [config]: Error in config file!
 { [Error: Cannot find module './node_modules/eee-polymer-tests/karma-common.conf.js'] code: 'MODULE_NOT_FOUND' }
Error: Cannot find module './node_modules/eee-polymer-tests/karma-common.conf.js'
    at Function.Module._resolveFilename (module.js:338:15)
    ...
This is a definite drawback to the pre-install NPM approach. I have to re-install each time I want to try something new. That is going to be a pain if I need to debug often. Perhaps if that is the case, I can try a hybrid approach that first installs dependencies, but then npm-links my local package. Food for thought another day.

For now, I re-install:
$ rm -rf node_modules
$ npm install
...
eee-polymer-tests@0.0.1 node_modules/eee-polymer-tests
With that:
karma start --single-run
INFO [karma]: Karma v0.12.23 server started at http://localhost:9876/
INFO [launcher]: Starting browser Chrome
INFO [Chrome 37.0.2062 (Linux)]: Connected on socket Q1jxhuNWJtv6SKmi2C2L with id 12087020
Chrome 37.0.2062 (Linux): Executed 2 of 2 SUCCESS (0.057 secs / 0.051 secs)
Nice!

I now require only a single testing dependency and zero configuration. That may not be completely reusable by others, but it does afford a certain amount of configuration thanks to the approach from the polymer-test-tools project. Regardless, it is a good start and will help me very much in my efforts to test the remainder of the elements in Patterns in Polymer.

I have not saved myself any files required for testing. I may or may not be able to include the PolymerSetup.js directly in eee-polymer-tests. I have been including the <link> import of the element definition under test in PolymerSetup.js. It is possible that I can move the import elsewhere, but that will take some experimentation. I will always need the equivalent of ClickSinkSpec.js. Now that I think about it, both could be generated from a script in eee-polymer-tests.

I will work on that tomorrow.


Day #168

Saturday, July 19, 2014

Command Line Arguments with Node.js and Dart2js


How on earth did it come to this?

I need for my compiled Dart to respond to command line arguments when compiled to JavaScript and run under Node.js. I think that sentence reads as proper English.

It all seemed so simple at first. I want to benchmark code for Design Patterns in Dart. I may use benchmarks for every pattern, I may use them for none—either way I would like the ability to quickly get benchmarks so that I can compare different approaches that I might take to patterns. So I would like to benchmark.

So I benchmark my Dart code. I added features to command-line Dart scripts so that they can read command line switches to vary the loop size (which seems to make a difference). Then I try to compile this code to JavaScript to be run under node.js. That actually works. Except for command line options to vary the loop size.

And so here I am. I need to figure out how to get node.js running dart2js code to accept command-line (or environment) options.

Last night I found that the usual main() entry point simply does not see command line arguments when compiled via dart2js and run with node. The print() of the command line args is an empty List even when options are supplied:
main (List<String> args) {
  print(args);
  // ...
}
With the Dart VM, I see command line options:
$ dart ./tool/benchmark.dart --loop-size=666
[--loop-size=666]
And, with the very nice args package, I can even process them to useful things. But when run with node.js, I only get a blank list:
$ node ./tool/benchmark.dart.js --loop-size=666
[]
I had thought to use some of the process environment options, but they are all part of the dart:io package which is unsupported by dart2js. Even initializing a string from the environment does not work:
const String LOOP_SIZE = const String.fromEnvironment("LOOP_SIZE", defaultValue: "10");
No matter how I tried to set that environment variable, my compiled JavaScript would only use the default value.

So am I stuck?

The answer turns out to be embedded in the output of dart2js code. At the very top of the file are a couple of hints including:
// dartMainRunner(main, args):
//    if this function is defined, the Dart [main] method will not be invoked
//    directly. Instead, a closure that will invoke [main], and its arguments
//    [args] is passed to [dartMainRunner].
It turns out that I can use this dartMainRunner() function to grab command line arguments the node.js way so that they can be supplied to the compiled Dart. In fact, I need almost no code to do it:
function dartMainRunner(main, args) {
  main(process.argv.slice(2)); 
}
I slice off the first two command line arguments, supplying the main() callback with the rest. In the case of my node.js code, the first two arguments are the node executable and the script name:
$ node ./tool/benchmark.dart.js --loop-size=666
With those chomped off, I am only supplying the remainder of the command line arguments—the switches that control how my benchmarks will run.

This is a bit of a hassle in my Dart benchmarks since I will need to add that wrapper code to each implementation every time that I make a change. I probably ought to put all of this into a Makefile (or equivalent). For now, however, I simply make it part of my benchmarking shell script:
#...
# Compile
wrapper='function dartMainRunner(main, args) { main(process.argv.slice(2)); }';
dart2js -o tool/benchmark.dart.js \
           tool/benchmark.dart
echo $wrapper >> tool/benchmark.dart.js

# More compiling then actual benchmarks ...
And that works!

Thanks to my already in place gnuplot graphing solution, I can even plot my three implementations of the Visitor Pattern compiled from Dart into JavaScript. The number of microseconds it takes a single run relative to the number of loops winds up looking like this:



That is a little different than last night's Dart numbers, but the bottom line seems to be that it does not matter too much which implementation I choose. At least for this pattern. Regardless, I am grateful to be able to get these numbers quickly now—even from node.js.


Day #127

Wednesday, May 23, 2012

SPDY/3 Flow Control Comparisons

‹prev | My Chain | next›

Last week, I compared Chrome and Firefox spdy/3 implementations. The result was inconclusive because I was using a sample page too far removed from the norm. Tonight, I revisit that comparison.

I again start with an artificial round trip time (RTT) of 100ms:
➜  spdybook-site git:(master) ✗ sudo tc qdisc add dev lo root netem delay 50ms        
[sudo] password for chris: 
➜  spdybook-site git:(master) ✗ ping localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 time=100 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=2 ttl=64 time=100 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=3 ttl=64 time=100 ms
...
It is not quite realistic, but it is close enough and has the virtue of making math easier.

As I did last night, I use a web page that includes roughly 50 smallish images and other resources (85 is typical):


For each trial, I stop the node-spdy (spdy-v3 branch) server and close the browser before making a connection. Ideally this will make for consistently cold TCP/IP pipes over which the SPDY connections will be made.

I run a regular Chrome connection over spdy/3:


Then a Chrome connection over spdy/3 with spdy server push:


And, lastly Firefox over vanilla spdy/3 (Firefox does not support push):


I had expected to find that the Firefox connection is faster than the vanilla Chrome connection. New in spdy/3 is flow control, which I thought would make the difference. But upon reflection, flow control should not enter into this—none of the images are large enough to threaten SPDY's default receive window (64kb). In other words, there should be no flow control.

So what is the difference? I suspect that the difference is that Firefox is requesting more resources initially, pushing the TCP/IP CWND up faster. This would seem to be born out by virtue of the first large packets in each starting at the 0.7 second mark for Firefox and nearly 1.0 seconds for Chrome. Last night's Speed Tracer diagram would also suggest that Chrome is processing the <head> items before requesting the images from the <body>:


Regardless, I had wanted to compare more realistic spdy/3 implementations. For that, it seems that I need to add a couple of images that push the bounds flow control past the default receive window. I add them to the bottom of the <body> to get them loading last:


Now I repeat the trials for Chrome with vanilla spdy/3:


Chrome with spdy/3 and spdy server push:


And, lastly, Firefox over spdy/3:


This is what I had expected: Firefox trounces Chrome's flow control implementation. With a SPDY receive window of 256mb, Firefox effectively eschews spdy/3 flow control. The SPDY server is free to jam as much data as it wants on the wire. In this case, it completely fills the TCP/IP receive window (the top lines in the graphs).

With Chrome, on the other hand, the SPDY server is forced to wait for WINDOW_UPDATE frames before it can send back the next batch of data. Since Chrome never updates the SPDY receive window by more than 32kb, the server is unable to send enough data to push the bounds of the TCP/IP receive window.

The result is stark. Firefox completes transfer in less than 2 seconds whereas Chrome is twice as slow. The SPDY push is even worse because of a pause to transfer non-pushed resources (I am not pushing Javascript and CSS).

Chrome's current implementation seems clearly sub-optimal. In spdy/2 (and in vanilla HTTP), Chrome is more than capable of handling large TCP/IP receive windows. There is no reason for Chrome to continue to request WINDOW_UDPATES of 32kb—instead Chrome should be asking for near the TCP/IP receive window's worth of data.

That said, from the server's point of view, this implementation might be regarded as beneficial. The server is able to jam the smallish resources back to the browser in short order. The larger items, which the user would likely not expect to render immediately anyway, can be sent back at a more leisurely pace—freeing up the server to respond to other SPDY sessions.

Regardless, it is not the responsibility of the client to throttle the server's response like this. The server is more than capable of doing it on its own. So I expect that Chrome's WINDOW_UPDATE algorithm will get a little more sophisticated in the near future.


Day #395

Tuesday, May 22, 2012

Simple Comparisons of HTTP, HTTPS, SPDY/2 and SPDY/3

‹prev | My Chain | next›

tl;dr SPDY rules speed tests.

Amazingly, the average web page includes 85 resources (per httparchive.org). My "real world" web page only has a dozen images:


So I add separate copies to the bottom of the page:


I add an artificial 100ms round trip time:
➜  ~  sudo tc qdisc add dev lo root netem delay 50ms
[sudo] password for chris: 
➜  ~  ping localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 time=100 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=2 ttl=64 time=100 ms
That is a little higher than is typical in the wild. I like it because it makes math easier and is not too far off.

Now, when I load the vanilla SSL site and watch in Speed Tracer, I see:


A total of 5.03 seconds (5.98 - 0.995) for SSL.

The "real world" SPDY running on the spdy-v3 branch of node-spdy:


SPDY/3: 1.1 seconds.

And finally, a push version that uses SPDY server push to push all of the images directly into Chrome's chache after the first request:


SPDY/3 push: 0.74 seconds.

Since I am doing all of this comparing, I might as well see what vanilla HTTP looks like:


HTTP: 2.7 seconds.

Important the SPDY vs HTTP comparison is not a fair one. Because of some deficiencies in Speed Tracer, it is not possible to include the SSL handshake in addition to the initial SPDY connection. The SPDY connection is from a cold start (I stop the server before each). Still, the SSL handshake would add ~0.5 seconds to the entire conversation, meaning that SPDY is still an easy winner.

For completeness' sake, spdy/2 looks like:


SPDY/2: 1.25 seconds.

And SPDY/2 with push:


SPDY/2: 1.03 seconds.

So the final tally is:

TrialTime (s)
SSL5.03
spdy/31.1
spdy/3 push0.74
HTTP2.7
spdy/21.25
spdy/2 push1.03

I am unsure why the spdy/3 numbers both beat the corresponding spdy/2 numbers. I would expect them to be about the same since spdy/3 adds flow control, but little to speed up this particular page. For now, I chalk it up to small number statistics—I only ran one run for each.

Regardless, the clear winner is SPDY. Tomorrow, I will repeat the spdy/3 part of the experiment with Chrome and Firefox—this time watching TCP traces. That should serve as a nice last word on spdy/3 flow control.

Day #394

Monday, May 21, 2012

Spdy/3 Push

‹prev | My Chain | next›

I have not had any brain waves since yesterday's failure to get SPDY server push working with version 3 of the protocol's specification. It is disappointing given that I was able to add support for it to node-spdy back when spdy/2 was the latest version and since I have been able to support the new spdy/3 flow control in node-spdy. I had hoped that SPDY server push would just work. Alas.

Before soliciting others for advice, I would like to throw up a sample site that others might use to debug. Since www.spdybook.com is already spdy/3 powered, that seems like a good place to do it.

So I go about copying over the views, images and stylesheets that make up this awesome, "real" world site:


Next, I need to copy in the express.js routes. I add one for regular access (/real) and one for the currently broken push (/push):
app.get('/real', function(req, res){
  res.render('real', {
    title: 'Hello (real) World!'
  });
});


app.get('/push', function(req, res){
  // do push stuff

  res.render('real', {
    title: 'Hello (real) World!'
  });
});
Say... while looking at the "// do push stuff" section, I notice that I never tried a colon header for status:
app.get('/push', function(req, res){
  var headers = {
    ':scheme': 'https',
    ':host': 'localhost:3000',
    // ':path': '/stylesheets/style.css',
    ':path': '/images/00-h.jpg'
    // 'content-type': 'image/jpeg'
    // status: 200,
    // version: 'http/1.1',
    // url: url,
    // ':method': 'GET',
    // ':version': 'HTTP/1.1',
    // ':last-modified': (new Date).toGMTString()
  };
  // ...
});
Odd, I thought I had tried every combination. It couldn't be that simple, could it?

YUP!

Updating the headers to include a spdy/3 colon header like so:
app.get('/push', function(req, res){
  var headers = {
    ':scheme': 'https',
    ':host': req.headers.host,
    ':status': 200,
    ':version': 'HTTP/1.1',
    ':path': '/images/00-h.jpg'
  };

  res.push('/images/00-h.jpg', {}, function(err, stream) {
    fs.createReadStream('public/images/00-h.jpg').pipe(stream);
  });
  // ...
});
Does the trick. In Chrome's SPDY tab (under chrome://net-internals), I see the SPDY session, the push packets, the adopted SYN_STREAM and, most importantly, no "invalid" stream error:
SPDY_SESSION_PUSHED_SYN_STREAM
--> associated_stream = 1
--> flags = 2
--> :host: localhost:4000
    :path: /images/00-h.jpg
    :scheme: https
    :status: 200
    :version: HTTP/1.1
--> id = 2

SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 1300
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 346
--> stream_id = 2
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 0
--> stream_id = 2

SPDY_STREAM_ADOPTED_PUSH_STREAM
I had truly despaired that I would not get that working. Turns out I only needed fresh eyes.

I push those two routes out to the SPDY Book marketing site. If you would like to try them out, they are at:Before calling it a night, I make pretty graphs with the Speed Tracer plugin for Chrome. The "real world" site:


From the start of the graph a 2.45s (I really wish Speed Tracer could normalize to 0 seconds) until the last image is transferred past the 3.16 second mark is roughly 0.7 seconds. I should probably add more images and make them a little larger to make my "real world" example more real world. Still that 0.7 seconds is nothing to sneeze at.

How about with push enabled?


From the start at the 9.32 mark until the last image is pushed into browser cache at roughly 9.62 seconds means that SPDY push moved the same already very fast site in 0.3 seconds. Nice!


Day #393

Sunday, May 20, 2012

Can't SPDY/3 Push

‹prev | My Chain | next›

I have sample node-spdy sites available. The older version that still relies on express-spdy is pretty solid. The spdy-v3 branch more or less works... except for SPDY server push.

SPDY server push is a fascinating (and a little scary) feature of SPDY. It allows the server to push resources directly into the browsers cache. In this way, resources can get served without the round-trip request-response typified by old HTTP.

I try to push the stylesheet for my "real world sample site" to the browser when it requests the /real resource:
app.get('/real', function(req, res){
  headers = {
    ':scheme': 'https',
    ':host': 'localhost:3000',
    ':path': '/stylesheets/style.css'
  };

  res.push('/stylesheets/style.css', headers, function(err, stream) {
    fs.createReadStream('public/stylesheets/style.css').pipe(stream);
    // fs.readFile('public/stylesheets/style.css', function (err, data) {
    //   if (err) throw err;
    //   console.log('stream writing: ' + data);
    //   stream.end(data);
    // });
  });

  res.render('real', {
    title: 'Hello (real) World!'
  });
});
I added the colon headers (:scheme, :host, etc) since spdy/3 requires them. Then I create a readable stream from the file system and pipe it back to the push stream.

And it almost works. In the SPDY tab of chrome://net-internals, I see the push stream initiated immediately after the request is send and before the SYN_REPLY reply comes back:
SPDY_SESSION_SYN_STREAM
--> flags = 1
--> :host: localhost:3000
    :method: GET
    :path: /real
    :scheme: https
    :version: HTTP/1.1
    accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    accept-encoding: gzip,deflate,sdch
    accept-language: en-US,en;q=0.8
    referer: https://localhost:3000/
    user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 Safari/536.11
--> id = 1
SPDY_SESSION_PUSHED_SYN_STREAM
--> associated_stream = 1
--> flags = 2
--> :host: localhost:3000
    :path: /stylesheets/style.css
    :scheme: https
    status: 200
    url: https://localhost:3000/stylesheets/style.css
    version: HTTP/1.1
--> id = 2
SPDY_SESSION_SYN_REPLY
--> flags = 0
--> :status: 200
    :version: HTTP/1.1
--> id = 1
I even see the push data come through and my coveted "adopted" push stream:
SPDY_SESSION_PUSHED_SYN_STREAM
--> associated_stream = 1
--> flags = 2
--> :host: localhost:3000
    :path: /stylesheets/style.css
    :scheme: https
    status: 200
    url: https://localhost:3000/stylesheets/style.css
    version: HTTP/1.1
--> id = 2
SPDY_SESSION_SYN_REPLY
--> flags = 0
--> :status: 200
    :version: HTTP/1.1
--> id = 1
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 221
--> stream_id = 2
...
SPDY_SESSION_RECV_DATA
--> flags = 0
--> size = 0
--> stream_id = 2
SPDY_STREAM_ADOPTED_PUSH_STREAM
But the page does not actually load (at least not for a minute or so). And I see this in the SPDY tab:
...
SPDY_SESSION_RST_STREAM
--> description = ""
--> status = 2
--> stream_id = 3
SPDY_SESSION_CLOSE
--> description = "bytes_read is <= 0."
--> status = -100
SPDY_SESSION_POOL_REMOVE_SESSION
--> source_dependency = 226371 (SPDY_SESSION)
SPDY_STREAM_ERROR
--> description = "ABANDONED (stream_id=2): /stylesheets/style.css"
--> status = -100
--> stream_id = 2
Back when I was first exploring SPDY server push, I found arcane rules that were needed in order get Chrome to handle the push properly. I try various combinations of those rules and attempt to push different resources, but to no avail. Even if I remove all headers but those explicitly mentioned in version 3 of the SPDY specification:
SPDY_SESSION_PUSHED_SYN_STREAM
--> associated_stream = 1
--> flags = 2
--> :host: localhost:3000
    :path: /images/00-h.jpg
    :scheme: https
--> id = 2
I still end up with an invalid stream:
SPDY_STREAM_ERROR
--> description = "ABANDONED (stream_id=2): /images/00-h.jpg"
--> status = -100
--> stream_id = 2
Looking through the Chromium source code, this error arises when a SPDY session times out and there are still streams open.

But why is that stream still open? Node-spdy sent a DATA FIN packet. Chrome even seemed to acknowledge that it received the DATA FIN by virtue of the zero length DATA packet (Chrome has never logged FIN flags for some reason) and the SPDY_STREAM_ADOPTED_PUSH_STREAM log message.

But, sure enough, after the session times out with the push stream abandoned, Chrome makes another, non-push request for my push resource in a new SPDY session:
SPDY_SESSION_SYN_STREAM
--> flags = 1
--> :host: localhost:3000
    :method: GET
    :path: /images/00-h.jpg
    :scheme: https
    :version: HTTP/1.1
    accept: */*
    accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    accept-encoding: gzip,deflate,sdch
    accept-language: en-US,en;q=0.8
    referer: https://localhost:3000/real
    user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 Safari/536.11
--> id = 1
In other words, even though I said that I was going to push that image, Chrome seemed to acknowledge that I was pushing that image and that it received bunches of data without error, this resource is still not in Chrome's browser cache.

I suspect that I am missing a magic header or two somewhere. I will likely have to ask on the mailing list because I have to call it a night with it still broken.


Day #392

Saturday, May 19, 2012

Sample Node-Spdy Sites (from The SPDY Book)

‹prev | My Chain | next›

I am nearly done with my exploration of SPDY flow control. New in version 3 of the protocol, flow control has proven tough to pin down, but I think I have a good handle on it.

One loose end is a more realistic example of a web page. I had that last year and it turns out that some readers of The SPDY Book want to play with that code. So why not kill two birds with one stone?

I git init a new repository and copy over the express-spdy code. One change that I need is to edit the package.json. The following should allow someone with a recent stable node.js (i.e. node.js 0.6.x) to npm install and then run the server:
{
    "name": "spdy-sample"
  , "version": "0.0.1"
  , "private": true
  , "dependencies": {
      "express-spdy": "0.1.3"
    , "jade": ">= 0.0.1"
  }
}
So, I try it :
➜  spdy-sample git:(master) ✗ npm install
...
jade@0.26.0 ./node_modules/jade
├── commander@0.5.2
└── mkdirp@0.3.0

express-spdy@0.1.3 ./node_modules/express-spdy
├── mkdirp@0.3.0
├── express@2.5.9 (qs@0.4.2, mime@1.2.4, connect@1.8.7)
├── connect-spdy@0.1.2 (connect@1.8.7)
└── spdy@0.1.4 (zlibcontext@1.0.9)
➜  spdy-sample git:(master) ✗ node app
Express server listening on port 3000
Nice!

Loading the page up in the browser, I see a super cool SPDY page:


The SPDY tab in chrome://net-internal verifies not only that this is SPDY (version 2), but also that SPDY server push still works:
SPDY_SESSION_SYN_STREAM
--> flags = 1
--> accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
    accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    accept-encoding: gzip,deflate,sdch
    accept-language: en-US,en;q=0.8
    cache-control: no-cache
    cookie: [value was stripped]
    host: localhost:3000
    method: GET
    pragma: no-cache
    referer: https://localhost:3000/
    scheme: https
    url: /real
    user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 Safari/536.11
    version: HTTP/1.1
--> id = 1
SPDY_SESSION_SYN_REPLY
--> flags = 0
--> connection: keep-alive
    content-length: 3316
    content-type: text/html
    status: 200 OK
    version: HTTP/1.1
    x-powered-by: Express
--> id = 1
SPDY_SESSION_PUSHED_SYN_STREAM
--> associated_stream = 1
--> flags = 2
--> last-modified: Sun, 20 May 2012 03:11:40 GMT
    status: 200
    url: https://localhost:3000/stylesheets/style.css
    version: http/1.1
--> id = 2
....
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
SPDY_STREAM_ADOPTED_PUSH_STREAM
...
The SPDY_STREAM_ADOPTED_PUSH_STREAM is important—unless you see that, something went wrong with SPDY push.

I add a README and the sample app is ready on GitHub. For good measure, I add a separate spdy-v3 branch as well.

Hopefully this will prove useful to folks.


Day #391

Thursday, May 17, 2012

Firefox SPDY/2 vs SPDY/3 in Graphs

‹prev | My Chain | next›

The setup for network testing is a real pain. Stop the server, stop the browser, start the server, start a fresh Wireshark capture, start the browser, stop the capture, save, and analyze. Then change something oh-so-slightly and repeat.

To be sure, it can produce some pretty graphs, like a Chrome SPDY/2 connection from last night:


It occurs to me that I failed to grab a Firefox spdy/2 conversation last night. I ended my research frustrated with spdy/3 charts for both Chrome and Firefox, but Firefox's flow control is significantly different than Chrome's. So, for completeness's sake, I will make new Firefox charts -- for both spdy/2 and spdy/3.

As I did last night, I set the RTT for packets to 100ms to somewhat approximate real-world connections (while still retaining easy math):
➜  ~  sudo tc qdisc add dev lo root netem delay 50ms
[sudo] password for chris: 
➜  ~  ping localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 time=100 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=2 ttl=64 time=100 ms
...
With that, I capture a Firefox spdy/2 conversation:


As I suspected, that is just like the Chrome spdy/2 conversation—the outgoing packets fill the TCP/IP receive window nicely, which grows nicely. This is TCP/IP slow start in action—my single SPDY interweb tube is warming as desired.

The Firefox spdy/3 conversation last night was not nearly as satisfying. The outgoing packets filled the receive window, but the receive window never grew—resulting in a very slow SPDY conversation.

I am not going to compare last night's data with tonight's so I start a new spdy/3 capture:


Wait... that looks exactly like the spdy/2 conversations. Actually, there are slight delays as node-spdy decides if SPDY/3 flow control is warranted (it never is for Firefox), but that looks almost identical. Why did I see something so different last night? Could I be making a mistake tonight?

The answer the latter question is "no" — there is no mistake. This is a spdy/3 conversation:


So it would seem that the mistake was last night. I try reproducing the experiment several more times and always see the same thing: spdy/2 and spdy/3 are essentially identical.

In fact this is what I had been hoping to see (which makes it somewhat harder to accept tonight's results). Since Firefox specifies a per-stream initial receive window of 256mb (much larger than any resource on my test page), there should be no reason for flow control to kick in. This, in turn, should mean that spdy/2 and spdy/3 are the same—at least for Firefox.

And (tonight), that is the case. But what about Chrome?

The Chrome spdy/2 conversation remains blazing fast—essentially identical to the Firefox spdy/2 and spdy/3 conversations. But maybe I made a similar mistake with the Chrome spdy/3 conversation?

Nope:


And again, this does not surprise me too much.

Where the Firefox receive window seems too large to me, the Chrome receive window seems too static. If I print out what node-spdy thinks the receive window is throughout the conversation, I see:
Express server listening on port 3000 in development mode
transferWindowSize(7): 62668
transferWindowSize(9): 56560
transferWindowSize(7): 65536
transferWindowSize(9): 41744
transferWindowSize(7): 60336
transferWindowSize(9): 38876
transferWindowSize(7): 65536
transferWindowSize(9): 57860
transferWindowSize(7): 61244
transferWindowSize(9): 48760
transferWindowSize(7): 50060
transferWindowSize(9): 62420
transferWindowSize(7): 61120
transferWindowSize(9): 59160
transferWindowSize(7): 50060
transferWindowSize(9): 52020
transferWindowSize(7): 61120
transferWindowSize(9): 55260
transferWindowSize(7): 50060
transferWindowSize(9): 55260
transferWindowSize(7): 60460
transferWindowSize(9): 52020
transferWindowSize(7): 50720
transferWindowSize(9): 59160
transferWindowSize(7): 60460
transferWindowSize(9): 62420
transferWindowSize(7): 50060
transferWindowSize(9): 64360
transferWindowSize(9): 52660
transferWindowSize(9): 58520
transferWindowSize(9): 52660
It never goes above the initial receive window of 64kb. So, every 64kb or so, node-spdy has no choice but to pause until Chrome updates the window. It is never too long—maybe a few hundredths of seconds—but it takes long enough that node-spdy, of more specifically, node.js, notices that it has 64kb of data lying about. That will not push the TCP/IP receive window, but it's enough that node.js will drain it and send it on the wire.

I do not think this is necessarily an indictment of spdy/3 flow control or of Chrome's implementation. Rather it suggests that Chrome spdy/3 is not optimized for a web page with little else besides two overly large (~200kb each) images.

Up tomorrow, I think I need to have a closer look at a more realistic scenario—dozens of images and resources instead of just the two. But, thankfully, I can call it a night with a little less confusion.


Day #389

Wednesday, May 16, 2012

Wireshark Graphs and Node-Spdy

‹prev | My Chain | next›

I now have a working implementation of SPDY version 3 in node-spdy. It works with Chrome, spdylay and even Firefox sandbox builds. It works, but it is dog slow. Slower than spdy/2 and even slower than vanilla SSL.

So, in the spirit of first get it working, then do it right, then optimize, well... tonight I skip ahead to optimization—at least of the network.

There is no sense in optimizing for the loopback interface—I would be doing little more than optimizing socket writes. So I start tonight by adding a round trip time (RTT) of 100ms to the loopback interface to make things a bit more realistic (the slowness is still apparent):
sudo tc qdisc add dev lo root netem delay 50ms
First up, I try adding timing output to the spdy/3 flow control in node.js. Specifically, I want to know the times at which node-spdy exhausts the receive window and the times at which Chrome sends back WINDOW_UPDATE to replenish the receive window. It is entirely possible that node-spdy is forced to wait, essentially doing nothing, while Chrome processes already sent data. I doubt it, but it's possible.

It turns out that it is really hard to identify periods of inactivity in node.js, so I give up on that idea quickly.

With that idea down the drain, it is time to break out Wireshark. Specifically, some the node graphing tools that it includes.

For instance, the spdy/3 conversation looks something like:


Compare that with the spdy/2 conversation:


Yikes! The spdy/2 conversation is filling up the TCP/IP receive window much faster. It is also growing the receive window much faster.

I have been speculating that Firefox's SPDY receive window of 256mb is little better than spdy/2, so I try it out:


Indeed it does look a little better, but it is not growing the window nearly as fast as spdy/2.

If this were just Chrome not growing the SPDY receive window, which in turn did not allow the TCP/IP window to grow, then Firefox's curve should be just as steep as spdy/2. Since it is not, there much be something about my node-spdy flow control that is also having a chilling effect on the SPDY conversation. Bummer.

At least I know where to start looking when I pick back up tomorrow.

Day #388