Expressively Selecting a Strategy using ES2016

I find myself needing to select a strategy based on some arbitrary function of input often enough to look for a neat solution. Maybe it’s the output of a remote service that I want to decorate with a summary, or records from a document store that I want to normalize somehow. ES2015’s destructuring, Array find method and arrow functions provide the most flexible, concise and expressive way of choosing the appropriate strategy from a list on a first-match basis that I’ve come up with so far. I’ll be using Babel to transpile Node 4 up to ES2015 spec.

For example, say our spec says that given an input y:
* if it’s a string, uppercase it
* else if it’s an array, return a string describing the length
* else if it’s an object, return a string describing the number of keys
* else return “Nothing Matched” and the default toString() output

We’ll define an array of pairs of functions, where the first element in each pair will be treated like a predicate, and the second will be invoked if the first ‘matches’. Arrow functions make this definition much clearer than the traditional function() {...} syntax.

const renderingStrategies = [
  [x => typeof x === 'string',  x => x.toUpperCase()],
  [x => Array.isArray(x),       x => `Array with ${x.length} elements`],
  [x => typeof x === 'object',  x => `Object with ${Object.keys(x).length} keys`],
  [() => true,                  x => `Nothing matched '${x}'`]
];

That seems fairly expressive to me, mapping pretty directly onto the spec. You could use an array of objects, each with a pair of methods like (match, handle), but that involves quite a bit more boilerplate. Likewise, an if/else-if/else structure could do the job, but it’s more boilerplate and, for me at least, doesn’t imply the intent as clearly.

Now, we need a function that, for an input, selects the first strategy for which the predicate is true. Use array find() to choose the first matching predicate and destructuring to clearly pull out the predicate make this a one-liner.

const render = x => renderingStrategies.find(([matches]) => matches(x))[1](x);

render('Hello World'); // HELLO WORLD
render([1, 2, 3, 4]);  // Array with 4 elements
render({x: 1, y: 2});  // Object with 2 keys
render(1234);          // Nothing matched '1234'

Performance of this selector and its if/elseif/else version are roughly equivalent, both completing a million selections in around a second on my computer. It’s a shame that the only simple way I can see to pull out the decorator function (without a verbose filter and map) is to extract by index. Let me know if you can see a better way!

If we were to use promises, then we could use destructuring again, and make our function asynchronous. For example:

const render = x => Promise.resolve(renderers.find(([matches]) => matches(x)))
  .then(([,decorate]) => decorate(x));

If you can improve on this, or suggest a better solution, leave me a comment, or get me on Twitter.

Node.js Microservice Optimisations

A few performance, scalability and availability tips for running Node.js microservices.

Unlike monolithic architectures, microservices typically have a relatively small footprint and achieve their goals by collaborating with other microservices over a network. Node.js has strengths that make it an obvious implementation choice, but some of its default behaviour could catch you out.

 

Cache your DNS results

Node does not cache the results of DNS queries. That means that every time your application uses a DNS name, it might be looking up an IP address for that name first.

It might seem odd that Node handles DNS queries like this. The quick version – the system calls that applications can use don’t expose important DNS details, preventing applications from using TTL information to manage caching. If you’re interested, Catchpoint has a nice walkthrough of why DNS works the way that it does and why applications typically work naively with DNS.

Never caching DNS lookups is going to really hurt your application’s performance and scalability. I think the simplest solution from a developer’s perspective is to add your own naive DNS cache. There are even libraries to help, like dnscache. I’d tend to err on the side of short cache expiry, particularly if you don’t own the DNS names your looking up. Even a 60-second cache will have a big impact on a system that’s doing a lot of DNS lookups.

An alternative, if you are running in an environment where you have sufficient control, is to add a caching DNS resolver to your system. This might be a little more complex but a better solution for some scenarios as it should be able to take advantage of the full DNS records, avoiding the hardcoded expiry. Bind, dnsmasq and unbound are solutions in this space and a little Google-fu should find you tutorials and walkthroughs.

Reuse HTTP Connections

Based on the network traffic I’ve seen from applications and test code, Node’s global HTTP agent disables HTTP Keep-Alive by default, always sending a Connection:close request header. That means that whether the server you’re talking to supports it or not, your Node application will create and destroy an HTTP connection for every request you make. That’s a lot of potentially unnecessary overhead on your service and the network. I’d expect a typical microservice to be talking frequently to a relatively small set of other services, in which case keep-alive might improve performance and scalability.

Enabling keep-alive is straightforward if it makes sense to do so, passing the option to a new agent or setting the global agent http.globalAgent.keepAlive andhttp.globalAgent.keepAliveMsecs parameters as is appropriate for your situation.

Tell Node if it’s running in less than 1.5G of memory

According to RisingStack, Node assumes it has 1.5G of memory to work with. If you’re running in less, you can configure the allowed sizes of the different memory areas via v8 command line parameters. Their suggestion is to configure the old generation space by adding the “–max_old_space_size” with a numeric value for number of megabytes to the startup command.

For a 512M available, they suggest 400M old generation space. I couldn’t find a great deal of information about the memory settings and their defaults in v8, so I’m using 80% as a starting point rule of thumb.

Summary

These tips might be pretty obvious – but they’re also subtle and easy to miss, particularly if you’re testing in a larger memory space, looping back to localhost or some local container.

 

Continuous Integration for Researchers?

TL;DR

Could tailored continuous integration help scientific researchers avoid errors in their data and code?

Computer Error?

Nature reported on the growing problem of errors in the computer code produced by researchers back in 2010. Last year, news hit the press about an error made in an Excel spreadsheet that undermined public policy in the UK. Mike Croucher discusses several more examples of bad code leading to bad research in his talk ‘Is your Research Software Correct?’.

It seems odd that computers are involved in these kinds of errors – after all, we write instructions down in the form of programs, complete and unambiguous descriptions of our methods. We feed the programs to computers and they do exactly what the programs tell them to do. If there’s an error, the scientific method should catch them when other researchers fail to reproduce the results. So why are errors slipping through?

That’s the question that Mike and I were chewing over between talks at TEDxSHU in December 2015. I think the talks I heard there inspired me to think harder about trying to find an answer. It seems like the first step to solving the problem is reproducing results.

Reproducibility Fail

My MSc. dissertation involved processing a load of data that I was given and running programs that I’d written to draw conclusions. Although my dissertation ran to many thousands of words, it was a fairly shallow description – my interpretation, in fact – of what the data said and what the code did. I can’t give you the data or the code as there were privacy and intellectual property concerns about both.

If I’m going to tear it apart, my dissertation really describes what I intended to tell a computer to do to execute my experiment. Then it claims success based on what happened when it did what I actually told it to do.

If you had my code, you could run it on your own data and see if my conclusions held up. You could inspect it for yourself. You could see the tests I wrote and maybe write some yourself if you had concerns. You could see exactly what versions of what library code I was using – maybe there have been bugs discovered since that invalidate my conclusions. If you had my data you could check that my answers were at least correct at the time and are still correct on more recent versions of the libraries.

If you had my code and my data, you won’t know what kind of computer I did the work on or how it was set up. Even that could change the result – remember the pentium bug? Finally, if you had all that information, you’ve still got to get hold of everything that you need, wire it all up and do your verifications. That’s quite a time and cost commitment, assuming that you still can get hold of all that stuff months or years later.

Continuous Integration to the Rescue?

I’m sure I’ve just skimmed the surface of the problem here – I’m not a researcher myself, nor am I claiming that my dissertation was in any way equivalent to an academic paper. It’s just an example I can talk about,  and it’s enough to give me an idea. It sounds a little like the “works on my machine” problem that used to be rife in software development. One of the tools we use to solve it is “continuous integration”.

Developers push their code to a system that “builds” it independently, in a clean and consistent environment (unlike a developer’s computer!). “Building” might involve steps like getting libraries you need, compiling and testing your code. If that system can’t independently build and test your code, then the build breaks and you fix it.

A solution along these lines would necessarily have to automatically verify that all the information needed to get the code running, such as the code itself, configuration parameters, libraries and their versions, and so forth are present and correct. If the solution could also accept data and results, and then verify that the code runs against the data to produce the results, then it seems like we’ve demonstrated reproducibility.

Setting your own CI server isn’t necessarily straightforward, but Codeship, SnapCI and the like show that hosted versions of such solutions work, offer high levels of privacy and (IMHO) simplify the user experience dramatically. A solution like one of these, but tailored to the needs and skills of researchers might help us start to solve the problem.

Tailored CI for Researchers

I think that the needs of a researcher might differ a little from those of a software developer. What kinds of tailoring am I talking about? How about:

  • quick, easy uploading of code, data and results, every effort to make it “just work” for a researcher with minimal general computing skills
  • built-in support for common research computing platforms like MATLAB and Mathematica
  • simple version control applied automatically behind the scenes – maybe by default each upload of code, data and results is a new commit on a single branch
  • maybe even entirely web-based development for the commonly-taken paths (taking cloud9 as inspiration)
  • support taking your code and data straight into big cloud and HPC compute services
  • enable more expert users to take more control of the build and test process for more unusual situations
  • private by default with ability to share code, data and results with individuals or groups
  • ability to allow individuals or groups to execute your code on their data, or their code on your data, without actually seeing any of your code or data
  • what-if scenarios, for example, does the code still produce the correct results if I update a library? How about if I run it on a Mac instead of a Windows machine?
  • support for academic scenarios like teams that might be researching under a grant but then move on to other things
  • support for important publication concerns like citations
  • APIs to allow integration with other academic services like figshare and academic journal systems

I think that’s the idea, in a nutshell. I’m not sure if it’s already being or been done, or if not, what could happen next, so I’m punting it into the public domain. If you have any comments or criticism, or if there’s anything I’ve skimmed over that you’d like me to talk about more please leave me a comment or ping me on Twitter.

Embassytown

China Miéville’s Embassytown finally made it to the top of my reading list, after the recommendation on Terminally Incoherent. I have to agree with everything Luke says, it’s a pretty compelling sci-fi mixture. There’s a little fantastical technology but the story revolves around humans interacting with an alien society whose use of language is fundamentally different to our own.

I finished the book yesterday and by chance listened to an oddly relevant episode on the Grammar Girl podcast this morning. “Because as a Preposition” talks about a new use of the word “because”, for example “I didn’t do my homework because Skyrim”. To me, this sounds wrong. No, sounds is too weak – it feels wrong, jarring, like other kinds of grammatical error. If I read it at speed, I read “…because of Skyrim”. It was a grammatical error when I learned to speak, read and listen, back in the early eighties. Regarding constructions that were erroneous and became acceptable after I’d learnt seem to be quite deep inside me, more a sense like taste or smell with instinctive likes and dislikes than something I think about.

The podcast talks about how this use was happening in popular culture for those who learnt English after I did, so maybe to them it feels different, natural, when they use or observe it. You’ll see why it’s relevant when you read the book!

I found the story itself to be well crafted and I struggled to put it down. I’d certainly recommend it if you’re a fan of SF and the ideas of language and mind interest you.

Finishing my MSc. Dissertation

I finished my dissertation a couple of months ago, and since graduated. Finishing was a great feeling, but I certainly remember the time when I thought I was losing control of the whole thing. I thought my experiments would fail to produce any positive results, and I lost any confidence I would finish at all. A time of sleepless nights and distracted days, but I learned I’m not alone in feeling that way whilst trying to get my dissertation to come together.  To anyone else who’s in that place, try not to get too stressed and negative about it. Stay focussed on what you want to achieve and keep going. If I can do it, you can – it will come together.

Here’s the final result of all that work, Pattern Recognition in Computer System Events – Paul Brabban, published here in the School of Computer Science library. If you want to read it, I’d suggest having a skim over the introduction and then maybe skip to the conclusions. If you’re still interested then the detail is in the middle sections and if you want to try and reproduce my work, there is an appendix detailing some of the implementation choices I made.

I’m lucky to have had such great tuition and support at Manchester, not to mention the excellent supervision I received for my project from Dr. Gavin Brown. I was also very happy to receive some great feedback from my external examiner,  Professor Muffy Calder at the University of Glasgow. I couldn’t have done the project without the support of the industry partner, so thanks to them and their representatives. My mum and stepbrother painstakingly proofread my later drafts and picked out any number of grammatical errors, and my wife, my friends and my family supported me and listened to me going on and on about computer science geekery.

My eternal gratitude to everyone I’ve mentioned and anyone I’ve forgotten!

A few weeks with the System76 Gazelle Pro

After writing about choosing and unboxing, I was going to write this post after two weeks of using my new laptop. It’s been over a month because I’ve busy with a Coursera course and – well – the laptop has just kinda worked. In fact, it’s been so uneventful that there’s not all that much to write about, but I’ve now tried three distributions on it.

Ubuntu 12.10

It arrived as described with Ubuntu installed, and pretty much everything worked, as you’d expect. The problem I could find was pointed out thanks to @TechHomeBacon on twitter:

@brabster @system76 comes out of the box saying graphics “unknown”

— Tech Home The Bacon (@TechHomeBacon) April 25, 2013

However, the folks @System76 replied, explaining how to resolve the issue:

@techhomebacon @brabster sudo apt-get install mesa-utils’ fixes the description. mesa-utils isn’t installed by default.

— System76 (@system76) April 25, 2013

A minor niggle. As I said in my previous post, I’m not a fan of the Unity desktop so enough of that – the first thing I did was start again and install Kubuntu.

Kubuntu 12.10

The install of Kubuntu, a derivative of Ubuntu based on the KDE desktop, was uneventful. There were no problems and everything worked out of the box – sound, graphics, touchpad – all working. Not much to say, but Ubuntu to Kubuntu use the same underlying distribution and I’m already familiar with both, so I decided to try something a little more challenging.

Arch

Arch Linux is an fairly popular lightweight distribution more geared to folks who like to get their hands dirty, so the setup is more involved and exposes more of what’s going on. It’s not based on Ubuntu, and this machine wasn’t built with Arch in mind. I should also mention that I’ve never used Arch before, so I was expecting more problems.

The setup was certainly more interesting, but entirely due to the more involved nature of Arch and my lack of general smarts. The hardware worked just fine, picking up the right packages without any special configuration. Dammit, still nothing juicy to talk about!

I have noticed a couple of things that often don’t work properly. First, Ctrl-F7 toggled my display between laptop panel and external monitor out of the box, which is fantastically helpful as I’m constantly plugging in an external monitor. Next, my USB hub has an ethernet port and sound hardware on board – these also both worked out of the box.

In Conclusion

So far, I would recommend to a friend.

All the hardware works under all three distributions. Although I bought the lowest-spec i7 processor and the Intel graphics hardware is relatively modest, KDE is a joy to use, silky smooth through all the desktop effects. It’s very quiet in normal use with no discernible fan noise. The laptop keyboard has enough space and tactile feedback to be comfortable in use for extended periods – this is of course subjective, but it works well for me. The display panel is clear and bright when the ambient light isn’t so bright as to cause excessive reflections, as you’d expect.

An Aside

I find it surprising that people still write articles criticising Linux as not ready for the desktop, or the casual user. Quotes such as “Is it bad if I say that I was impressed that sound worked right out of the box?” on a recent Ars Technica article brought this to mind as I bought this laptop, and my experience with a multitude of distributions over the past few years leads me to the opposite view – that many distributions tend to work without fuss and seem quite capable of meeting the needs of a typical, casual user. I may try and talk my wife (a Windows 7 user when she’s not tapping and swiping on her iPad) into trying out a suitable distribution for a while, to try and see the experience from a more casual perspective…

Unboxing my System76 Gazelle Pro

In a previous post, I explained my reasoning behind purchasing a Gazelle Pro laptop from System76. Having never bought direct from a US company before, I had reservations  – whether the machine would survive the trip in one piece and how tax would work on the import.

TL;DR: a good experience with nothing particularly bad to note, but things to be aware of if you’re considering buying one of these:

  • Check how to pay taxes if you’re importing – you might need cash, cheque or some other antiquated mode of disbursement on delivery
  • The system comes with a US power adapter rather than one for your region but it can be worked around
  • It’s not as light or as thin as an ultrabook
  • The gloss flat panel is – well – glossy

System76 mailed me when I made my order, then to confirm that my payment and address were validated and that my machine was being assembled and tested, and finally to confirm that it was on its way, with UPS tracking information. I ordered on the 30th March, and it shipped on 5th April. Not too shabby, given that the Easter holidays were in there, and within the 6-10 business days promised. So far so good.

It arrived at my door on the 10th April, exactly when the UPS tracking site said it would. The courier asked for payment of taxes on the doorstep and required payment by cash or cheque. You remember cheques, right? My grandfather swore by them.

Fortunately, I could lay my hands on my chequebook (after blowing the dust off it) because who keeps £150-ish in cash laying about? If I hadn’t been able to pay by one of these methods, the package would have gone back with the courier to redeliver the following day, which would have been a pain in the backside. A bit of potential annoyance there, it’s a shame UPS don’t tell you on their otherwise very handy tracking site how much you’re going to need to pay and that you’re need cash to cheques ready to take your package.

So – check exactly how you’re going to need to pay taxes. UK folks, right now, keep your cheque book handy or make sure you’ve got the cash to cover it.

Anyway. Now, I’ve got a package in my grubby little mits. The outer packaging contains another cardboard box. Taking a knife to the tape reveals that inside, the laptop is cradled in a couple of foam holders, with the power brick stashed down the side. A photo follows – nothing fancy, but who cares about fancy packaging anyway? So long as the kit is in one piece.

System 76 Gazelle Pro packaging
System 76 Gazelle Pro packaging

We unpack, to find a laptop with protective plastic covers, a power brick and cable and a US keyboard component. I had the UK keyboard fitted, explaining the spare part.

Contents of the Gazelle Pro packaging
Contents of the Gazelle Pro packaging

Ah – the power supply cable is for a US power outlet. Not much use for me here in the UK. Could have been a bit of a problem, but fortunately these days most laptop power bricks have a standard three-pin adapter cable between the wall socket and the brick. I swapped my old brick’s UK adapter cable and we’re in business, but it’s something you might need to bear in mind.

Something that’s clear from the System76 brochureware and again on removing the unit from its packaging is that it’s no Macbook Air-style ultrabook. It’s not particularly light or thin, but then it’s also not as expensive as those kinds of machine. To my eye, much more a workhorse than a fashion accessory, but I like that.

The Gazelle Pro out of its protective foam packaging
The Gazelle Pro out of its protective foam packaging

Booting up confirms that the machine works perfectly and that I have the hardware spec I asked for. I cut a corner to keep the cost down a little and went for the standard glossy screen. Was that a mistake? You be the judge. Here’s the screen with the power off, indoors but with bright sunlight streaming through the window nearby.

Reflection from the Gazelle Pro gloss screen
Reflection from the Gazelle Pro gloss screen in bright sunlight when switched off

Here is it at the Ubuntu login screen, again in bright sunlight.

The Gazelle Pro glossy screen at the login prompt in bright sunlight
The Gazelle Pro glossy screen at the login prompt in bright sunlight

I’m not sure how the matte panel would fare, but this unit, as is typical of glossy panels, isn’t going to work well in bright light. Still, I bought the unit knowing that this would be the case, so I’d generally be using it in much more subdued lighting conditions. Things are much better after drawing the curtains.

The Gazelle Pro gloss panel in subdued lighting
The Gazelle Pro gloss panel in subdued lighting (click for much larger image)

 

So after unboxing, I’m pretty happy. There were only a couple of minor, easily resolvable problems to do with shipping over from the US, and I have the machine I paid for. Next time, the verdict after I’ve installed a different Linux distribution (just can’t get on with the Gnome 3 Unity interface, sorry!) and used the system in anger to do some work.