Links

pmuellr is Patrick Mueller

other pmuellr thangs: home page, twitter, flickr, github

Showing posts sorted by date for query json. Sort by relevance Show all posts
Showing posts sorted by date for query json. Sort by relevance Show all posts

Monday, March 14, 2016

watching your projects

I'm a big fan of having an "automated build step" as part of the development workflow for a project. Figured I'd share what I'm currently doing with my Node.js projects.

What is an "automated build step"? For me, this mean some "shell" code that gets run when I save files while developing. It may not actually be "building" anything - often I'm just running tests. But the idea is that as I save files in my editor, things are run against the code that I just saved.

So there's basically two concepts here:

  • file watchers - watching for updates to files
  • code runners - when files are updated, run some code

file watchers

I have some history with file watchers - wr, jbuild, cakex. The problem with file watching is that it's not easy. The file watching bits in jbuild and cakex are also bundled with other build-y things, which is good and bad - basically bad because you have to buy in to using jbuild and cakex exclusively. wr is a little better in that it's just a file watcher/runner, but I ended finding a replacement for that with nodemon. The advantage to using nodemon is that it's already an accepted tool, and I don't have to support it. :-) Thanks Remy!

code runners

There are many options for code runners; make, cake, grunt, gulp, npm scripts, etc. I'm currently using npm scripts, because they're the easiest thing to do, for non-complex "build steps".

For example, here are the scripts defined in the package.json of the nsolid-statsd package.

"scripts": {
  "start": "node daemon",
  "utest": "node test/index.js | tap-spec",
  "test": "npm run utest && standard",
  "watch": "nodemon --exec 'npm test' --ext js,json"
}

Everything's kicked off by the watch script. It watches for file changes - in this case, changes to .js and .json files, and runs npm test when file changes occur. npm test is defined to run the test script, and for this package, that means running npm run utest and then standard. utest is the final leg of the scripts here, which runs my tape tests rooted at test/index.js, piping them through tap-spec for colorization, etc.

So the basic flow will be this, when running the watch script:

  • run node test/index.js, piping through tap-spec
  • if that passes, run standard
  • wait for a .js or .json file to change
  • when one of those files changes, start over from the beginning

Just run the watch script in a dedicated terminal window, perhaps beside your editor, and start editing and saving files.

Note that nodemon, standard and tap-spec are available in the local node_modules directory, because they are devDependencies in the package itself (tape is used when running test/index.js):

"devDependencies": {
  "nodemon": "~1.8.1",
  "tape": "~4.2.0",
  "tap-spec": "~4.1.1",
  "standard": "~5.4.1"
}

As such, I can use their 'binaries' directly in the npm scripts.

command line usage

You would then kick this all off by running npm run watch. But since it turns out I've been adding a watch script to projects for a long time, all of which do basically the same thing (maybe with different tools), I instead wrote a bash script a while back called watch:

#!/bin/sh
npm run watch

So now I just always run watch in the project directory to start my automated build step.

Here's what the complete workflow looks like:

  • open a terminal in the project directory
  • open my editor (Atom)
  • run watch at the command-line
  • see the tests runs successfully
  • make a change by adding a blank line that standard will provide a diagnostic for
  • save file
  • see tests run, see message from standard
  • remove blank line, save file
  • see tests run, no message from standard

(open image in a new window)

It's basically an IDE using the command-line and your flavorite editor, and I love it.

As projects get more complex, I'll start using some additional tooling like make, cake, etc, or just invoke stand-alone bash or node scripts available in a tools directory. Those would just get added as new npm scripts, and injected into the script flow with nodemon. For instance, you might do something like this:

"scripts": {
  "start": "node daemon",
  "utest": "node test/index.js | tap-spec",
  "test": "npm run utest && standard",
  "build": "tools/build.sh",
  "build-test": "npm run build && npm test",
  "watch": "nodemon --exec 'npm run build-test' --ext js,json"
}

Now when I watch, tools/build.sh will be run before the tests. You can also run each of these steps individually, via npm run build, npm test, npm run utest, etc.

Monday, September 28, 2015

getting started with N|Solid at the command line

Last week, NodeSource (where I work) announced a new product, N|Solid . N|Solid is a platform built on Node.js that provides a number of enhancements to improve troubleshooting, debugging, managing, monitoring and securing your Node.js applications.

N|Solid provides a gorgeous web-based console to monitor/introspect your applications, but also allows you to introspect your Node.js applications, in the same way, at ye olde command line.

Let's explore that command line thing!

installing N|Solid Runtime

In order to introspect your Node.js applications, you'll run them with the N|Solid Runtime, which is shaped similarly to a typical Node.js runtime, but provides some additional executables.

To install N|Solid Runtime, download and unpack an N|Solid Runtime tarball (.tar.gz file) from the N|Solid download site. For the purposes of this blog post, you'll only need to download N|Solid Runtime; the additional downloads N|Solid Hub and N|Solid Console are not required.

On a Mac, you can alternatively download the native installer .pkg file. If using the native installer, download the .pkg file, and then double-click the downloaded file in Finder to start the installation. It will walk you through the process of installing N|Solid Runtime in the usual Node.js installation location, /usr/local/bin.

If you just want to take a peek at N|Solid, the easiest thing is to download a tarball and unpack it. On my mac, I downloaded the "Mac OS .tar.gz" for "N|Solid Runtime", and then double-clicked on the .tar.gz file in Finder to unpack it. This created the directory nsolid-v1.0.1-darwin-x64. Rename that directory to nsolid, start a terminal session, cd into that directory, and prepend it's bin subdirectory to the PATH environment variable:

$ cd Downloads/nsolid
$ PATH=./bin:$PATH
$ nsolid -v
v4.1.1
$

In the snippet above, I also ran nsolid -v to print the version of Node.js that the N|Solid Runtime is built on.

This will make the following executables available on the PATH, for this shell session:

  • nsolid is the binary executable version of Node.js that N|Solid ships
  • node is a symlink to nsolid
  • npm is a symlink into lib/node_modules/npm/bin/npm-cli.js, as it is with typical Node.js installs
  • nsolid-cli is a command-line interface to the N|Solid Agent, explained later in this blog post

Let's write a hello.js program and run it:

$ echo 'console.log("Hello, World!")' > hello.js
$ nsolid hello
Hello, World!
$

Success!

the extra goodies

N|Solid Runtime version 1.0.1 provides the same Node.js runtime as Node.js 4.1.1, with some extra goodies. Anything that can run in Node.js 4.1.1, can run in N|Solid 1.0.1. NodeSource will release new versions of N|Solid as new releases of Node.js become available.

So what makes N|Solid different from regular Node.js?

If you run nsolid --help, you'll see a listing of additional options and environment variables at the end:

$ nsolid --help
...
{usual Node.js help here}
...
N|Solid Options:
  --policies file       provide an NSolid application policies file

N|Solid Environment variables:
NSOLID_HUB              Provide the location of the NSolid Hub
NSOLID_SOCKET           Provide a specific socket for the NSolid Agent listener
NSOLID_APPNAME          Set a name for this application in the NSolid Console
$

N|Solid policies allow you to harden your application in various ways. For example, you can have all native memory allocations zero-filled by N|Solid, by using the zeroFillAllocations policy. By default, Node.js does not zero-fill memory it allocates from the operating system, for performance reasons.

For more information on policies, see the N|Solid Policies documentation.

Besides policies, the other extra goody that N|Solid provides is an agent that you can enable to allow introspection of your Node.js processes. To enable the N|Solid Agent, you'll use the environment variables listed in the help text above.

For the purposes of the rest of this blog post, we'll just focus on interacting with a single Node.js process, and will just use the NSOLID_SOCKET environment variable. The NSOLID_HUB and NSOLID_APPNAME environment variables are used when interacting with multiple Node.js processes, via the N|Solid Hub.

The N|Solid Agent is enabled if the NSOLID_SOCKET environment variable is set, and is not enabled if the environment variable is not set.

Let's start a Node.js REPL with the N|Solid Agent enabled:

$ NSOLID_SOCKET=5000 nsolid
> 1+1 // just show that things are working
2
>

This command starts up the typical Node.js REPL, with the N|Solid Agent listening on port 5000. When the N|Solid Agent is enabled, you can interact with it using N|Solid Command Line Interface (CLI), implemented as the nsolid-cli executable.

running nsolid-cli commands

Let's start with a ping command. Leave the REPL running, start a new terminal window, cd into your nsolid directory again, and set the PATH environment variable:

$ cd Downloads/nsolid
$ PATH=./bin:$PATH
$

Now let's send the ping command to the N|Solid Agent running in the REPL:

$ nsolid-cli --socket 5000 ping
"PONG"
$

In this case, we passed the --socket option on the command line, which indicates the N|Solid Agent port to connect to. And we told it to run the ping command. The response was the string "PONG".

The ping command just validates that the N|Solid Agent is actually running.

Let's try the system_stats command, with the REPL still running in the other window:

$ nsolid-cli --socket 5000 system_stats
{"freemem":2135748608,"uptime":2414371,"load_1m":1.17431640625,"load_5m":1.345703125,"load_15m":1.3447265625,"cpu_speed":2500}
$

The system_stats command provides some system-level statistics, such as amount of free memory (in bytes), system uptime, and load averages.

The output is a single line of JSON. To make the output more readable, you can pipe the output through the json command, available at npm:

$ nsolid-cli --socket 5000 system_stats | json
{
  "freemem": 1970876416,
  "uptime": 2414810,
  "load_1m": 1.34765625,
  "load_5m": 1.26611328125,
  "load_15m": 1.29052734375,
  "cpu_speed": 2500
}
$

Another nsolid-cli command is process_stats, which provides some process-level statistics:

$ nsolid-cli --socket 5000 process_stats | json
{
  "uptime": 2225.215,
  "rss": 25767936,
  "heapTotal": 9296640,
  "heapUsed": 6144552,
  "active_requests": 0,
  "active_handles": 4,
  "user": "pmuellr",
  "title": "nsolid",
  "cpu": 0
}
$

The full list of commands you can use with nsolid-cli is available at the doc page N|Solid Command Line Interface (CLI) .

generating a CPU profile

Let's try one more thing - generating a CPU profile. Here's a link to a sample program to run, that will keep your CPU busy: busy-web.js

This program is an HTTP server that issues an HTTP request to itself, every 10 milliseconds. It makes use of some of the new ES6 features available in Node.js 4.0, like template strings and arrow functions. Since the N|Solid Runtime is using the latest version of Node.js, you can make use of those features with N|Solid as well.

Let's run it with the agent enabled:

$ NSOLID_SOCKET=5000 nsolid busy-web
server listing at http://localhost:53011
send: 100 requests
recv: 100 requests
...

In another terminal window, run the profile_start command, wait a few seconds and run the profile_stop command, redirecting the output to the file busy-web.cpuprofile:

$ nsolid-cli --socket 5000 profile_start
{"started":1443108818350,"collecting":true}
... wait a few seconds ...
$ nsolid-cli --socket 5000 profile_stop > busy-web.cpuprofile

The file busy-web.cpuprofile can then be loaded into Chrome Dev Tools for analysis:

  • in Chrome, select the menu item View / Developer / Developer Tools
  • in the Developer Tools window, select the Profiles tab
  • click the "Load" button
  • select the busy-web.cpuprofile file
  • in the CPU PROFILES list on the left, select "busy-web"

For more information on using Chrome Dev Tools to analyze a CPU profile, see Google's Speed Up JavaScript Execution page.

Note that we didn't have to instrument our program with any special profiling packages - access to the V8 CPU profiler is baked right into N|Solid! About time someone did that, eh?

You can easily write a script to automate the creation of a CPU profile, where you add a sleep command to wait some number of seconds between the profile_start and profile_stop commands.

#!/bin/sh

echo "starting CPU profile"
nsolid-cli --socket 5000 profile_start

echo "waiting 5 seconds"
sleep 5

echo "writing profile to busy-web.cpuprofile"
nsolid-cli --socket 5000 profile_stop > busy-web.cpuprofile

Or instead of sleeping, if your app is an HTTP server, you can drive some traffic to it with Apache Bench (ab), by running something like this instead of the sleep command:

ab -n 1000 -c 100 http://localhost:3000/

generating heap snapshots

You can use the same technique to capture heap snapshots, using the snapshot command. The snapshot command produces output which should be redirected to a file with a .heapsnapshot extension:

$ nsolid-cli --socket 5000 snapshot > busy-web.heapsnapshot

You can then load those files in Chrome Dev Tools for analysis, the same way the CPU profiles are loaded.

For more information on using Chrome Dev Tools to analyze a heap snapshot, see Google's How to Record Heap Snapshots page.

more info

The full list of commands you can use with nsolid-cli is available at the doc page N|Solid Command Line Interface (CLI) .

All of the documentation for N|Solid is available at the doc site N|Solid Documentation.

If you have any questions about N|Solid, feel free to post them at Stack Overflow, and add a tag nsolid.

Wednesday, September 10, 2014

keeping secrets secret

If you're building a web app, you probably have secrets you have to deal with:

  • database credentials
  • session keys
  • etc

So, where do you keep these secrets? Typical ways are:

  • hard-code them into your source
  • require them to be passed on the command-line of your program
  • get them from a config file
  • get them from environment variables

Folks using Cloud Foundry based systems have another option:

This blog post will go over the advantages and disadvantages of these approaches. Examples are provided for node.js, but are applicable to any language.

secrets via hard-coding

The documentation for the express-session package shows the following example of hard-coding your secrets into your code:

This is awful:

  • If you need to change the secret, you need to change the code; apply some separation of concerns, and keep your code separate from your configuration.

  • If you happen to check this code into a source code management (SCM) system, like GitHub, then everyone with access to that SCM will have access to your password. That might be literally everyone.

Please, DO NOT DO THIS!!

Don't be one of these people. Use one of the techniques below, instead.

secrets via config files

Here is an example using require() to get a secret from a JSON file:

This example takes advantage of the node.js feature of being able to load a JSON file and get the parsed object as a result.

If you're going to go this route, you should do the following:

  • Do NOT store the config file in your SCM, because otherwise you may still be making your secret available to everyone who has access to your SCM.

  • To keep the config file from being stored, add the file to your .gitignore file (or equivalent for your SCM).

  • Create an example config file, say secret-config-sample.json, which folks can copy to the actual secret-config.json file, and use as an example.

  • Document the example config file usage.

You now have an issue of how to "manage" or save this file, since it's not being stored in an SCM.

secrets via command-line arguments

Here is an example using the nopt package to get a secret from a command-line argument:

You can then invoke your program using either of these commands:

node secret-arg.js --sessionSecret "keyboard cat"
node secret-arg.js -s "keyboard cat"

This is certainly nicer than having secrets hard-coded in your app, but it also means you will be typing the secrets a lot. If you decide to "script" the command invocation, keep in mind your script now has your secrets in it. Use the "example file" pattern described above in "secrets via config files" to keep the secret out of your SCM.

secrets via environment variables

Here is an example using process.env to get a secret from an environment variable:

You can then invoke your program using the following command:

SESSION_SECRET="keyboard cat" node secret-env.js

Like using command-line arguments, if you decide to script this, keep in mind your secret will be in the script.

You likely have other ways of setting environment variables when you run your program. For instance, in Cloud Foundry, you can set environment variables via a manifest.yml file or with the cf set-env command.

If you decide to set the environment variable in your manifest.yml file, keep in mind your secret will be in the manifest. Use the "example file" pattern described above in "secrets via config files" to keep the secret out of your SCM. Eg, put manifest.yml in your .gitignore file, and ship a manifest-sample.yml file instead.

secrets via Cloud Foundry user-provided services

Here is an example using the cfenv package to get a secret from a user-provided service:

This is my favorite way to store secrets for Cloud Foundry. In the example above, the code is expecting a service whose name matches the regular expression /session-secret/ to contain the secret in the credentials property named secret. You can create the user-provided service with the cf cups command:

cf cups a-session-secret-of-mine -p secret

This will prompt you for the value of the property secret, and then create a new service named a-session-secret-of-mine. You will need to cf bind the service to your application to get access to it.

There are a number of advantages to storing your secrets in user-provided services:

  • A service can be bound to multiple applications; this is a great way to store secrets that need to be shared by "micro-services", if you're into that kind of thing.

  • Once created, these values are persistent until you delete the service or use the new cf uups command to update them.

  • These values are only visible to users who have the appropriate access to the service.

  • Using regular expression matching for services makes it easy to switch services by having multiple services with regexp matchable names, and binding only the one you want. See my project bluemix-service-switcher for an example of doing this.

secrets via multiple methods

Of course, for your all singing, all dancing wunder-app, you'll want to allow folks to configure secrets in a variety of ways. Here's an example that uses all of the techniques above - including hard-coding an undefined value in the code! That should be the only value you ever hard-code. :-)

The example uses the defaults() function from underscore to apply precedence for obtaining a secret from multiple techniques.

Monday, May 19, 2014

enabling New Relic in a Cloud Foundry node application

Something you will want to enable with your apps running in a Cloud Foundry environment such as BlueMix, is monitoring. You'll want a service to watch your app, show you when it's down, how much traffic it's getting, etc.

One such popular service is New Relic.

Below are some instructions showing how you can enable a node.js application to optionally make use of monitoring with New Relic, and keep hard-coded names and license keys out of your source code.

The documentation for using New Relic with a node application is available in the Help Center documentation "Installing and maintaining Node.js".

But we're going to make a few changes, to make this optional, and apply indirection in getting your app name and license key.

  • instead of copying node_modules/newrelic/newrelic.js to the root directory of your app, create a newrelic.js file in the root directory with the following contents:
  • This module is slightly enhanced from the version that New Relic suggests that you create (see https://github.com/newrelic/node-newrelic/blob/master/newrelic.js). Rather than hard-code your app name and license key, we get them dyanmically.

  • The app name is retrieved from your package.json's name property; and the license key is obtained from an environment variable. Note this code is completely portable, and can be copied from one project to another without having to change keys or names.

  • To set the environment variable for your CloudFoundry app, use the command

    cf set-env <app-name> NEW_RELIC_LICENSE_KEY 983498129....
    
  • To run the code in the initialize() function, use the following code in your application startup, as close to the beginning as possible:

  • This code is different than what you what New Relic suggests you use at the beginning of your application code; instead of doing the require("newrelic") directly in your code, it will be run via the require("./newrelic").initialize() code.

  • If you don't have the relevant environment variable set, then New Relic monitoring will not be enabled for your app.

Another option to keeping your license key un-hard-coded and dynamic is to use a Cloud Foundry service. For instance, you can create a user-provided service instance using the following command:

cf cups NewRelic -p '{"key":"983498129...."}'

You can then bind that service to your app:

cf bind-service <app-name> NewRelic

Your application code can then get the key from the VCAP_SERVICES environment variable.

I would actually use services rather than environment variables in most cases, as services can be bound to multiple apps at the same time, whereas you need to set the environment variables for each app.

In this case, I chose to use an environment variable, as you really should be doing the New Relic initialization as early as possible, and there is less code involved in getting the value of an environment variable than parsing the VCAP_SERVICES values.

You may want to add some other enhancements, such as appending a -dev or -local suffix to the app name if you determine you're running locally instead of within Cloud Foundry.

I've added optional New Relic monitoring to my node-stuff app, so you can see all this in action in the node-stuff source at GitHub.


update on 2014/05/19

After posting this blog entry, Chase Douglas (@txase) from New Relic tweeted that "the New Relic Node.js agent supports env vars directly", pointing to the New Relic Help Center doc "Configuring Node.js with environment variables".

Thanks Chase. Guess I need to learn to RTFM!

What this means is that you can most likely get by with a much easier set up if you want to live the "environment variable configuration" life. There may still be some value in a more structured approach, like what I've documented here, if you'd like to be a little more explicit.

Also note that I specified using an environment variable of NEW_RELIC_LICENSE_KEY, which is the exact same name as the environment variable that the New Relic module uses itself! (Great minds think alike?) As such, it would probably be a good idea, if you want to do explicit configuration as described here, to avoid using NEW_RELIC_* as the name of your environment variables, as you may get some unexpected interaction. In fact, my read of the precedence rules are that the environment variables override the newrelic.js config file settings, so the setting in the newrelic.js is ignored in favor of the environment variable, at least in this example.

Tuesday, October 08, 2013

sourcemap best practices

Source map support for web page debugging has been a thing now for a while. If you don't know what a sourcemap is, Ryan Seddon's article "Introduction to JavaScript Source Maps", provides a technical introduction. The "proposal" for source map seems to be here.

In a nutshell, sourcemap allow you to ship minized .js files (and maybe .css files), which point back to the original source, so that when you debug your code in a debugger like Chrome Dev Tools, you'll see the original source.

It's awesome.

Even better, we're starting to see folks ship source maps with their minized resources. For example, looking at the minized angular 1.2.0-rc.2 js file you can see the sourcemap annotation near the end:

/*
//@ sourceMappingURL=angular.min.js.map
*/

The contents of that .map file looks like this (I've truncated bits of it):

{
"version":3,
"file":"angular.min.js",
"lineCount":183,
"mappings":"A;;;;;aAKC,SAAQ,CAACA,CAAD,...",
"sources":["angular.js","MINERR_ASSET"],
"names":["window","document","undefined",...]
}

You don't need to understand any of this, but what it means is that if you use the angular.min.js file in a web page, and also make angular.min.js.map and angular.js files available, when you debug with a sourcemap-enabled debugger (like Chrome Dev Tools), you'll see the original source instead of the minized source.

But there are a few issues. Although I haven't written any tools to generate source maps, I do consume them in libraries and with tools that I use (like browserify). Sometimes I do a bit of surgery on them, to make them work a little better.

Armed with this experience, I figured I'd post a few "best practices", based on some of the issues I've seen, aimed at folks generating sourcemaps.

do not use a data-url with your sourceMappingURL annotation

Using a data url, which browserify does, ends up creating a huge single line for the sourceMappingURL annotation. Many text editors will choke on this, if you accidently, or purposely edit the file with the annotation.

In addition, using a data-url means the mapping data is uuencoded, which means humans can't read it. The sourcemap data is actually sometimes interesting to look at, for instance, if you want to see what files got bundled with browserify.

Also, including the sourcemap as a data-url means you just made your "production" file bigger, especially since it's uuencoded.

Instead of using a data-url with the sourcemap information inlined, just provide a map file like angular does (described above).

put the sourceMappingURL annotation on a line by itself at the end

In the angular example above, the sourceMappingURL annotation is in a // style comment inside a /* */ style comment. Kinda pointless. But worse, it no longer works with Chrome 31.0.1650.8 beta.

Presumably, Chrome Dev Tools got a bit stricter with how they recognize the sourceMappingURL annotation; it seems to like having the comment at the very end of the file. See https://code.google.com/p/chromium/issues/detail?id=305284 for more info.

Browserify also has an issue here, as it adds a line with a single semi-colon to the end of the file, right before the sourceMappingURL annotation, which also does not work in the version of Chrome I referenced.

name your sourcemap file <min-file>.map.json

Turns out these sourcemap files are json. But no one uses a .json file extension, which seems unfortunate as the browser doesn't understand them, if you happen to try loading one of the files there. Not sure if there's a restriction about naming them, but it seems like there shouldn't be, and it seems like it makes sense to just use a .json extension for them.

embed the original source in the sourcemap file

Source map files contain a list of the names of the original source files (urls, actually), and can optionally contain the original source file content in the sourcesContent key. Not everyone does this - I think most people do not put the original source in the sourcemap files (eg, jquery, angular).

If you don't include the source with the sourcesContent key, then the source will need to be retrieved by your browser. Not only is this another HTTP GET required, but you will need to provide the original .js files as well as the minized .js files on your server. And they will need to be arranged in whatever manner the source files are specified in the source map file (remember, the names are actually URLs).

If you're going to provide a separate map file, then you might as well add the source to it, so the whole wad is available in one file.

generate your sourcemap json file so that it's readable

I'm looking at you, http://code.jquery.com/jquery-2.0.3.min.map.

The file is only used at debug time, it's unlikely there's going to be much of a performance/memory hit by single-lining the file. Remember, as I said above, it's often useful to be able to read the sourcemap file, so ... make it readable.

if you use the names key in your sourcemap, put it at the end of the map file

Again, sourcemap files are interesting reading sometimes, but the names key ends up being painful to deal with, if you generate the sourcemap with something like JSON.stringify(mapObject, null, 4) or something. Because the value of the names key is an array of strings, and it's pretty long, as is not nearly as interesting to read as the other bits in the source map. Add the property to your map object last, before you stringify it, so it doesn't get in the way.

where can we publish some sourcemap best practices?

I'd like to see somewhere we can publish and debate sourcemap best practices. Idears?

bugs opened

Some bugs relevant to the "sourceMappingURL not the last thing in the file" issue/violation:

Wednesday, November 16, 2011

debugging concatenated JavaScript files

In James Burke's blog post "Why not AMD?", the subject of debugging briefly came up. In response to the claim that AMD is "Inefficient by default", James responds: (bold emphasis applied by me)

I assume this means that it allows separate modules to be loaded async. FWIW, the current state of ES harmony modules will allow separate file loading for each module. This works better for debugging.

For AMD, you can get the "one script file at the bottom of the page" loading with the 750 byte almond AMD shim and runtime http loading.

I cannot see a better solution to this issue. If you have ideas I would like to hear them.

I'd like to point out some futures/options for making concatenated scripts easier to debug. None of solutions deal with mangled names, they're just ways of letting the debugger show a concatenated script as the set of individual scripts that make up the concatenated script. Baby steps!

Source Map support in the web debuggers

Werner Schuster's blog post "Mozilla, WebKit To Support Debugging Minified JS As Well As CoffeeScript and other JS Languages" covers most of the ground for the Source Map work that's ongoing. Chris Heilmann's recent presentation from Velocity "Firefox Performance" mentions some work going on at Mozilla.

Of course, we need both ends working here; minizer's are going to have to be able to spit out Source Maps, as well as language translators like CoffeeScript. The CoffeeScript bug for Source Map work is here (I think).

cheating with eval() and //@ sourceurl

Back in the day, a feature in Firebug that I copied into Web Inspector was "sourceURL" support, described in "Give your eval a name with //@ sourceURL". I recently made use of this in my "unminified" version of the injected target weinre script. weinre ships with two versions of the code that gets injected into the target: target-script.js and target-script-min.js. The "min" version is what you should be using for typical weinre debugging, the non-"min" version is what I use when debugging the debugger.

The file target-script-min.js contains gently minized JS files, just concatenated together. The target-script.js file is a bit different. For every JS file, it adds a "//@ sourceurl" comment to the bottom of the file, converts the script content to a string with JSON.stringify(), and then writes an eval([that string here]) to the concatenated file.

The difference between debugging these in a browser which supports sourceurl is night and day. Try it: after visiting these pages, open your web debugger and look at the scripts which are loaded. Note, this works on Google Chrome 16.0.912.36 beta on a Mac (and likely other versions).

Friday, December 17, 2010

weinre at GitHub

I finally pushed my weinre project up to GitHub last night:

weinre - web inspector remote - pronounced "winery"
http://pmuellr.github.com/weinre/

It's a debugger for mobile web apps. Uses the Web Inspector debug front-end from WebKit (implemented in HTML/CSS/JS), plugged up to some plain old JavaScript running in your web page. There's an HTTP server in there somewhere.

It's early days - it may not be the easiest thing to set up and run - and there's a lot of function not implemented (showing all the CSS style info, for instance). But it's something.

I intend to continue enhancing it over the next while. First order of business will be to get it back, function-wise, to where my earlier prototype was, as shown in this video. I've been spending more time on infrastructure stuff than adding debug function lately - it'll be fun to dive back into the innards of Web Inspector again.

My intention is for this work to eventually be folded into the PhoneGap project. PhoneGap (wisely IMO) requires a Contributor Agreement in place before accepting contributions, so I won't be able to accept any contributions into my repo unless you've signed up.

If you have questions, feature requests, etc, create an issue at GitHub. I also hang out on #phonegap on freenode during business hours (US east).

Tasty Innards Too!

Besides this project's subject matter being a fun thing to work on (building a working debugger), I've had a lot of fun building and using smaller thingees. If I can get my blogging going again, hopefully I'll write more about some of these goodies, soon:

  • All my JavaScript code is structured as CommonJS modules, using modjewel.

  • All my JavaScript is written in a pidgin dialect of JavaScript called scoop. Basically just a lexically simpler way to define classes, methods, etc in JavaScript (if you didn't know already, I'm an old Smalltalk dude). Here's an example - the implementation of the Console class used by the debug target.

  • The interface between the large grained components of weinre is specified in a subset-but-extended bastardization of WebIDL. The Web Inspector code already does this itself (because WebKit in general does this also), and it worked out well for me. I wrote a WebIDL-to-JSON compiler, and the runtime makes use of the JSON to create proxies, etc. Lots more interesting stuff can be done here, I'm sure.

Tuesday, April 14, 2009

ordered javascript properties

So all this time, I believed what I had read regarding the ordering of properties when enumerating JavaScript objects with the for...in statement, with this being a typical description:

A for...in loop iterates over the properties of an object in an arbitrary order.

That's from the Mozilla Developer Center JavaScript reference.

Turns out that's not quite true. See John Resig's blog post "JavaScript in Chrome", and scroll down to the section "for loop order". In particular, John writes: "All modern implementations of ECMAScript iterate through object properties in the order in which they were defined. Because of this the Chrome team has deemed this to be a bug and will be fixing it." Follow the links to the bugs John points out in his blog post for more discussion.

I couldn't resist trying this out myself, so created a little test case, here. WebKit Nightlies and FireFox 3.0 behave the same for all the cases, but Opera 9.23 acts a little differently in one of the cases.

John makes a couple of points I can't agree with, in his comments in the Chromium bug that he referenced.

  • The specification does not define how an implementation should handle it - therefore an implementation should conform with other implementations.

    What? How does not having an explicit definition in the spec imply that all implementations should conform with each other?

  • The argument that they're doing it to "keep the engine fast and lean" is bogus. There are two other, faster, ECMAScript engines out there: SquirrelFish and TraceMonkey and they both implement the looping indentically.

    John is referencing a previous comment which claimed that V8 did not respect the 'definition order' because doing so could impact memory usage and/or peformance. But the rationale John makes is that since there are two faster engines which DO implement the 'definition order', the memory/performance rationale is bogus. Which makes no sense of course. I would imagine the typical implementation of 'definition order' would trade space over speed, so you could make the property access "fast enough" by spending some additional space to maintain the order as well as the presumably speedy hash access. Complete guess on my part. But to me, it's hard to imagine that implementing 'definition order' isn't going to cost you SOMEWHERE, over not implementing it. I'm cheap, I don't like to pay for things I don't need.

So not only was I surprised by the property ordering, I'm kind of sad because it means JavaScript has some built-in waste for a feature few objects will probably ever need. Kind of like Java's monitors in every object. Ah well.

A few folks pointed out to me that upcoming EcmaScript standards would likely standardize on this ordering behavior. While it's difficult (for me anyway) to track down EcmaScript standard stuff, I did find this set of drafts which seemed ... recent ... and looking at the "23 Feb 2009" version, you can see phrases like "An ECMAScript object is an unordered collection of properties" (page 14) have been changed to "An ECMAScript object is a collection of properties". Hardly a ringing endorsement of defined property ordering, but a step in that direction, no doubt.

So, I guess change is coming. Next question, how can we make use of this?

One thought is with JSON. Typically with JSON you think of object definitions with key/value properties, all defined "at once". Meaning things like "streaming" JSON objects don't really make sense. Only now, maybe it kinda does. Or you could do something like add a property to an object first, called something like "__type__" which would provide some shape information, which a serializer could make use of, because it would see that before other properties.

That's nice. And is fairly logical. But the memory/performance impact will probably always bug me.

Wednesday, November 12, 2008

brainwashed

I remember reading Michael Lewis's "Liar's Poker" back in the day, and enjoying it, so it's not a big surprise that I also enjoyed reading his recent article on our financial crisis, "The End".

But my reaction to the article is a little different than Tim Bray's "Angry" blog post. Anger is an understandable reaction; we've essentially been fleeced. But when you get fleeced, you have to realize that often you walked right into the scam. One of the people to be angry at, is yourself.

How did this happen?

One word: brainwashing. We all wanted to believe there really was a lot of money to be made, that level of wealth building going on was somehow sustainable, and that we could all be a part of it.


DJIA from 1930 to today - link to live chart

But honestly, did you really believe your realtor when they told you the property prices in the neighborhood you bought into were appreciating 10% a year, with no end in sight? Does it really seem ok to spend $30,000 on an automobile? Can you really look at the historical record of the Dow Jones Industrial Average from the 1930's to today, and say: "I don't see anything abnormal".

We all wanted to believe, so ignored the signs, if we saw them at all. Were there some bad apples out there? Sure. But far more folks who weren't really bad apples, really just duped like we were. Deluded by fantasies of riches. Brainwashed.

Relating this to computer tech

I couldn't help but to extrapolate from my take on Lewis's article, to some of the goings on in the computer tech field today, because I think there's a fair amount of brainwashing going on in tech also. What do you think about the following ideas:

  • Using LaTeX files or Microsoft Word .doc files as serialization formats for structured data.

  • Using C or C++ to build your next web-based application.

To me, these sound crazy. Why would you use a word processing system as the basis for a data serialization format? Nuts, right? But we are. XML traces it's roots back to IBM's Generalized Markup Language, a text markup language not like LaTeX or nroff (good times, good times). XML is frankly not all that different from GML, I'd say easier on the eyes (brackets are easier to visually parse than colons), and more regularized syntax. But it's fundamentally a language to apply bits of text formatting to large amounts of raw text. A typical BookMaster document was mainly plain old text, with occasional tags to mark paragraph boundaries, etc.

Same sort of nutso thinking with Java. A potentially decent systems-level programming language, it could have been a successor to C and C++ had things worked out a bit differently. But as an application programming language? Sure, some people can do it. But there's a level of complexity there, over and above application programming languages we've used in the past - COBOL and BASIC, for instance - that really renders it unsuitable for a large potential segment of the programmer market.

How did these modern-day accidents occur? Hype. Being in the right place at the right time. They more or less worked for simple cases. We all wanted to believe. We brainwashed ourselves.

Luckily, evolution is taking it's toll on these two languages. XML isn't the only game in town now for structured data; JSON and YAML are often used where it makes sense; Roy Fielding notes that perhaps GIF images are an interesting way to represent sparse bit arrays (ok, that's a random mutation in evolutionary terms). We're seeing an upswing in alternative languages where Java used to be king: Ruby, Python, Groovy, etc (with many of these languages having implementations in Java - perfect!).

Reality is setting in; do what makes sense; think different; the hype curve doesn't always point to the right answer.

My new favorite example of tech brainwashing

So while I can't complain so much about XML and Java as I used to, it's kicking a dead horse at this point, I do have a new whipping boy in the tech world for where we've been brainwashed - "web applications". Those things that run in our web browser, giving us the power, beauty and flexibility of desktop apps. Web 2.0. RIAs. GMail and Google Maps.

I don't have to explain to anyone who's ever tried putting together a "Web 2.0 application" the utter pain in doing this. Ignoring server-side issues, you have to deal with three different languages: HTML, CSS, and JavaScript; typically interspersed betwixt themselves. That behave differently in the three to five popular browsers you might hope to support. And the iPhone. Server side programming throws more wrenches in the gears, as in our simpler web 1.0 world, we frequently mixed HTML, CSS, and JavaScript with whatever programming language(s) we used on the server. And we still do, at times, in this new world also, only there's lots more HTML, CSS and JavaScript, so it's even messier.

Or maybe you're using Flex or Silverlight or some other more constrained environment for your web app. But then you have different problems; your users might expect to be able to bookmark in the middle of the app - it's running on the web after all. Or cut and paste some of the content. Etc. And you're probably still deploying in a web browser anyway! There is no escape!

What really frustrates me about the situation we're in, is that we've painted ourselves into a corner. We started with a very useful, mainly read-only, networked hypertext viewer, and over the years bolted new geegaws on the sides. Blink tags. Tables. JavaScript. Frames. DHTML. File uploads. XmlHTTPRequest. SVG. HTML Canvas. (stop me, my head's about to explode!) All great stuff to add to a mainly read-only, networked hypertext viewer. Can you use it to build a word processor? Yes, you can. Well, a team of software developers at Google can. Not sure that I can.

But I used to be able to build GUI apps without a lot of difficulty. High function, richly formatting text editors even. In C, for gawd's sake, though life got a lot easier in Smalltalk.

It's time to stop thinking we can apply bandages to the status quo and make everything better. We want to believe. Just another gadget or framework is going to make everything better! We've brainwashed ourselves.

Wake up! We fundamentally have the wrong tools to do the job. We're using a spoon where we should be using a backhoe. Look down! You're using a spoon for *bleep*'s sake! Don't you realize it? Slap yourself around a little and clear the fog from your eyes. Expect better.

To be a little more concrete, I actually do think that the fundamentals of our web tech economy are sound. I'm not unhappy with HTTP, HTML, CSS, and JavaScript when viewed as separate technologies. I don't think we've fit them together in the best way, to make it easy to build applications with. And they're wrapped in a shell optimized around mainly read-only, history-enabled, page-by-page navigation, which doesn't seem like the best base on which to build an application. It's time for some new thinking here. Can we take some of the basic building blocks we already have and build a better application runtime platform than what we've got in front of us? I have to believe the answer is: Yes we can.

Friday, September 19, 2008

fun with WorkerPools

Arrr

I suspect I''e looked at Google Gears a half dozen or so times since it was originally released. Always looked kinda intarstin', but hadn't mightily any use for it. I took another look when Chrome was announced, since, o' all the stuff in Chrome, the fact that Gears was baked in was the most intarstin' bit t' me.

(Bein' a bit curmugdeonly har, as in, the flashy chrome bits don't excite me. "When I was a kid" my web browser (OS/2's WebExplorer) could only remember 10 bookmarks. The Nintendo DS Browser works for me, in a pinch. Now GET OFF MY YARD!)

Aye

Pirate-speak translation above provided by the Pirate Speak Translator.

Gears is the most interesting bit in Chrome because it's the programmable bit.

What I decided to look through the other day was the WorkerPool bits, since I hadn't really looked into them much before. What I realized pretty quickly is that they should have actually called these ActorPools. You may be familiar with the Actor paradigm via the recent Erlang hotness.

In a nutshell, the WorkerPool facility provides the following capabilities:

  • the ability to run a hunk of JavaScript code in a new context
  • that context does not share code or state with any other JavaScript context, including the context which 'launched' the code
  • the only way to communicate with the code is via asynchronous one-way message sends of arbitrary JavaScript objects (basically, the same sorts of objects describable in JSON; no functions or non-trivial objects allowed, for instance)
  • the ability to run that code independently of other contexts. Think threads, though that's just an implementation detail.

If that's all it was, wouldn't be terribly interesting. You can get aspects of this type of stuff with traditional JavaScript code, though it's often messy. Gears provides, at least, a fairly clean way of providing these capabilities.

But here's where it gets interesting. That hunk of code that you've created a worker for can be loaded from an arbitrary server, referenced via a URL. And then that code follows the "same origin policy" rules for other Gears APIs available to workers, for instance, the Database APIs and HttpRequest APIs. In other words, your worker code can access HTTP-resources on the server it came from, and have a 'protected' Database that it manages that is only visible to workers that also were loaded from that server.

Very cool, because this means that you can build workers that act as self-contained service modules to allow access to HTTP resources for other applications to use. None of the usual cross-site chicanery we've had to deal with. In addition, these modules can manage their own protected cache of data. Also, such modules can be reused across multiple web applications, with each one reusing the same code and database store.

This seems like powerful mojo.

Building an RPC mechanism on top of the message send APIs

One of the downers, for most people, with the current WorkerPool APIs, is going to be the message sending paradigm. It's pretty low-level and raw. The great thing is that asynchronous message sends are a type of atomic building block upon which other forms of IPC can easily be built. The QNX operating system is famously built up on this core concept, slightly expanded.

I've taken a run at building a simple RPC mechanism built on top of the message send API. The proof of concept is available here: http://muellerware.org/ggw-services-poc/. Here's how it works:

To build your RPC-styled worker, create a JavaScript file that includes the services you want to expose, implemented as plain old functions, along with a list of the functions you want to expose. Here's an example of some math services:

    //---------------------------------------------------------
    // service function to add a list of numbers
    //---------------------------------------------------------
    function add() {
        var result = 0
        for (var i=0; i<arguments.length; i++) {
            result += arguments[i]
        }
        return result
    }

    ...

    //---------------------------------------------------------
    // list of exported services
    //---------------------------------------------------------
    services = [
        add,
        ...
    ]
    
    //---------------------------------------------------------
    // boiler-plate from here to end
    //---------------------------------------------------------
    
    ...

At the bottom of this file is some boiler-plate code that deals with the messaging interface. Basically, messages are received that are serialized versions of the function invocation: function name, arguments, and an identifier to indicate which invocation this was (needed to match up return values later). The boiler-plate code cracks open the message, reflectively calls the function, then sends back the function result as a message to the original message sender.

On the client end, in your main HTML / JavaScript code, you'll be using the service like this:

   math_service = new ggw_services_Service("math_services.js")

   ...

   // callback function to display the result of our service call
   function print_sum(sum) {
      ...
   }

   // handler that invokes our service call
   function do_sum() {
      math_service.services.add(print_sum, 1,2,3,4,5,6,7,8,9,10)
   }

   ...

In this code, we instantiate the services with the ggw_services_Service constructor, passing it the URL of the JavaScript code we want to run as a worker - this would be the service implementation file described above. The resulting object will then expose proxies for the exposed functions in the service in the services field of the object. You call these just like normal functions. One trick: because the message sends are one-way, and you'll probably want to get a result back, the first parameter can be a call-back function which is invoked when the service method returns it's value. In this case, that would be the print_sum function.

Neat. But crude. To do this right, would require a bit more infrastructure, as well as making sure you can catch all the sorts of error conditions that can happen. The end result won't be (shouldn't be) as transparent as the example above, but you can probably get pretty close.

Notes

  • Because there is no sharing of code or data in a worker, and anything else, things like debugging get hard, because you can't access the DOM, you can't access the document, you can't access alert(). In FireBug, you can see the message text from Errors, which is useful, especially when you throw them yourself. But the code source isn't identified, just that the error occurred on "worker 0" or the like.

  • Speaking of FireBug, I was able to pretty consistently lock up FireFox while debugging my example. Due to my browser coding naiveté, don't know if this was me, FireBug, Gears, or some combination of them. But it got old fast.

  • It's not clear what the best way is to handle security credentials for HTTP requests from within workers. My gut tells me that some Gears APIs to manage sensitive data like passwords and keys would be useful. Storing credentials in a server-specific database doesn't sound great, but doesn't sound terrible either. But it's not even clear how a worker would go about prompting a user for credentials, and do it safely.

  • The current story for worker code is that all the worker code has to be in a single file. Not great. It would be nice to have an API like loadScript() or some such that would allow you to add additional JavaScript code to your context. In lieu of that, you can always XHR GET your additional code, and eval() it into the context. Icky, but should work.

  • One of the nice things about the stark bleakness of the context in which the workers run is that it makes these workers applicable to other environments. For instance, it's not a huge stretch to consider porting the Gears APIs to Rhino, allowing reuse of the workers from within Java. Very cool for Java, where loading "live code" is typically not something that is done, for various reasons, but this makes it relatively straight-forward.

  • In terms of higher-level frameworks for this stuff, I think I'd start looking at OSGi and it's Bundle and Service concepts. I suspect there's a pretty good fit there. Combined with the previous thought of reusing workers in Java itself, why not design it around OSGi, so that I could actually design a worker such that it could easily be spun into OSGi bundle itself, and so directly consumable by OSGi-friendly code without having to have them deal with "yucky" JavaScript. Having access to JavaScript in Java isn't always considered a "plus" by Java programmers, but they can be easily fooled.

Thursday, August 21, 2008

better than json

Well, JSON is the new hotness. This week. Again. Thought I'd jot down some thoughts I had on JSON last summer, in the area of improving on JSON.

Before doing that, let me go over some of my core beliefs about JSON:

  • It defines an ASCII serialization format for a lowest common denominator of primitive and composite types used in most common programming languages, so it can be used to serialize natural data structures in many environments.

  • JSON doesn't attempt to handle traditional OO mechanics, it's really just plain old simple data and data structures, keeping things simpler.

  • The fact that JSON is legal JavaScript, and so can be eval()'d and <script src="">'d in web browsers via JSONP, is not a benefit, it's a security nightmare waiting to happen. JSON parsers are easy to write, and with JSONP you're giving up too much control over your HTTP requests.

  • The 'readability' and 'writeability' of JSON, by humans, isn't a big priority for me. But it does bug me that it could easily more readable and writable, by humans.

Basically, I like what it can express, and I care less about the syntax.

So, what would I change? Turns out, not much, mainly syntax changes to aid in human readability and writability.

Add some additional primitive data types / literal forms. Some obvious ones would be decimal and date. Most languages can support these, somehow. Date gets dicey in terms of subsetting, like date with no time, time with no date, etc.

Remove the idiotic "\/" escaping rule. People think they have to encode "/" character because it shows up in the 'backslash escapeable character list'. Section 8, Examples, of RFC 4627 has an example which clearly does not use escaped "/" characters. I assume this escaping rule had something to do with the way JavaScript is/was parsed in some web browsers. feh.

Remove extraneous punctuation. The "," separators used between elements in {} and [] structures aren't needed. Make them optional. Same with the ":" characters between key / value pairs in {} structures. For human readable output, I'd not use "," but would use ":", because I like the visual parsing you get between key value pairs. I would typically write key / value pairs on a single line anyway, obviating the need for the "," separator.

Stop requiring quotes around strings unless required. This is the biggest noise reducer. There are only 3 keywords in JSON - true, false, and null. For property keys specifically, many times the key values aren't one of these keywords, aren't another primitive literal value, and don't include whitespace or other separator characters. Their values are basically that of 'identifiers'. That get used unquoted in JavaScript itself, in JavaScript dot notation and object literals.

I assume this quoted property name rule exists is to keep people from inadvertently using JavaScript keywords as property keys, which would then screw up the parse-by-eval() trick. For program generated JSON, it's probably just easier to always use quotes, but when JSON is being rendered for humans, I'd like quotes removed if they could be. When writing literal JSON, I'd also not use quotes if I didn't have to.

The same rules apply for all string usage, not just property keys. But I'd probably typically want to read and write strings as quoted values everywhere but property keys, as that's just what I'm used to.

Using 'bare strings' means that you might write out a property name that in the future became a new JSON keyword. Not good. So perhaps something like the Smalltalk/Ruby symbol syntax construct could be used. Basically a new character prefix, with no terminator, indicating the following characters up to a separator are the string value. If "#" was the prefix, then #abc would be the same thing as "abc".

Or perhaps we can find and set some rules that would allow new keywords and operators to be introduced without breaking serializations that weren't aware of them. The NextREXX language does this.

Provide single line and multi-line comments. Duh.

Examples

Here are some examples of using some of these changes, based on the following JSON object that I found on the web somewhere. To be fair, since these examples are supposed to show readability enhancements, I did a reformatting in TextMate. Here's the original, but reformatted, legal JSON.

{
    "members": [
        {
            "href": "34KJDCSKJN2HHF0DW20394",
            "etag": "0hf0239hf2hf9fds09sadfo90ua093j",
            "entity": {
                "id": "example.org:34KJDCSKJN2HHF0DW20394",
                "name": {
                    "unstructured": "Jane Doe"
                },
                "gender": {
                    "displayvalue": "女性",
                    "key":          "FEMALE"
                }
            }
        },
        {
            "href": "aaaaaaaaaaa11111",
            "etag": "alsjdfieflsajfajsfjadsljfalksjd",
            "entity": {
                "id": "example.org:aaaaaaaaaaa11111",
                "name": {
                    "unstructured": "Joe Gregorio"
                },
                "gender": {
                    "displayvalue": "Male",
                    "key":          "MALE"
                }
            }
        }
    ],
    "next": null
}

Let's remove the comma's. Comma removal doesn't help much with the readability, but it's much easier to not have to add the commons when you're writing JSON literals by hand.

{
    "members": [
        {
            "href": "34KJDCSKJN2HHF0DW20394"
            "etag": "0hf0239hf2hf9fds09sadfo90ua093j"
            "entity": {
                "id": "example.org:34KJDCSKJN2HHF0DW20394"
                "name": {
                    "unstructured": "Jane Doe"
                }
                "gender": {
                    "displayvalue": "女性"
                    "key":          "FEMALE"
                }
            }
        }
        {
            "href": "aaaaaaaaaaa11111"
            "etag": "alsjdfieflsajfajsfjadsljfalksjd"
            "entity": {
                "id": "example.org:aaaaaaaaaaa11111"
                "name": {
                    "unstructured": "Joe Gregorio"
                }
                "gender": {
                    "displayvalue": "Male"
                    "key":          "MALE"
                }
            }
        }
    ]
    "next": null
}

Now remove the quotes around property keys. That's really nice, but for compatibility with potential new keywords, it probably is best to not use 'bare strings'.

{
    members: [
        {
            href: "34KJDCSKJN2HHF0DW20394"
            etag: "0hf0239hf2hf9fds09sadfo90ua093j"
            entity: {
                id: "example.org:34KJDCSKJN2HHF0DW20394"
                name: {
                    unstructured: "Jane Doe"
                }
                gender: {
                    displayvalue: "女性"
                    key:          "FEMALE"
                }
            }
        }
        {
            href: "aaaaaaaaaaa11111"
            etag: "alsjdfieflsajfajsfjadsljfalksjd"
            entity: {
                id: "example.org:aaaaaaaaaaa11111"
                name: {
                    unstructured: "Joe Gregorio"
                }
                gender: {
                    displayvalue: "Male"
                    key:          "MALE"
                }
            }
        }
    ]
    next: null
}

Now try prefixing property keys with "#" using a symbol-like construct, and not using ":" to separate key value pairs, to make up for having to put the quote in. Add some comments.

{
    // the list of entries in the list
    #members [
        // Jane Doe's entry
        {
            #href "34KJDCSKJN2HHF0DW20394"
            #etag "0hf0239hf2hf9fds09sadfo90ua093j"
            #entity {
                #id "example.org:34KJDCSKJN2HHF0DW20394"
                #name {
                    #unstructured "Jane Doe"
                }
                #gender {
                    // apparently this data is multi-byte encoded
                    #displayvalue "女性"
                    #key          "FEMALE"
                }
            }
        }
        // Joe Gregorio's entry
        {
            #href "aaaaaaaaaaa11111"
            #etag "alsjdfieflsajfajsfjadsljfalksjd"
            #entity {
                #id "example.org:aaaaaaaaaaa11111"
                #name {
                    #unstructured "Joe Gregorio"
                }
                #gender {
                    #displayvalue "Male"
                    #key          "MALE"
                }
            }
        }
    ]
    #next null
}

To me, I see some readability enhancement with these changes. I think the big bang for the buck is the writability enhancement.

As I said above, the syntax isn't a really big deal for me. It's only a big deal when I have to read it with my eyes or type it at a keyboard. Which we seem to be doing more of these days. In fact, I had to fix two typos in Joe's original sample. Can you find them?

It's funny that with all the whining I do about unreadable and overly verbose XML, I find it easier to read and write XML than JSON. That might well just be because I'm typically reading and writing XML with syntax coloring viewers and editors, but not doing that so much with JSON.

Wednesday, January 16, 2008

IDL vs. Human Documentation

Ping pong; in reply to Steve's post on the same subject ...

Like I said in my previous post, interface definition languages exist for machines to generate code. They're totally inadequate, though, for instructing developers on how to write code to use a service. The need for human documentation in this context isn't quaint or impractical at all - it's simply reality.

Steve also points out the reams of documentation produced by OMG, and produced about WS-*, over the years, as a proof point of this.

He's right. Programmers can not survive on IDL alone, or more generally, meta-data. Human language is still often required to express subtleties or non-intuitive aspects of programming libraries, services, etc., simply because we have no other formal means of doing so. Or you wouldn't want to read it, if we did. Human readable documentation is also key to providing overview, introductory, relationship, etc type of information.

I appreciate having that sort of documentation. Lots of it.

But here's what I see as reality: Flickr Services.

Overlook the fact that parts of the interface aren't terribly RESTy, if you're a REST purist. But go out on a limb for me, and pretend they did the right thing in terms of REST; it's not a big leap, I don't think. Let's ask some questions. Is there some kind of XML schema that describes the input and output documents of these service definitions? Nope; can't find one. What HTTP status codes might get returned? Not documented, though they define their own error codes returned in the HTTP response payload; that commonly seen pattern is something else we need to talk about, BTW. Are ETags in use? Last-Modified checking? Who knows. etc

So, keep in mind that this documentation is all you've got. I'm going to claim it's inadequate.

Now the kicker: this API is still perfectly usable! In fact, I use it every time I write a blog entry, via a GreaseMonkey script to generate my little flickr images with annotations. It's not rocket science! It's HTTP!

While the documentation isn't completely adequate, it's perfectly acceptable, because I'm only using a small number of the APIs. The fact that's it's inadequate is containable. As Steve has previously mentioned, it's easy to do REPL-ish experiments with REST APIs. Heck, Flickr includes an API "Explorer" on their site to let you play, live. Nice!

But here is my fear. It's early days for REST. I want to believe that we'll see lots of people using REST over the coming decade to provide 'API's to their services. Where the promise of DCE, CORBA, WS-* got mired down in their complexities, REST is simple enough to actually be practical.

And that's my tension. It's simple/easy (you pick your semantic) to do simple stuff. I'd like to make sure that it's possible to do hard stuff. What happens when I need to deal with MORE that just one interface, and those interfaces are BIGGER than Flickr's? I feel like we're going to get lost in a sea of differently inadequate documentation. Using meta-data to help describe at least the nuts+bolts layer, is something that can help. The trick is to make sure it doesn't get too much in the way, and that you can keep it in sync with your code. My belief is that both are entirely possible. BTW, the link in the sentence above is a couple steps back in this conversation thread, if you've lost your place.

Let me finish this with a challenge. We all agree that documentation is good. Do you think there's some kind of a standard 'template' that we might agree on, that could provide all the practical, required information regarding usage of REST services? All text, prose, for now; just identify the information actually required. That seems like a worth-while goal, especially to try to educate people on the "way of REST" - and I'm talking about RESTy service providers here. Lots of people don't get REST. Let's teach them, by example, and by the way, I'm sure I still have a lot to learn myself.

You never know; I may see that prose and say "My gods. I've been such a dumb-ass! I can see that there's no way to formalize that to some machine readable format!". But I'll bet you a beer, that I won't say that. Take that prose, create an XHTML template that you could style, morph it into a MicroFormat (might not be so micro), create a JSON mapping when JSON takes over the universe this year, etc. Now I got my meta-data and I'll stop yammering on about it (not likely). But baby steps for now. I'd be happy with prose for now. Let's go top-down.

One more final note :-) I wrote this post last night, before Tim Bray posted about 'therestfulway.com'. Synchronicity? Wouldn't it be great to have a whole site full of patterns, best practices, examples, etc on REST? I've posed this question before, and gotten some positive responses. But some action is obviously required. I can't do it alone, but I'd be happy to help. I'm willing to sign a waiver indicating I won't talk about meta-data for the first six months. Who can pass that up?

Friday, January 11, 2008

why couchdb

Someone asked me today what I thought value proposition was behind CouchDb. Here goes.

  • It's a non-relational database. I've ranted on this before. Not like relational databases don't have have their place, but the fact of the matter is that so many people are familiar with them today, that they've become the first tool many people look at when trying to solve a persistance problem. I'm always happy to see conceptually simpler database tools get some attention, because not every problem needs a relational database.

  • It's a schema-free database. Now, you've heard me rant about how important I think schema is for things like JSON and REST, so now you're no doubt confused about why I would claim a schema-challenged database is good. The problem with schema in most relational databases is that it's terribly brittle. It's painful to deal with. Not terribly portable. Schema has a place in the world, but at the lowest level of the database, it seems like it just gets in the way. At the very least, I think it'll be interesting to see how much trouble the lack of schema for this semi-structured database causes.

  • It's a web server. W00t! My database driver is my HTTP client. Almost every language has a decent HTTP client library baked in. Almost.

  • Erlang with it actor-ish programming model. Getting some traction right on the eve of our multi-core future. The nice thing about this particular usage of Erlang is that I think it's in the exactly perfect spot. The engine. Which you never see. You'll see other languages (JavaScript, et al), but in general the Erlang is all under the covers.

  • JSON. I need not say more.

  • A 'stored procedure'-ish language, that's actually a real language. A simple and powerful language. JavaScript. And other languages, if you wish.

  • Designed for distributed usage.

  • Seems like classic disruptive innovation.

  • It's a web server and a database. And to me, this is the most interesting point. Just as we've seen client programs start to embed web browsing technology (like iTunes), there's really no reason why server programs like a database shouldn't be able to embed a web server. It's obviously a convenience factor (single install). It also has some potential nice performance aspects as the path-length between the server and the database is greatly, greatly shortened.

Let's noodle on that last point a bit more; it's a server AND a database. Now, whenever I see "server", I immediately ask the question - can I write a web app for that thing? Or is it just serving read-only documents up? Check the REST APIs. Read/write web, folks. But, there are some caveats. JSON objects are trivial to store in the database behind a simple URI, but anything else (something that's not JSON), needs to be stored as an 'attachment' for some JSON object. The raw data of the attachment is available at a particular fugly-ish URI, of the form:

/database/attachment_doc?attachment=foo.txt 

Fugly, but possible.

What does all this mean? Well, it means you could, say, serve up HTML out of your CouchDb database, that could be rendered in a browser. Which might include some JavaScript (inline, or referenced as another 'attachment'), which could then read/write objects in the database. A self-contained app inside an app server. Oh yeah, the data for the app is stored there to.

That's the theory anyway. I intend to practice this weekend.

BTW, for any Mac folk that want to install CouchDb to play, I recommend installing it from MacPorts via:

sudo port install icu erlang couchdb
sudo cp /opt/local/Library/LaunchDaemons/org.couchdb.couchdb.plist  /Library/LaunchDaemons/
sudo launchctl load -w /Library/LaunchDaemons/org.couchdb.couchdb.plist 

The first command installs the icu package, then erlang, then couchdb. The last two commands launch CouchDb, and arrange to have it started at every boot. From memory, I think I had to do these after the port install, but I could be wrong; perhaps the port install did them for you. In any case, there's no harm in running those commands again.

As a quick check to make sure CouchDb is running, either open your browser on the following url: http://localhost:5984/_utils/index.html, or run the command, which should provide the short JSON object below:

$ curl localhost:5984
{"couchdb": "Welcome", "version": "0.7.2"}

Thursday, January 03, 2008

hot data

Damien Katz, of CouchDB fame, announced today he's accepted a job with IBM, to work full time on CouchDB. For a JSON-lovin', relational-hatin' person like myself, you can imagine my reaction. "Yee Haw!" indeed!!

But when I thought about it today, I realized there's plenty of other non-relational, and sometimes web-related database stuff going on in IBM:

  • Project Zero's ZRM (Zero Resource Model) provides a REST-friendly DB abstraction layer for use in applications built with Project Zero. Though it's built for relational databases, it's one of those new-fangled ORMish things which gives you an API which is bit more 'functional'.

  • Brandon Smith (who's developing ZRM) pointed me at the Impliance research project a month or so ago.

  • Following up on the Impliance work ended up leading me to jaql.org; notice some of the same names from the Impliance paper. And the JSON; the lovely, lovely, JSON. My heart's a-twitter! Not sure if I can take the new query language; we at least need a structured query facility as well; ie, I'll give you a query expressed as a JSON structure. Early days ...

  • Can't pass up a chance to mention Jazz. The thing that attracted me to Jazz when I went to work on it many moons ago, wasn't the actual 'vertical' market they've carved out for themselves (collaborative development). It was the server. Basically, it's a versionable object database with an HTTP (but not terribly RESTy, yet) front-end. I like to think that it can easily have a life above and beyond mere "collaborative development" tools, if desired. Bill Higgins made a comment on a blog (from, of all people, Brandon Smith :-) , spilling some of those beans.

That's just the stuff I know about. And note only two of those items are actually being developed in the Information Management (IM) tower in IBM (home of DB2); WebSphere is the home of Project Zero, and Rational is the home of Jazz.

So here's a question - why do the database guys get to do all the wild and wacky stuff? Where's the wild and wacky stuff in web-serving frameworks, web-client frameworks, development tools, etc. I'll give programming languages themselves a break here, what with recent interest in Erlang, Scala, and odd-balls like Processing, Factor (ran into both of those again, over the holidays), etc. Comparatively speaking, I feel like we have a wide variety of choices of DBs, ORMs, and languages to use these days, but the other tools in the programmer's toolbox haven't evolved as quickly. AppJet, though very minimalistic, is one of the more interesting "development environments" that I've seen in a while. It's really not hard imagining what that could be on steroids. I'll just let you imagine what my Smalltalk-related comment might be here ...

Next question: when are the Information Management guys going to start working on web servers and development tooling?

BTW, I think I'll pass on Factor; I wrote PostScript programs, back in the day. Been there, done that, got the T-shirt. Though I am tempted ...