Some Bits: Nelson's log

12 posts in May 2014

My first Node server

I rewrote this Python CGI server in to a Node.js server, or most of one. The main thing it does is accept POST content, writing it to a file and returning a generated filename. (Yes, that’s really a PUT. I know.) The Python CGI is 39 lines, the Node.js is 52 with 12 lines of NPM configuration. But then the Node version is a full server and has fancier message handling. Things I learned:

The Node community and docs are good but nowhere near as mature as Python. Also the Node philosophy is one small stable core, then you download add-on modules. Batteries not included. The core Node API is well documented. Beyond that you’re hunting through npmjs or maybe node.js modules for more.

NPM isn’t so scary. Grab a template, put your dependencies in a packages.json, run “npm install” and it will build a node_modules directory for you with all the dependencies. It’s good that’s a default tool deep in the Node chain. More info on npm.

express is a reasonable webapp framework and has a nice tutorial guide. I like the router style of specifying handlers.

node by default doesn’t do anything with POST body content, you have to install middleware to handle the input bytes. senchalabs / connect seems to be the default choice for doing fancy things like parsing JSON, etc. I just want the plain message text so the raw-body middleware middle is for me. It’s an awful lot of boilerplate to set up.

I’m gonna need a content hash; here’s a pure Javascript implementation of Murmur 128 that’s in npm as “murmurhash3js”. Hard to come by; it’s tricky doing true bit twiddling in Javascript without proper bit types. NPM turns up 10 different Murmur implentations, many of which either require native code or only implement the 32 bit hash.

 

fragments of thoughts on window.history

I’m trying to do an Ajax thing where I’m swapping views of a page based on user clicks and dropping files and stuff, but without any page navigation. A single HTML page webapp. I’ve got it sort of working just using old school manipulation of location.hash, but the back button doesn’t work.

To get the back button working, you need to listen to “popstate” events on the window. One of those fires when the user clicks back or presumably navigates their history in other ways. I’m guessing this event only exists if the browser supports pushState() and popState() functions. Ie: everything but IE 9 and older. But I’m not sure.

Apparently window.history is inconsistent across browsers. History.js is a compatibility library to try to bridge the gap. I’m trying to avoid those, but it may end up being useful.

I’ve got the tools to code up state now, but I’m still tripped up by what my application logic needs to be. Need to sit down and sketch out the control flow. Life sure was easier when the server did all this work :-)

My first Mocha test

OK I’m writing tests in Mocha now! Yay! But what a lot of boilerplate. I want to test a javascript file that works great in a browser. It’s named “lol-netlog-parse.js” and contains a single top level function named parseLolNetlog. Let’s just do a fake test for now.

require('chai').should();
var parse = require("../webapp/lol-netlog-parse")

describe('lol-netlog-parse', function() {
    describe('parseLolNetlog', function() {
        it('Should throw an error', function() {
            "foo".should.equal("bar");
        });
})});

This actually works. But only if I wrap my browser code in some require.js boilerplate to set exports. But then the exports object doesn’t exist in browsers, so I have to do extra work to provide a stub exports object in the browser so that it will still run.

It’s also 7 lines of code for a 1 line test. All test frameworks have their boilerplate, and I understand why this all helps with more complex text harnesses. Still sometimes I think Python doctest had the write idea.. The relative path in the require is a pretty ugly wart too, maybe if I knew more about Node and include paths I wouldn’t have to do that.

I’ve written this in the BDD style, where the function “suite” is named “describe” in some vague attempt at literate programming. I did this because it’s the default style Mocha wants and I don’t want to have to add the “-u” command line flag to use the TDD style. It’s very clever that the code supports 4+ different ways to write unit tests but that’s 3+ more than is necessary. One way to do things; it’s a virtue.

I’m fully embracing the BDD style and using chai’s scary Object prototype manipulation to see if I like it.

Javascript unit testing options

I want to write some Javascript unit tests. I’d hoped Node.js would be mature enough there was one clear answer from that community, but there’s not. This article was useful but two years old. Here’s some options:

  • Mocha: fancy
  • NodeUnit: simple
  • vows: d3js uses this, but I’ve seen some comments it’s not the fresh choice
  • QUnit: been around a long time, browser oriented

I tried looking at most starred modules and nodejsmodules.org to try to figure out what the cool kids were using but it was too much work.

I’ll probably use Mocha unless it seems too hard to do simple things. It seems particularly crazy that there’s not even a consensus assert module. “There’s more than one way to do things” is usually not a virtue.

 

Bad default QoS settings in Tomato/Shibby

I had a problem with the QoS settings in my new router firmware where file downloads weren’t using the full network bandwidth. Even if nothing else was trying to use the network, I was being limited to about 2/3 capacity. Finally figured out the cause: the default Inboumd Rates classified “WWW” and a bunch of other stuff to max out at 60%. I don’t think that’s an appropriate setting for home installations. The QoS should be there to give all TCP flows fair scheduling and, ideally, give important traffic higher priority. Bandwidth reservation is sort of a last resort.

The problem is the Tomato/Shibby QoS settings are very complicated. The key thing are the rate limits in the QoS/Basic Settings page, particularly Inbound for traffic coming into the router from the Internet. Here’s where I ended up:

Screen Shot 2014-05-24 at 7.53.07 AM

That setting says “all traffic classified as Service should use between 5% and 100% of the bandwidth”. The default setting for WWW was “20% to 60%” or something, or maybe that was FileXfer. Anyway, didn’t make sense. Frankly I think all of these could just be 0–100 and it’d work fine, if I understand correctly the router will still give higher classes more priority.

The other half of this is the classification and that’s gotten quite complex with 43 rules! They mostly seem reasonable to me, services like DNS and NTP are given highest “Service” priority. There’s some crazy Layer 7 classifier picking out applications like Youtube, irc, flash video, and a bunch of games. Sadly no L7 classifier for League of Legends, although given that’s UDP I’m not even sure the QoS settings can do that much.

I added some TCP rules to give my Roku device Media classification. Seems to work, I was able to reliably stream high quality video off Twitch using 25% of my bandwidth while 4 other TCP flows were downloading at max possible rate from an NNTP server.

The Tomato “View Graphs” pie charts are really useful, the pie charts for Bandwidth Distribution show current classification and flows. “Zoom graphs” is useful, it shows unused bandwidth as a white wedge.

 

MacOS finder is garbage

I’m looking at a Finder window for the folder /Applications/League of Legends.app/Contents/LOL/Logs/Network Logs. It looks like this

Screen Shot 2014-05-18 at 8.18.07 PM

Then I open a shell in that folder and run ls -l. It looks like this

Screen Shot 2014-05-18 at 8.18.16 PM

Notice how there are files from May 18 that don’t show up in Finder? Yes, the fucking Mac interface can’t even list the files in a local folder correctly. I see this garbage all the time, the Finder window caches some sort of state and doesn’t resync correctly. There’s not even a Refresh option. Perhaps in this case it’s complicated by the fact that some game is writing new files to the directory, maybe it’s using some odd API? But then that’s what the Unix kernel is for; one single creat() system call. And Apple can’t get it right.

Forcing a Finder relaunch fixes it, of course.

Fundamental stuff in MacOS is broken. It’s really awful.

 

Basic HTML5 dropping file demo

Just cooked up this demo HTML file showing how to build a web page that does something to the contents of a file that’s dropped on to it. There’s lots of approaches and tutorials for how to do this, this one is mine.

The challenge is that most of the docs I found dated back to 2010 when drag-and-drop was a bold new idea and was fraught with peril. Now it’s pretty simple and just writing the obvious code works in Chrome, Firefox, and Safari. (I hear there’s another browser but I’m unable to run it, so who cares?)

The most useful document I found while figuring this out was this MDN article. The key concept is that there’s a “drop” event in the DOM. By default that causes the browser to navigate; you override that to provide your own behavior. The FileReader API is also useful, beware that it does not work in IE 9. If I cared I’d probably stop writing my own raw code and use some jQuery plugin or other library to provide compatibility.

 

Another HTML 5 template

Can’t believe I’m doing something this mundane, but here’s a template for a new HTML 5 web document with spots already set up for CSS and Javascript in the body. Way back in 1994 I wrote an emacs mode with one major feature being starting you with a template HTML document. And here I am 20 years later still doing it. At least the doctype string got simpler.

<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8">
<title>TEMPLATE</title>
<style type="text/css">

</style>
</head>

<body>
<script type="text/javascript">

</script>
</body></html>

Haskell notes

Since the Heartbleed bug, I’ve been pondering what language a library OpenSSL should be written in. C is a disaster and C++ is no better. But a component like OpenSSL needs to be buildable into a linkable library, into a .so or .a file that other projects like Apache, Python, etc can then incorporate. And most modern programming languages really don’t work well with the C linker. Javascript, Python, Ruby, Lua, Java, Go ... none of these are suitable langauges for building reusable object code libraries because they either have massive runtime libraries or else toolchains that don’t work with the linker.

Enter Haskell. My friend K.K. recommended looking at it because it’s a modern safe language and is good at linking libraries. I’m not actually going to learn Haskell now, but I did want to collect some of the links and notes he shared with me.

I’m very, very skeptical of bringing new languages into practical software engineering. But the community desperately needs a C replacement, something with safe memory access. Rust is a new effort for this but there’s a lot of work to do. D seems to stand for dead-end.

 

CORS, S3, Origin headers

Learned something new today: Amazon S3 only serves CORS headers if asked to with an Origin: header in the request.

$ curl --silent -i https://s3.amazonaws.com/metro-extracts.mapzen.com/cities.json | head -20
HTTP/1.1 200 OK
x-amz-id-2: d3m01CEUWtx5ZNomSKLJHFihaigT/YZr5B2hY0bpi+KTWvfFWmapxZlEH72yl+v1
x-amz-request-id: 613AC95DCE686F29
Date: Sun, 11 May 2014 23:42:51 GMT
Last-Modified: Sat, 10 May 2014 00:49:14 GMT
ETag: "db184f33f4774a213ff4eb6428ba243c"
Accept-Ranges: bytes
Content-Type:
Content-Length: 56589
Server: AmazonS3

$ curl --silent -H "Origin: http://some.url.com" -i https://s3.amazonaws.com/metro-extracts.mapzen.com/cities.json | head -20
HTTP/1.1 200 OK
x-amz-id-2: 9JqpSl5SOftwRTeIa2b91V+drB1WwM8QySWftj55vSy+cvdQ8RNuRWoceeZW3Gho
x-amz-request-id: 2327BBA990C7F483
Date: Sun, 11 May 2014 23:43:32 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Max-Age: 3000
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
Last-Modified: Sat, 10 May 2014 00:49:14 GMT
ETag: "db184f33f4774a213ff4eb6428ba243c"
Accept-Ranges: bytes
Content-Type:
Content-Length: 56589
Server: AmazonS3

on the idea of reusable D3 chart components

I love D3.js, it’s amazing. But one thing that bugs me is the style it encourages is to write new chart types inline in Javascript. There’s not much in the way for reusable charts, D3’s focus is on making it easier to build your own charts in Javascript. So I find myself painfully rewriting basic histograms and time series and the like. In some sense this is by design; Mike’s style is to parsimonious Javascript and making it easy to actually build charts by hand. And it’s good in that it encourages a diversity of visualizations. But sometimes you just want a simple timeseries, you know?

Of course nothing prevents people from building a chart component suite on top of D3. And lots of people have. Here’s a very quick review of looking at the project web sites for a bunch of efforts. I’m only looking at their ability to produce static visualizations. An API supporting interactions and transitions is significantly more subtle to get right.

The libraries group into two categories. Declarative libraries let you specify a chart simply with a bunch of configuration parameters, no real executable Javascript code. In general, my guess is these are great for doing simple things and hard to customize to go beyond what the library was designed to do. Programmable libraries are more like toolkits on top of D3 that still require some real programming to get results. But then they may give you more access to do complex customizations and interactions.

Declarative libraries

Rickshaw has been around awhile and looks good.

C3.js looks a lot like Rickshaw, see the bar chart example. Seems solid and simple.

Vega is strictly declarative, to the point of emphasizing chart specifications are JSON objects and completely wrapping D3. Has a neat live editor, headless rendering tools, and high-falutin language about “visual grammar”. It’s an impressive package.

Ember Charts by Addepar has some basic chart types. It’s tied to the Ember.js framework and needs Node to develop, also not a lot of activity on GitHub, so I didn’t investigate further.

Tenxer xCharts is declarative but with some programmatic customization. Examples feature using closures inside the chart definitions. Also has notes on customization and extension. Drawbacks are relatively few chart types and that there’s been no code development in eight months.

Programmable libraries

Towards Reusable Charts: Mike’s own opinion on reusability in D3. Advocates encapsulating a chart type in a closure. Doesn’t go much beyond establishing a design pattern. Some of the D3 plugins like Sankey and Horizon are good examples.

NVD3 is a reusable component library that works hard to respect access to underlying D3 design. It’s been around for awhile and seems pretty mature, not many commits in the past few months. The Discrete Bar example is appealingly simple.

Dimple adds chart types on top of D3 that you configure with simple declarative code. But then the advanced examples show you dropping in to the underlying D3 to extend the charts beyond what Dimple provides, which is great.

Bocoup d3.chart is a framework for creating charts, not a chart library itself. Its design is informed by a very thoughtful critique on reusable chart approaches. But it’s pretty early days and it’s aimed more at people writing chart libraries than folks just wanting to draw some charts. Also, I’m bummed the examples aren’t rendering right in JSFiddle. Overall my impression is these guys are pushing on solving the problem I want solved right now.

Summary

I’d use Vega or maybe Rickshaw if I just want some simple graphs. Dimple looks to be the most promising programmable system worth a closer look. I’m stubborn and foolish and like shaving yaks so I’m going to write my own little histogram thing using Mike’s suggested pattern just for the experience. Maybe I’ll end up using Dimple for future projects.

Example

Here’s an example trivial new chart type based on Mike’s proposed format. I’m not very happy with this result.

Update

dc.js is an interesting option. It takes too much programming to really just be reusable chart templates, but it has a nice way of packaging in crossfilter and aiding making basic data charts instead of arbitrary D3 SVG marks.

 

Using Tomato to make a wireless access point

I need a second wireless access point in my house, to deal with crappy wifi signal strength through lathe-and-plaster walls. I’m using an ASUS-RT16N running Tomato/Shibby to do this.

There’s a bunch of ways to string together wireless networks. There’s wifi repeaters (no wires), ethernet bridges, WDS, blah blah. This system is acting as a wireless access point; its whole job is to accept traffic on a wifi network and then share it to a wired ethernet.

In a nutshell, the configuration is to plug the house ethernet into one of the LAN ports on the router (not the WAN!). Then disable the WAN interface entirely in Tomato, and statically configure the router to a specific IP address on your wired network. Then set up the WAN as you’d want.

Here’s some details from Toastman. It looks a little different with the Shibby build, the LAN configuration is now hidden in this complicated bridge thing. But the idea is the same. One hint I picked up from elsewhere is to also go into the Administration thing and change the skin / color of the UI, just so you don’t get it confused with your main router.