Links

pmuellr is Patrick Mueller

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

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

Monday, April 24, 2006

The problems with JSON

My love affair with JSON is over. I'm going to outline the problems I've got with it, and then also reiterate some of the things I do still like about it.

  • Licensing
    I will admit this point is rather weak. It's based on the license that Douglas Crockford ("father of JSON?") uses for the JSON code he makes available. It's an MIT-ish license, I suppose, but has an odd additional stipulation in it. The Software shall be used for Good, not Evil. There is some discussion of the license here (scroll about half way down the page). My experience dealing with IBM lawyers for the past 15 years, is that this is exactly the thing that drives them nuts. I'm with Mark on this (read the blog post), and I'll admit that when I see stuff like this, I just immediately assume a battle ahead with lawyers trying to get permission to reship it. I'm getting too old for that shit.

    So, like I said, this is a weak point, since as Crockford himself says, JSON parsers and generators are easy to write. It's just ... a shame.

  • Lack of complex data types
    While JSON has great support for basic data types, unlike XML, it has no built-in support for complex data types. In JSON, instead of objects, you really have hash tables, where the properties/attributes of the 'object' are string keys, and the values are any of the valid JSON objects, including an 'object' (hash table).

    Unfortunately, for my purposes, this isn't good enough. The objects I'm dealing with right now at work are actually classically designed object-oriented instances of classes. That can be subclassed. JSON has no built-in way to indicate the actual type of the object, just the properties on the object. Every object is 'anonymous'. Or again, just a hash table.

    You can kind of fix this by including a type name as a property of the object, but this is a bit of a hack. And it's non-standard. And if you actually looked at some of the stuff we were JSON-ing, you'd realize that you'd really like to have something like XML namespaces to help cut down on string duplication, if your type names are long (ie, they include an XML namespace, package, module name). That's hard to fix.

    XML on the other hand, does a pretty good job of this. Type names can end up becoming actual element names, using namespaces to end up with a short form of the longer, universally unique class name. With the long name declared up front, kinda like a Java import statement. Nice.

  • Executable
    The end of the day, this is really the biggest problem. This is executable code. How long have we known that you really shouldn't be sending executable code over the network; you gotta have a lot of trust in your partner if you're going to execute code they give you. With JSON in JavaScript, you really should forgoe using eval() or any other function using eval(), unless you are really sure you can trust your partner. And I would claim that's hard. Ask MySpace.

    Instead of using eval(), you should really use some code which actually parses up the JSON text. Like every other language does. But, you gotta wonder, what's faster, a JSON parser written in JavaScript, or the existing DOM engines to parse XML? My bet's on the DOM engines. Complete guess. But even if for some reason a JSON parser was faster than XML, it still means you have to carry around this wad of JS code to parse JSON for your pages. Baggage.

So, what do I still like about it?

  • Support for basic data types
    I still really love the self-descriptive typing for basic data types in JSON. Compared to XML, where just because you see a text node or attribute value of "true", you really have no idea if that this is a string, or a boolean, or maybe even some specialized marshalling of another type. No problem with JSON; "true", the string, is rendered in a completely different way than "true", the boolean. This is a fantastic property of JSON; hopefully future structured serialization languages can likewise incorporate this.

  • Easy for JavaScript users
    Really easy. My friends using dojo said that handling dojo from REST calls is quite simple. Anything to make life a little easier in that world is nice. If nothing else, using JSON for prototyping is probably a great idea.

Thursday, December 21, 2006

data not markup

Mike Champion's blog entry, XML 2006 Observations, ends with some thoughts/questions on JSON. Here are my answers.

'Urban Markup' by Gord Fynes

Will we see JSON substituting for XML in SOAP messages, RSS feeds, etc.?

Kind of, and no. I don't think we'll see a JSON flavored SOAP, but there's already such things as JSON-RPC, so for those SOAP usages that are RPC in nature, the answer is yes. For those SOAP usages that are document-oriented in nature, there are such things as RESTful JSON.

But it's a stretch to imagine taking on the work to enable JSON-flavored [XML-thing]. For those things that XML works well for, follow the old adage: if it ain't broke, don't fix it.

Asking about feeds is telling also. Markup (XML) is fantastic for augmenting text. I have a bias; I've been doing text markup for 20 years (nroff, tex, GML, BookMaster, HTML, XML). Nothing better than to be able to in-line visual or semantic augmentation with your text, because it's sooo inline. Readable. Imagining writing a document as a big JSON object, with text strings littered with objects indicating augmentation is ... horrifying.

But that's just the text. Feeds don't neccessarily carry just text (well, at least in the future they won't). If the feed content is data, then sure, why not JSON. And the feed meta-data itself probably also better lends itself to a data layout than XML.

So, my take is: XML for text, JSON for data. Until the day the computers take over the world, we'll always be needing text, somewhere, and XML is the answer. But I'd rather be specifying my data in a data definition language like JSON, compared to doing it in XML as wonky marked up narratives.

Will people store JSON persistently?

Yes. If folks are storing XML persistently, and that XML is used to describe data in some way, I will argue that you'll save space by converting to JSON. Unless you perhaps take into consideration the fantastic compression you can get on XML, because of the extreme verbosity (what ever happened to anonymous end tags?).

That will require JSON-flavored APIs, schema/"data contract" languages, query/transformation languages, apps, etc.

Sure. Guess what? A schema for JSON in JSON is pretty simple. And ... readable. Query/transformation languages? Yup. But they won't be languages built on JSON. They will be the languages we use to do our jobs; JavaScript, Java, PHP, Python, Ruby, C, C#, etc. Because JSON, like the programming languages we use, has built-in constructs for numbers, strings, arrays, hash tables, etc. With XML, you need to apply some other structure on top of the XML itself to get this level of semantic. And don't get me started on query/transformation languages. XSLT is ... hard. James Governor asked on the #redmonk irc channel the other day if anyone had thoughts on XQuery, and my response was: tried to read the docs once; much like C++, I figured it was too complex, so I decided to ignore it, and hope it will just go away.

I'm sure that lots of us at in the MS Data Programmability team are pondering what we should think and do about JSON.

Excellent. Keep us informed.


Photo 'Urban Markup' with a nice CC license, by Gord Fynes. Found using the Flickr's Create Commons Search.


Update: 2006/12/22: fixed a typo

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.

Tuesday, March 07, 2006

JSON as a data binding

In my never ending question for the be-all, end-all cross-language data binding story, I've been thinking lately about JSON.

First, consider that SDO is an important part of IBM's SOA story; it's a or the story for sending data via SCA. Let's compare SDO and JSON, in terms of the Java interfaces.

SDO's DataObject interface looks something like this (see page 23 in the referenced PDF file). Actually, this is just a bit of it.

public interface DataObject extends Serializable { ... boolean getBoolean(String path); byte getByte(String path); char getChar(String path); double getDouble(String path); float getFloat(String path); int getInt(String path); ... }

Now let's compare to JSON's Java interface, and again, just a bit of it.

class JSONObject { java.lang.Object get(java.lang.String key) boolean getBoolean(java.lang.String key) double getDouble(java.lang.String key) int getInt(java.lang.String key) JSONArray getJSONArray(java.lang.String key) JSONObject getJSONObject(java.lang.String key) long getLong(java.lang.String key) java.lang.String getString(java.lang.String key) ... }

Look familiar? Now, sure, SDO has a lot more 'stuff' in it than JSONObject, like change tracking, but, really, I'm not interested in that stuff anyway. In any case, if SDO is good, and JSON smells like SDO, I guess it must be kinda good also.

Next, if I had to implement just one type of 'object' serialization in a server, obvious choices are XML and JSON. JSON is trivial for JavaScript code to eat, and any other language will require some library, but there are plenty available (scroll to the bottom), for free, as long as you don't use them for evil. With XML, everyone needs a library. Not so much of a problem that you need some extra library, because everyone has XML parsers in their language environment, but it's more code you have to write to get the data. If AJAXy web apps are a core piece of what you're doing, JSON may be what you want to make your client-side app code to be a little snappier.

Lastly, one of the things I always think about with data-to-xml bindings is whether fields/properties/etc should be rendered as attributes or child elements. Sometimes, you have no choice; if the field is 'complex', you will likely have to render as a child element. With a string-valued field, you got a tough choice. If the value is small, it feels better usually as an attribute; if it's longer, it feels better as a subelement.

None of this is an issue with JSON. Blissfully choice-challenged.

Sure, there's gotchas with JSON, like the fact that it really just models structs, lists, primitive types. Specifically, it has no way of handling classes. This is an issue when you want to serialize some data in JavaScript, and send it to a typed language, and would like to have that data turned into typed objects; instead of something like SDO's DataObject or JSON's JSONObject. No one wants to deal with that crap. The obvious sort of thing to do is have a magic field in your struct, named maybe "__type__" or something, that provided an indication of the class. This would of course be a pain to have to add manually in the JavaScript object, but if you could provide thin wrappers in JavaScript to poof objects like this up ....

So, I'm thinking it would be interesting to see what a JSON data binding story would look like. On the Java end, I'd want to deal with EMF objects, so the idea would be to serialize EMF objects using it's metadata, and when JSON is deserialized, somehow it gets turned into EMF objects. On the JavaScript end, code that generates these objects would be done with some kind of thin wrapper to add the magic field.

Wednesday, April 11, 2007

json array exploit

Unless you've been living in a cave for the last week or so, you are familiar with JSON exploit as publicized by Fortify Software. I believe this is the same exploit I first read about on Robert Yates' blog. Original reference was from Joe Walker.

I'm not going to claim to be an expert on this particular exploit, but if I understand the situation correctly, I have a few issues with the current concerns.

  1. It's clearly not just JSON data which is suspect here. Anything which appears to be a valid (or maybe even somewhat valid) chunk of JavaScript, which someone could access via <script src=> is suspect. How many resources like this might be available at your site? How 'valid' (in terms of valid JavaScript) does it have to be? Only folks who are intimately familiar with the code of the JavaScript interpreters we use, can say for sure. Let's also not forget E4X; could your XML data be suspect?

  2. This appears to be a problem today just for Mozilla / Firefox. And I believe the reason is the advanced functionality it provides in JavaScript with coolio getter/setter capabilities. (BTW, ActionScript 3 also supports getter/setter capabilities). Is this actually a bug? Doesn't seem like it. Is there some chance this functionality could be locked down during script/src inclusion? Seems unlikely (slippery slope; what else would you lock down?). Could the enhanced functionality be turned off for user-land scripts? Probably; I don't suspect too many people are actually making use of the functionality. There's an open bug @ Mozilla on the issue that has additional thoughts.

  3. I'm clearly showing my n00biness here, but why aren't even simpler exploits possible, on all the browsers? Before doing a script/src, redefine a well-known object/function with one that does some hijacking? The security model for JavaScript is complex; so complex; too complex.

  4. Ted Husted pointed out that one way to fix this problem is to enclose your JSON in comment characters, and then strip the comments before parsing the JSON. That's great, unless I want to actually include comments inside my JSON. And assuming that JavaScript comments can't be 'recursive' (not specified at moz's js doc). Why would I want comments in my JSON? Why not? If you can have them in XML, I'm not sure why we won't someday want them in JSON. Note that I don't consider RFC 4627 to be the final statement on JSON syntax.

  5. The fact that JSON is also a syntactically valid chunk of JavaScript is smelling worse and worse all the time. I can't imagine a situation where I'd eval() JSON data in a production app; it's just so much safer to parse the data yourself. So, why don't we use this opportunity to come up with YASDN (yet another simple data notation)? JSON is great because it's readable, but I've already pointed out how we could make it even MORE readable.

  6. Isn't it about time we got a little better modularity available in JavaScript, beyond the script/src story. Which is more or less the same thing as building a C program in one big monolithic file that pulls in functionality with #include. So 1970's ...

Tuesday, March 06, 2007

JSON array vulnerability

Robert Yates points to an odd vulernability of JSON, in at least Firefox, having to do with an overwritten, user-supplied Array constructor. Sigh.

Some thoughts:

  • I don't like JSON because it happens to be directly eval()-able by JavaScript (and maybe Python). I like it because it's fairly consise, textual, and contains the bare minimum set of primitive and composite data structures from which all manner of useful data structures can be built. Having it be eval()-able was just a nice-to-have. I have recommended to people they should never use eval() though. There are JSON decoders available for JSON. Do you really want to be subject to someone injecting a function invocation into your datastream?
  • Although I like JSON because it's consise, it can actually be made more consise, although rendering not legal JavaScript anymore. Perhaps that would be a good thing. :-) For instance, the commas separating array elements and key/value pairs seem to be completely extraneous. Likewise, quoting keys, for keys that contain non-special characters, is overkill. Fixing both of these would make JSON a lot more readable:

    Legal JSON:

    { "Image": { "Width":800, "Height":600, "Title":"View from 15th Floor", "Thumbnail": { "Url":"http://scd.mm-b1.yimg.com/image/481989943", "Height": 125, "Width": "100" }, "IDs":[ 116, 943, 234, 38793 ] } }

    Consise-r JSON:

    { Image: { Width:800 Height:600 Title:"View from 15th Floor" Thumbnail: { Url:"http://scd.mm-b1.yimg.com/image/481989943" Height: 125 Width: "100" } IDs:[ 116 943 234 38793 ] } }
  • Joe Walker notes the Array constructor vulnerability only occurs for JSON which has a top level array, and not for arrays included in a top level object, presumably because the interpreter balks at the object notation, considering it a code block instead. A code block with a quoted string followed by a colon in it, which is not legal JavaScript for a code block. However, I was able to get a JSON object, without quoted keys, to kick off the Array constructor vulnerability. Now I see why quoted keys are important. Presumably the non-quoted key looked like a code label. Did you know JavaScript has labels?
  • Uncle Ben says: "With great power ....". Sure, it's really nice to be able to add methods to built-in classes, override existing methods / constructors (classes), but ... there's a cost. I'm not sure the cost is worth it. Perhaps it's time we started thinking about moving some of the wild west capabilities out of JavaScript, or at least out of user-land JavaScript. Steve Northover had a great presentation years ago on the dangers of class extension in Smalltalk; for you youngsters, that would be the ability to add methods, etc to existing classes. One of the few things I dislike about Ruby. I should see if he still has that presentation around somewhere.
  • Perhaps it's time to take another look at YAML.
  • Flex is looking better every day.

As a complete aside, Robert added the info about the vulnerability in an update to a previous blog entry. That update never showed up as an update in Google Reader. Maybe because it's RSS, and not Atom? Bummer. Somehow Robert Sayre noticed the update, and I noticed Robert's entry.

Wednesday, April 11, 2007

json schema

James Clark has a great post on XML and JSON. But I have one point to pick at.

"JSON's primitive datatype support is weak."

First, the number issue. If you assume JSON datatypes map into JavaScript ones, I believe the JavaScript number type does in fact have a very specific representation. I believe, a 64 bit floating point number. Even for integers. I'd love to point to a reference for this, but I don't have one handy, and the one at mozdev is insufficient.

Note that outside of JavaScript, for languages that treat integers and floating point as separate types, a parser can obviously distinguish between integers and floating points and 'do the right thing' in terms of mapping the JSON value into the appropriate type.

Next, "the set of primitive datatypes is not extensible". But this is true for XML itself. Until you mix in XML schema. It's schema that allows you to interpret a string in XML as some sort of other data type. JSON has no standard schema. Yet. It's easy to imagine though. Defined in JSON, of course.

Sunday, September 24, 2006

Just Say No to XML - more often

In Just Say No to XML, Allen Holub writes "XML is perhaps the worst programming language ever conceived." What's he's talking about here are all the tools which use XML as a programming language. My only direct experience with this is with Ant. Within Eclipse. Because it's the easiest easy way to do 'scripting' with Eclipse. You know it's there, it's shipped with the base Eclipse. And I'll just say that, in general, I'm in agreement with Allen; I've written a shed-load of Ant scripts over the years, and I'd rather not have to be dealing with XML here.

Titanic cake

But I'd like to go even further! Allen follows up his 'worst' sentence (quoted above), with this: "I'm not talking about XML as a data-description language, which was its original design." If we're going to start thinking about not using XML for programming languages, let's also consider not using it for data-description as well. Why? Because XML isn't designed for data. XML is designed for documents.

And there's the problem. Documents. Programmers know how to design data. They don't know how to design documents. I think this is probably one of the biggest problems with the ws-* flavored web services; you need to design documents. To design an XML document, you need to know XML Schema. I know exactly one human who claims to be able to write XML schema off the top of their head, with no multi-hundred page reference document open. That's not good.

Sure, there are ways around having to learn schema, kind of. There's RELAX NG. But it's not widely supported in a least the places I program, and look at that last updated date on the page I just linked to. Kinda scary.

There's design tools, like UML-based stuff, but that adds layers of cake; now I have additional tooling I have to learn, there's code-gen in play so I have to watch for getting things synchronized, etc.

But let's pretend for a minute like there was an easy and standard way to design documents, and that programmers actually knew how to design documents.

Now you got the problem that there isn't really a simple way to go from documents to data. You might want to design your documents to be 'easy to parse' (eg self-descriptive), but that's likely going to violate some of the things you want in your document design, like readability. You'll probably end up using some coolio XML-to-data framework in your own code. However, some folks aren't going to have access to whatever coolio document-parsing-to-data system you're using, since most of these frameworks are single language stories, and your XML may be read by nearly any programming language known to man. In the end, some folks are going to have to use a DOM-based parser, or *gulp* SAX-based parser, to read your data. And that's simply no fun.

What's the alternative? Whatever is appropriate.

Java .properties files / windows .ini files are a really simple format for storing really simple data; too simple in most cases, but not all. Use these wherever you can get away with them.

YAML is kinda like .properties files on steroids.

JSON is the latest contender here, and is an appropriate format to use if you're expecting some JavaScript code to be handling your data, since you can use eval() to deserialize a JSON string into objects. IFF you can trust the source that gave you the JSON, anyway (that's a pretty big If, BTW; there are JSON parsers in JavaScript you can use if you can't trust your source).

Upon first really looking into JSON, I was struck by the similiarity in function that SDO provides. SDO provides a lot more than what what JSON provides, but at it's core, there's some definite similiarities. That seems good.

The point is, XML is unavoidable to programmers these days. It's everywhere. Just don't assume it's the best answer to your problem, just because everyone else is using it. There might be a better answer.


Photo "Titanic cake", with a nice CC license, by psb_minimal. Found using the Create Commons Search Site.

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"}

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:

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.

Friday, October 12, 2007

on links

When people think about links, with regard to tying together information on the web, the usual thoughts are of URLs. Either absolute URLs, or a URL relative to some base (either implicitly the URL of the resource that contains the link, or explicitly via some kind of xml:base-like annotation).

But I wrestle with this.

Here's one issue. Let's say I have multiple representations of my resources available; today you see this typically as services exposing data as either JSON or XML. If that representation includes a link to other data that can be exposed as either JSON or XML, do you express that link as some kind of "platonic URL"? Or if you are doing content-negotiation via 'file name extension' sort of processing, does your JSON link point to a .json URL, but your XML link point to a .xml URL?

See a discussion in the JSR 311 mailing list for some thoughts on this; I stole the term "platonic URL" from this discussion.

The godfather had something interesting to say in a recent presentation. In "The Rest of REST", on slide 22, Roy Fielding writes:

Hypertext does not need to be HTML on a browser
- machines can follow links when they understand the data format and relationship types

Where's the URL? Perhaps tying links to URLs is a constraint we can relax. Consider, as a complementary alternative, that just a piece of data could be considered a link.

Here's an example: let's say I have a banking system with a resource representing a person, that has a set of accounts associated with it. I might typically represent the location of the account resources as a URL. But if I happen to know, a priori, the layout of the URLs, I could just provide an account number (assuming that's the key). With the account number, and knowledge of how to construct a URL to an account given that information (and perhaps MORE information), the URL to the account can easily be constructed.

The up-side is that the server doesn't have to calculate the URL, if all they have is the account number. They just provide the account number. The notion of content-type-specific URLs goes away; there is only the account number. The resources on the server can be a bit more independent of themselves; they don't have to know where the resource actually resides, just to generate the URL.

Code-wise, on the server, this is nice. There's always some kind of translation step on the server that's pulling your URLs apart, figuring out what kind of resource you're going after, and then invoking some code to process the request. "Routing". For that code to also know how to generate URLs going back to other resources, means the code needs the reverse information.

The down-side, of course, is that you can't use a dumb client anymore; your client now needs to know things like how to get to an account given just an account number.

And just generally, why put more work on the client, when you can do it on the server? Well, server performance is something we're always trying to optimize - why NOT foist the work back to the client?

But let's also keep in mind that the Web 2.0 apps we know and love today aren't dumb clients. There's user-land code running there in your browser. Typically provided by the same server that's providing your resources in the first place. ie, JavaScript.

I realize that's a bad example for me to use; me being the guy who thinks browsers are a relatively terrible application client, but what the heck; that's the way things are today.

For folks who just want the data, and not the client code, because they have their own client code, well, they'll need some kind of description of how everything's laid out; the data within a resource representation, and the locations of the resources themselves. But the server already knows all that information, and could easily provide it in one of several formats (human- and machine-readable).

As an proof point of all of this, consider Google Maps. Think about how the map tiles are being downloaded, and how they might be being referenced as "links". Do you think that when Google Maps first displays a page, all the map tiles for that first map view are sent down as URLs? Think about what happens when you scroll the map area, and new tiles need to be downloaded. Does the client send a request to the server asking for the URLs for the new tiles? Or maybe those URLs were even sent down as part of the original request.

All rhetorical questions, for me anyway. I took a quick look at the JavaScript for Google Maps in FireBug, and realized I've already debugged enough obfuscated code for a few lifetimes. Probably a TOS violation to do that anyway. Sigh. I'll leave that exercise to younger pups. But ... what would you do?

For Google maps, it's easy to imagine programmatically generating the list of tiles based on location, map zoom level, and map window size. Assuming the tiles are all accessible via URLs that include location and zoom level somewhere in the URL. In that case, the client code for calculating the URLS of the tiles needed is just a math problem. Why make it more complex than that?

I think there are problem domains where dealing with 'links' as just data, instead of explicit URLs make sense, as outlined with Google Maps. Remember what Roy wrote in his presentation: "machines can follow links when they understand the data format and relationship types". Of course, there's plenty of good reason to use continue to use URLs for links as well, especially with dumb-ish clients.

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.

Tuesday, May 15, 2007

modelled serialization

Too many times I've seen programmers writing their web services, where they are generating the web service output 'by hand'. Worse, incoming structured input to the services (XML or JavaScript), parsed by hand into objects. Maybe not parsed, but DOMs and JSON structures walked. Manually. Egads! Folks, we're using computers! Let the computer do some work fer ya!

In my previous project, we used Eclipse's EMF to model the data we were sending and receiving via RESTy, POXy web services. For an example of what I'm referring to as 'modelling', see this EMF overview and scroll down to "Annotated Java". For us, to model our data, meant adding EMF comments to our code. And then running some code to generate the EMF goop. What they goop ended up giving you was a runtime version of this model you could introspect on. Basically just like Java introspection and reflection calls, to examine the shape of classes, and the state of objects, dynamically. Only with richer semantics. And frankly, just easier, if I remember correctly.

Anyhoo, for the web services were we writing, we constrained the data being passed over the wire to being modelled classes. Want to send some data from the server to the client? Describe it with a modelled class. Because the structure of these modelled classes was available at runtime, it was (relatively) easy to write code that could walk over the classes and generate a serialized version of the object (XML or JSON). Likewise, we could take an XML or JSON stream and turn it into an instance of a modelled class fairly easily. Generically. For all our modelled classes. With one piece of code.

Automagic serialization.

One simplification that helped was that we greatly constrained the types of 'features' (what EMF non-users would call attributes or properties) of a class; it turned out to be basically what's allowed in JSON objects: strings, numbers, booleans, arrays, and (recursively) objects. We had a few other primitive types, like dates and uuid, but amazingly, were we able to build a large complex system from a pretty barebones set of primitives and composites. Less is more.

For folks familiar with WS-*, none of this should come as a huge suprise. There are basically two approaches to defining your web service data: define it in XML schema, and have tooling generate code for you. Or define it in code, and have tooling generate schema for you. In both cases, serialization code will be generated for you. Neither of these resulted in a pleasing story to me. Defining documents in schema is not simple, certainly harder than defining Java classes. And the code generated from tooling to handle schema tends to be ... not pretty. On the other hand, when starting with code, your documents will be ugly - some folks don't care about that, but I do. The document is your contract. Why do you want your contract to be ugly?

Model driven serialization can be a nice alternative to these two approaches, assuming you're talking about building RESTy or POXy web services. Because it's relatively simple to create a serializer that feels right for you. And you know your data better than anyone; make your data models as simple or complex as you actually need. If you're using Java, and have complex needs, consider EMF, because it can probably do what you need, or at least provide a solid base for what you need.

Besides serialization, data modelling has other uses:

  • Generating human-readable documentation of your web service data. You were planning on documenting it, right? And what, you were going to do it by hand?

  • Generating machine-readable documentation of your web service data; ie, XML schema. I know you weren't going to write that by hand. Tell me you weren't going to write that by hand. Actually, admit it, you probably weren't going to generate XML schema at all.

  • Generating editors, like EMF does. Only these editors would be generated in that 'junky' HTML/CSS/JavaScript trinity, for your web browser client needs. Who wants to write that goop?

  • Writing wrappers for your web services for other languages. At least this helps with the data marshalling. Again, JavaScript is an obvious target language here.

  • Generating database schema and access code, if you want to go hog wild.

 

If it's not obvious, I'm sold on this modelling stuff. At least lightweight versions thereof.

So I happened to be having a discussion with a colleague the other day about using software modelling to make life easier for people who need to serialize objects over the web. I don't think I was able to get my message across as well as I wanted, and we didn't have much time to chat anyway, so I thought I'd whip up a little sample. Code talks.

This sample is called ToyModSer - Toy Modelled Serializer. It's a toy because it only does a small amount of what you'd really want it to be able to do; but there's enough there to be able to see the value in the concept, and how light-weight you can go. I hope.

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 ...

Thursday, November 30, 2006

choose JSON

'stop' by MarkNick

In Should You Choose RELAX or JSON Now?, Robert Sayre claims "100% of the data-oriented use cases can be served better and faster by JSON. No 80/20 truism."

+1

I've had a love / hate relationship with JSON over the last year, but I'm currently very positive on it. It has all the basic data types you need, and no more: numbers, strings, boolean, hash tables, arrays, and null. And it's not a document.


Photo 'stop', with a nice CC license, by MarkNick. Found using the Create Commons Search Site.

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.