Using Thrift with Cappuccino

We’ve been Thrift fans for a long time. When we decided to build the front-end of our product in the Cappuccino web framework (Cocoa for the web), we wanted to bring Thrift with us. It’s a big win – our product has many parts: an iPhone app, a backend written in Java, and a rich web tool written in Cappuccino. It helps that both our mobile client and our Cappuccino app can talk to the same API on our Java backend in the same exact way, and without ever having to futz with the data marshaling ourselves.

Thrift already worked on Cocoa (thanks to Andrew McGeachie). We ported Andrew’s work from Objective-C to Objective-J, carried over some ideas from Matt Ronge’s patch, and added some work of our own to make async calls easy and make the HTTP transport play nicely in the browser where binary POSTs aren’t possible.

Getting the Code

For now, you can grab the Thrift/Cappuccino code from our thrift fork on GitHub. There’s a new compiler language target for cappuccino and a new library under lib/cappuccino. We’ll try to submit this back to the main Thrift project and see if people are interested in including it with the main distribution.

Installing

You need to build the thrift compiler as usual. If you’re doing this for the first time, you might find the Thrift Wiki helpful.

You also need to install the Thrift Framework so it can be made available to your Cappuccino projects. Assuming you already have Cappuccino installed, just do the following to copy the framework to your narwhal/packages directory:

cd path/to/thrift/clone/lib/cappuccino
jake install

Using Thrift in your Cappuccino Project

You can copy the Thrift framework to your project with:

capp gen --frameworks --framework Thrift path/to/your/project

The warning about not being able to find the debug framework can be ignored. Alternatively, you can just copy the contents from lib/cappuccino/Framework/Thrift into your project’s Frameworks directory.

The big change in using Thrift in Cappuccino as opposed to elsewhere is that you’re probably going to do everything asynchronously. Everytime you make a call, you provide a target and selectors that will get notified when things succeed or fail (see below)

For a more complete example, checkout the tutorial under tutorial/cappuccino.

Server-side Changes

Doing HTTP POSTs of binary blobs of data (as you would normally do with Thrift over HTTP) isn’t something that’s possible with a lot of browsers today. So, the included THTTPTransport expects to communicate via HTTP POSTs of URL-Safe-Base64 encoded data. Your HTTP endpoint will need to translate the base64 to binary, operate as normal, and then translate the binary back to base64.

If you use Rails, checkout thrift-cappuccino-rails-example (live) for an example of how you would do this. If you’re on Java like us and have been using Tom White’s TServlet.java, checkout our modified version.