add CouchDB view_cache in server memory for 60s
authorDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 23 Jan 2013 01:23:58 +0000 (02:23 +0100)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Wed, 23 Jan 2013 01:23:58 +0000 (02:23 +0100)
angular-server.pl

index 80d2392..030d0fe 100755 (executable)
@@ -210,6 +210,8 @@ any [ 'post' ] => '/data/:database/:entity' => sub {
 
 # CouchDB proxy for _design _view
 
+our $view_cache;
+
 get '/:database/_design/:design/_view/:view' => sub {
        my $self = shift;
        my $format = $self->param('format');
@@ -217,6 +219,19 @@ get '/:database/_design/:design/_view/:view' => sub {
        if ( my $param = $self->req->url->query->clone->remove('callback')->remove('format')->to_string ) {
                $url .= '?' . $param
        }
+
+       if ( exists $view_cache->{$url}->{time} ) {
+               if ( time() - $view_cache->{$url}->{time} < 60 ) {
+                       warn "HIT CouchDB cache $url";
+                       $view_cache->{$url}->{hit}++;
+                       return _render_jsonp( $self, $view_cache->{$url}->{json} );
+               } else {
+                       warn "REFRESH CouchDB cache $url";
+                       $view_cache->{$url}->{refresh}++;
+               }
+       } else {
+               $view_cache->{$url}->{miss}++;
+       }
        warn "CouchDB proxy $url";
        my $json = _couchdb_get($url);
 
@@ -251,6 +266,12 @@ if ( doc.user.organization != '' ) {
        if ( $format eq 'key_array' ) { # array of keys sorted by value
                $json->{rows} = [ map { $_->{key} } sort { $b->{value} <=> $a->{value} } @{ $json->{rows} } ];
        }
+
+       $view_cache->{$url}->{time} = time();
+       $view_cache->{$url}->{json} = $json;
+
+       warn "# view_cache ",dump($view_cache);
+
        _render_jsonp( $self, $json );
 };