/ #CouchDB #Erlang 

eCloudEdit Part 2: CouchDB

In my last post I showed the Webmachine backend to James Yu’s CloudEdit app in Backbone.js. What was left out was, where are the documents stored? Here I’ll show how this is done with CouchDB. And you can give the app a try at http://erlware.org:8080

First, a new Erlang app is needed that we’ll call ece_db.

Three modules are implemented, one that starts the app by calling the supervisor’s start function, the supervisor itself that sets up a simple_one_for_one and the gen_server that handles the frontends requests for creating and modifying documents in CouchDB.

We’ll ignore the ece_db_app.erl module for this post and start with ece_db_sup.erl. On requests from the Webmachine resource module we don’t want one to wait on the other, requests should be handled in parrallel. One option is to not create a process for the database backend and instead have all of the functions in the database interface run in the process of the Webmachine resource. However, two reasons to not do this are that there are multiple pieces of data that must be read out of a configuration file and used to setup what is needed to talk to CouchDB. We do not want to be doing this for every request! Furthermore a supervised gen_server allows us the possibility of retrying requests with no extra code and crashing without retrying but not taking down the resource’s process that is handling the user’s HTTP request. It is a lot nicer and easier to just let things fail when we can!

First, we have the config entries in config/sys.config that will be read in by application:gen_env. Here we set the server URL, port number and name of the database to use. CouchDB can easily be run locally but for my running copy I use a database hosted by the great service Cloudant. Next is the init function for ece_db_sup.erl. A key thing to note for a simple_one_for_one is that NO process is started after the supervisor’s init function returns like with other types of supervisor children. Instead we must explicitly call start_child. This is how we are able to create a supervised gen_server process for every HTTP request. Below is the code in ece_db_sup for starting and stopping the process:

In the last post I showed the functions that start and stop the ece_db process. Here they are again:

On each request Webmachine calls the init function for the resource that is matched in the dispatch table. In that init function we call start_child in ece_db_sup which returns {ok, PID}. The PID is the process id we’ll be sending messages. Now in ece_db we implement the API functions needed to start the process and to interact with it.

Each function, besides the one for starting the process, takes a PID. This PID is the process gen_server:call to which it sends its message. To handle these messages we have the gen_server callbacks.

init takes the server URL, the port number and the name of the database to store the documents as arguments and creates a CouchBeam database record. To handle the other messages we have the handle_call function to match on the different tuples sent to gen_server:call for the different function calls. all uses the internal function get_docs with the option to have the function in descending order (so the newest is first) and returns those after encoding to JSON. find uses the same function but only wants a certain document which in the case of CouchDB is specified with a key value. create first saves the new document which returns the document that is actually stored in CouchDB. CouchDB adds the _id and _rev key/value pairs it generates. Since our frontend expects the id to be the value of a key id and not _id we use couchbeam_doc:set_value to set a value of the new key id with the value of the documents id retrieved from the document with couchbeam_doc:get_id. For update we first open the document corresponding to the id passed in as an argument to get the _rev value. _rev needs to be set in the document we send to save_doc so CouchDB knows this is a valid update based on the previous version of the document. Thus we set the new documents _id and _rev values and send to save_doc.

Lastly, we have the get_docs function. Since the frontend expects the key id to exist and CouchDB stores the id with the key _id we use a simple view to return the documents with id containing the value of the documents _id. Views are defined with map/reduce functions that CouchDB runs across the databases documents and builds an index from. These indexes are then queried based on keys to find documents. Thus access is very quick, indexes are built with BTrees, and a map/reduce does not have to be run on the documents for every request. Additionally, when a new document is created the view’s map/reduce functions only need to run over the new documents to update the BTree. Updates to the view’s indexes are either done on each use of the view or can be manually told to run.

In get_docs the couchbeam:view function is used to construct a view request to be sent to the CouchDB server. couchbeam_view:fetch sends the view request and returns the results as Erlang terms. After this we extract the rows from the results and use lists:map to extract out just the value of each row to be returned.

That’s it! There are places that could use improvement. One being the use of lists:map over every returned row to construct documents the frontend can deal with. Additionally, the need to duplicate _id as id for the frontends use could be removed through modifications on the frontend.

In the next installment I’ll be updating the code – and maybe making some of these performance enhancements – with James Yu’s recent changes in his Part 2.