Wednesday, July 25, 2012

Riak: Precommit Hook Example

Book "Seven Databases in Seven Weeks" has an example of how to use a precommit hook in Riak. However, it did not work for me (Riak 1.1.4). The issue is that I was getting the following message for every single commit:
PUT aborted by pre-commit hook
After enabling debug logging in the app.config (*), I realized that it was failing with the following error:
Problem invoking pre-commit hook: [{<<"lineno">>,1},{<<"message">>,<<"ReferenceError: good_scores is not defined">>},{<<"source">>,<<"unknown">>}]
The problem is that the command to set the precommit hook MUST specify the language, otherwise it doesn't work properly. In order to get the book's example fixed then, do the following:
curl -i -X PUT http://localhost:8091/riak/animals -H "content-type: application/json" -d '{"props":{"precommit":[{"name":"good_score","language":"javascript"}]}}'
Once enabled, I was getting the proper error messages. Most importantly, valid data was being accepted and committed by Riak.

You may be wondering how the Javascript looks like. Since I can't copy the book's example due to copyright, this is an example of function that works the same:
// Makes sure the object has JSON contents
function precommitMustBeJSON(object){
  try {
    Riak.mapValuesJson(object);
    return object;
  } catch(e) {
    return {"fail":"Object is not JSON"};
  }
}
Unfortunately Riak does not have a good tutorial or example on that and it was hard to find the reason for the error. Maybe it'll get better as it matures.

One final thing: don't forget that you need to put your function in a .js file in a directory configured in your app.config. For instance, my file is called "my_validators.js" and it's located in the directory I configured in app.config:
{js_source_dir, "/home/rdcastro/riak/js_source"},
(*) To enable debug logging, make sure your "lager" section has the following settings:
            {handlers, [
                {lager_console_backend, debug},
                {lager_file_backend, [
                    {"./log/error.log", error, 10485760, "$D0", 5},
                    {"./log/console.log", debug, 10485760, "$D0", 5}
                ]}
            ]},
Post a Comment