Guilhermesilveira's Blog

as random as it gets

Posts Tagged ‘dynamic

Hypermedia and dynamic contracts: let my bandwidth rest!

with 10 comments

“Break it” to scale!

Many systems contain webpages that are very similar to user “custom pages”, where they can configure what they want to see, and every piece is aggregated from different sources into one single page.

In some cases, those are widget based frameworks as wicket and gwt that can be added to my custom page; in other cases you have aggregating portals.

An example of this kind of application (even though its not configurable) is a retail website containing four sections in its home page: the top 10, my orders, random items, and weird items.

In this case, all information come from the same source, but every part has a different probable validity if it is going to be cached. If the page is served as one big chunck of information, it will always be stale due to the random items section. “My orders” is stale only when I place a new order and, in the same way, the top 10 is only stale if any item is bought and surpasses the number of times the 10th item was bought so far.

One of the main issues with this type of pages which aggregate information from one or many sources with different expire-expectations is that cached versions in proxies and clients become stale faster than it should for some elements: once one of this providing sources publishes new information or is updated, the entire representation becomes stale..

Martin Fowler described once a well spread approach to allow those pages to be partially cached within local proxies and clients, thus sharing requested representations between multiple users.

The approach

Given the coffee scenario, one would create different json representations:

And finally an aggregating page:

<html>
<a class="lazy_load" href="http://restbucks.com/top_sellers">Top sellers</a>
<a class="lazy_load" href="http://restbucks.com/my_orders">My orders</a>
<a class="lazy_load" href="http://restbucks.com/random_items">Random items</a>
<a class="lazy_load" href="http://restbucks.com/weird_items">Weird items</a>

And then, for each lazy_load link, we create a div with its content:

<script>
$('.lazy_load').each(function(link) {
  uri = link.attr('href'); 
  div = $('
').load(uri); // cache hits! link.after(div); }); </script> </html>

This allows our proxies to cache each component in our page apart from the page itself: whenever one page’s content becomes stale in a proxy, only part of that page needs update.

In a web were most data can be cached and does not become stale so fast, this technique should usually lessen the amount of data being transfered between client and server.

All one needs to do is properly use the http headers for caching.

Remember that if your client supports either parallel requests to the server and/or keep-alive connection, the results might be even better.

Distributed systems? Linked resources?

Roy Fielding mentions that in the data view in REST systems, “small or medium-grain messages are used for control semantics, but the bulk of application work is accomplished via large-grain messages containing a complete resource representation.”

Pretty much in the same way as with the human web, a distributed system using the web as its infrastructure will gain the same cache benefits as long as they implement correct caching policies through http headers (and correct http verbs).

When your server provides a resource representation linking to a series of other related resources the client and proxies staying on the way will be allowed to cache each and every other resource on its own.

This approach results, again, in changes applied to one resource not affecting cached representations of other resources. An stale representation will not affect those accessing other resources within the same context.

Sometimes the decision whether to change latency for scalability might depend on how you think your clients will use your resources: in the human web mentioned above, the developer knew exactly how its clients would access it.

In distributed systems using REST, guessing how resources will be used can be dangerous as it allows you to tight couple yourself to this behaviour while published resources can and would be used in unforeseen ways.

Roy’s dissertation seems to apply here to balance things: “a protocol that requires multiple interactions per user action, in order to do things like negotiate feature capabilities prior to sending a content response, will be perceptively slower than a protocol that sends whatever is most likely to be optimal first and then provides a list of alternatives for the client to retrieve if the first response is unsatisfactory”.

Giving information that will help most cases is fine and providing links to further resources details allow you to balance between latency and scalability (due to caching) as you wish.

Dynamic contracts

This is only possible because we have signed dynamic contracts with our clients. They expect us to follow some formal format definition (defined in xhtml) and processes. How our processes are presented within our representations is the dynamic part of the contract.

While the fixed part can be validated with the use of schema validators, the dynamic part – the process – which is guided by our server needs to be validated through testing the behaviour of our applications: asserting that hypermedia guided transitions should be reflected in our application state.

Nowadays

On the other hand, many contemporary systems use the POST verb receiving a response including many representations at once or the GET verb without any cache related headers: thus not profiting from the web infrastructure at all. This could changed with one (or both) of the following:

  • use the GET verb with cache headers
  • use hypermedia and micro formats to describe relations between resources

Using it might present similar results as hypermedia+GET+cache headers in the human web – and some styles might already be providing support for it, although not being a constraint.

Note that in this case hypermedia is not driving the application state, but helping with scalability issues.

Progressive enhancement

Martin notes that this is a kind of progressive enhancement: although its definition is related to accessibility, its control over bandwidth benefits are similar to the approach mentioned ones.

Any other systems that use hyperlinks to “break” representations and scale?

Written by guilhermesilveira

December 10, 2009 at 9:15 am

Restfulie Java: quit pretending, start using the web for real

with 5 comments

Its time to release Restfulie Java, offering the same power encountered in its ruby release, through the use of dynamic bytecode generation and request interception using VRaptor.

Serialization framework

Restfulie adopts XStream by default. Its simple usage and configuration gets even easier due to vraptor’s serialization extension built upon XStream – but it allows the usage of other serializers.

The following code will serialize the order object including its children items (much similar to rails to_xml only option):

serializer.from(order).include("items").serialize();

Connected: Hypermedia content creation

In order to guide the client from one application state to another, the server needs to create and dispatch links that can be interpreted by the client machine, thus the need for generating hypermedia aware serialization tools and consumer apis.

Its the basic usage of the web in a software-to-software communication level.

Pretty much like Restfulie’s ruby implementation, by implementing the getFollowingTransitions method, restfulie will serialize your
resource, generating its representation with hypermedia links:

public List getFollowingTransitions(Restfulie control) {
  if (status.equals("unpaid")) {
    control.transition(OrderingController.class).cancel(this);
    control.transition(OrderingController.class).pay(this,null);
  }
  if(status.equals("paid")) {
    control.transition(OrderingController.class).retrieve(this);
  }
  return control.getTransitions();
}

Controller interception

Restfulie for Java goes further, intercepting transition invocations and checking for its status. The following example will only be executed if order is in a valid state for paying:

@Post @Path("/order/{order.id}/pay")
@Consumes("application/xml")
@Transition
public void pay(Order order, Payment payment) {
	order = database.getOrder(order.getId());
	order.pay(payment);
	result.use(xml()).from(order.getReceipt()).serialize();
}

Why?

Restfulie does not provide a bloated solution with huge api’s, trying to solve every other problem in the world. According to Richardson Maturity Model, systems are called RESTFul when they support this kind of state flow transition through hypermedia content contained within resources representations:

<order>
 <product>basic rails course</product>
 <product>RESTful training</product>
 <atom:link rel="refresh" href="http://www.caelum.com.br/orders/1" xmlns:atom="http://www.w3.org/2005/Atom"/>
 <atom:link rel="pay" href="http://www.caelum.com.br/orders/1/pay" xmlns:atom="http://www.w3.org/2005/Atom"/>
 <atom:link rel="cancel" href="http://www.caelum.com.br/orders/1" xmlns:atom="http://www.w3.org/2005/Atom"/>
</order>

Stateless state

In order to profit even more from the web infrastructure, Restfulie for Java provides a (client state) stateless api.

Addressability

VRaptor’s controller api allows you to specify custom URI’s (and http verbs) to identify resources (and transitions) in your system.

Addressability + client cache stateless state server allows one to achieve REST’s idea on cache usage and its related layered systems advantages by allowing other layers to be added between the client and the server.

Unknown usage of my resources

Addressability + hypermedia content allows clients to use your resources pretty much in a way that was not tought of at first. Addresses (in our case, URI’s) can be passed around from one application to another, to and from a client’s internal database (as simple as a browser favorites, or google gears).

Building your system upon such basis, it become unaware of its resources usage (resource representation’s interpretation) patterns, allowing clients to create such previously unknown systems.

Less and simpler code, more results

Both on the server and client side, restfulie tries to achieve results based on conventions, therefore one can easily access its entry api to insert a resource in a system, i.e.:

  Movie solino = new Movie();
  resource("http://www.caelum.com.br/movies").include("metadata").post(solino);

And after creating a resource, one can actually navigate through your resource’s connections:

  Movie solino = resource("http://www.caelum.com.br/movies/solino").get();
  Comments comments = resource(solino).getTransition("comments").executeAndRetrieve();
  // print all comments

And navigate through your resource’s states:

  Comments comments = resource(solino).getTransition("comments").executeAndRetrieve();

  Comment comment = new Comment("nice movie on generations of immigrants and the hard times that they face when moving to a new place");
  resource(comments).getTransition("add").execute(comment);

A lot of good practices should be put into place in order to avoid creating Leonard Richardson’s defined REST-RPC alike systems.

Those good practices involve simple steps as avoiding anemic models on the client side . Restfulie+Vraptor already tries to avoid this on the server side andwe will discuss about such practices in following posts.

Download and example applications

Beginners could start by downloading restfulie’s client and server example application, ready to run in a eclipse wtp enviroment or pure eclipse installation.

Users are encouraged to use either the java or ruby mailing lists.

Since Restfulie was born in Ruby…

Since we released restfulie for ruby (on rails), which can be found at its github page, it was commented by Jim Webbers both on his blog and in person during QCon in San Francisco, where both him and Ian Robinson held a tutorial on restful systems and the web and will hold another round, more hands-on, at QCon London 2010.

Meanwhile, Restfulie was commented at ruby5’s podcast, commented here, at infoq, and in portuguese by Juliana and by Anderson Leite – a fellow Caelum developer.

As some comments were out about restfulie’s ruby implementation, restfulie: it’s more than easy.

Written by guilhermesilveira

November 25, 2009 at 11:13 am

Dev in rio 2009

leave a comment »

Some good friends from globo.com (Guilherme) and myfreecomm (Henrique) have invited two speakers from the Caelum team to talk about Java at this year’s Dev in Rio.

Guilherme and Henrique will start the event monday morning and after that me and Nico Steppat will talk about how new modern languages (either dynamic, functional, more or less expressive or anything alike) are influencing the market around the world and how we can enjoy the benefits of those languages within the scope of a polyglot-programming team. Java shows its signs of age, so how can we face those changes in the world and profit from every positive aspects of those languages, while still benefiting something from the Java technology?

Ryan Ozimek will start talking about Joomla! and how it has been changing the and improving technology.

Fabio Akita from Locaweb will talk about Rails, we can expect some introduction to the rails enviroment and what has been developed so far by the community in order to make software development an easier task.

Jacob Kaplan-Moss will talk about Django, a well-known Python software that makes it easy to develop database-based websites.

And summing up, Vinicius Teles will gather all speakers and participants to talk about… software development.

It is a really nice chance to meet new people, learn and share ideas with some big names from the open source development community.

Written by guilhermesilveira

August 28, 2009 at 8:00 am