/[Frey]/branches/zimbardo/lib/Frey/CouchAPI.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Diff of /branches/zimbardo/lib/Frey/CouchAPI.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1052 by dpavlin, Thu Apr 23 20:12:45 2009 UTC revision 1071 by dpavlin, Tue Apr 28 16:38:18 2009 UTC
# Line 4  package Frey::CouchAPI; Line 4  package Frey::CouchAPI;
4    
5  This is REST wrapper using following L<Mojo> implement Apache's CouchDB API  This is REST wrapper using following L<Mojo> implement Apache's CouchDB API
6    
7    You can access it using normal C</_utils/> URI, just like on real CouchDB and
8    it will bring up partially functional Futon interface against this module.
9    
10  L<Mojo::URL>  L<Mojo::URL>
11    
# Line 23  use URI::Escape; Line 25  use URI::Escape;
25  use File::Path qw(make_path remove_tree);  use File::Path qw(make_path remove_tree);
26  use Storable;  use Storable;
27    
28  our $VERSION = '0.1';  our $VERSION = '0.3';
29  $VERSION .= ' on Frey ' . $Frey::VERSION;  $VERSION .= " (Frey $Frey::VERSION)" if $Frey::VERSION;
30    
31  our $debug = $Frey::debug || 0;  our $debug = $Frey::debug || 0;
32    
# Line 43  sub rewrite_urls { Line 45  sub rewrite_urls {
45  }  }
46    
47  our $config = {  our $config = {
48          path => '/data/webpac2/var/row',          database => {
49                    path => '/data/webpac2/var/row',
50                    name_glob => '/*/*',
51            }
52  };  };
53    
 my $p = $config->{path};  
 my @all_dbs = map {  
         s{^\Q$p\E/*}{};  
         $_;  
 } glob "$p/*/*";  
   
54  my $regex_dbs = '[a-z][a-z0-9_\$\(\)\+\-/]+';  my $regex_dbs = '[a-z][a-z0-9_\$\(\)\+\-/]+';
55    
56  our $json = {};  our $json = {};
# Line 60  our $status; Line 59  our $status;
59  sub ok {  sub ok {
60          $json = { ok => JSON::true };          $json = { ok => JSON::true };
61          $status = 200;          $status = 200;
62          warn "ok\n";          warn "ok from ",join(' ',caller),$/;
63  }  }
64    
65    sub file_rev { (stat($_[0]))[9] } # mtime
66    
67    sub data_from_tx {
68            my $tx = shift;
69            my $data = $tx->req->content->file->slurp;
70            $data = JSON->new->allow_nonref->decode( $data );
71            warn "## data ",dump( $data );
72            return $data;
73    }
74    
75  sub dispatch {  sub dispatch {
76          my ($self,$tx) = @_;          my ($self,$tx) = @_;
# Line 72  sub dispatch { Line 80  sub dispatch {
80          my $url = $tx->req->url->to_string;          my $url = $tx->req->url->to_string;
81          $url = uri_unescape( $url );          $url = uri_unescape( $url );
82          my $method = $tx->req->method;          my $method = $tx->req->method;
83            my $path = $config->{database}->{path};
84                    
85          if ( $url eq '/' ) {          if ( $url eq '/' ) {
86                  $json = {                  $json = {
# Line 80  sub dispatch { Line 89  sub dispatch {
89                  };                  };
90                  $status = 200;                  $status = 200;
91          } elsif ( $url eq '/_all_dbs' ) {          } elsif ( $url eq '/_all_dbs' ) {
92                  $json = [ @all_dbs ];                  $json = [
93                            map {
94                                    s{^\Q$path\E/*}{};
95                                    $_;
96                            } glob $path . $config->{database}->{name_glob}
97                    ];
98                  $status = 200;                  $status = 200;
99          } elsif ( $url =~ m{^/_config/?(.+)} ) {          } elsif ( $url =~ m{^/_config/?(.+)} ) {
100    
101                  $json = { CouchAPI => $config };                  $json = $config;
102    
103                  if ( $method eq 'PUT' ) {                  if ( $method eq 'PUT' ) {
104    
105                          my $part = $1;                          my $part = $1;
106                          warn "## part $part";                          my $data = data_from_tx( $tx );
107                            warn "## part $part = $data\n";
108    
                         $part =~ s!^!->{'!;  
109                          $part =~ s!/!'}->{'!;                          $part =~ s!/!'}->{'!;
                         $part =~ s/$/'}/;  
110    
                         my $data = $tx->req->content->file->slurp;  
                         $data = JSON->new->allow_nonref->decode( $data );  
                         warn "## data ",dump( $data );  
111                          # poor man's transaction :-)                          # poor man's transaction :-)
112                          my $code = "\$json$part = \$data; \$config$part = \$data;";                          my $code = "\$config->{'$part'} = \$data;";
113                          eval $code;                          eval $code;
114                          if ( $@ ) {                          if ( $@ ) {
115                                  warn "ERROR: $code -> $@";                                  warn "ERROR: $code -> $@";
# Line 108  sub dispatch { Line 118  sub dispatch {
118                                  $status = 200;                                  $status = 200;
119                          }                          }
120    
121  warn "json ",dump( $json ), " config ", dump( $config );                          warn "# config after $code is ",dump( $config ),$/;
122    
123                  } elsif ( $method eq 'GET' ) {                  } elsif ( $method eq 'GET' ) {
124                          $status = 200;                          $status = 200;
# Line 116  warn "json ",dump( $json ), " config ", Line 126  warn "json ",dump( $json ), " config ",
126                          $status = 501;                          $status = 501;
127                  }                  }
128    
         } elsif ( $url =~ m{($regex_dbs)/$} ) {  
   
129  =head2 Database  =head2 Database
130    
131  L<http://wiki.apache.org/couchdb/HTTP_database_API> except compaction  L<http://wiki.apache.org/couchdb/HTTP_database_API> except compaction
132    
133  =cut  =cut
134    
135            } elsif (
136                       $url =~ m{($regex_dbs)/$}
137                    # DELETE doesn't have trailing slash
138                    || $method eq 'DELETE' && $url =~ m{($regex_dbs)$}
139            ) {
140    
141                  my $database = $1;                  my $database = $1;
142                  my $dir = "$config->{path}/$database";  
143                    my $dir = "$path/$database";
144    
145                  if ( $method eq 'GET' ) {                  if ( $method eq 'GET' ) {
146                          $json = database_get( $database );                          $json = database_get( $database );
# Line 133  L<http://wiki.apache.org/couchdb/HTTP_da Line 148  L<http://wiki.apache.org/couchdb/HTTP_da
148                          if ( ! -e $dir ) {                          if ( ! -e $dir ) {
149                                  $status = 404;                                  $status = 404;
150                          } else {                          } else {
151                                  remove_tree($dir) && ok || { $status = 500 };                                  remove_tree($dir);
152                                    if ( ! -d $dir ) {
153                                            ok;
154                                    } else {
155                                            $status = 500;
156                                    }
157                          }                          }
158                  } elsif ( $method eq 'PUT' ) {                  } elsif ( $method eq 'PUT' ) {
159                          if ( ! -e $dir ) {                          if ( -e $dir ) {
                                 make_path($dir) && ok && warn "created $dir" || { $status = 500 };  
                         } else {  
160                                  $status = 412;                                  $status = 412;
161                            } else {
162                                    make_path($dir);
163                                    if ( -e $path ) {
164                                            ok;
165                                            $status = 201;
166                                    } else {
167                                            $status = 500;
168                                    }
169                          }                          }
170                  }                  }
171    
172                    warn "## database $database $status ",dump( $json );
173    
174          } elsif ( $url =~ m{($regex_dbs)/([^?]+)\??(.+)?$} ) {          } elsif ( $url =~ m{($regex_dbs)/([^?]+)\??(.+)?$} ) {
175                  my ($database,$id,$args) = ($1,$2,$3);                  my ($database,$id,$args) = ($1,$2,$3);
176    
# Line 161  L<http://wiki.apache.org/couchdb/HTTP_Do Line 189  L<http://wiki.apache.org/couchdb/HTTP_Do
189                          }                          }
190                  }                  }
191    
                 my $path = $config->{path};  
192                  warn "ERROR: path $path doesn't exist\n" unless -e $path;                  warn "ERROR: path $path doesn't exist\n" unless -e $path;
193    
194                  my $p = "$path/$database/$id";                  my $p = "$path/$database/$id";
195                  warn "## database: $database id: $id -> $p ", dump( $arg ),"\n";                  warn "## database: $database id: $id -> $p ", dump( $arg ),"\n";
196    
197    
198                  if ( $id =~ m{_all_docs(\w+)?$} ) {                  if ( $id =~ m{_all_docs(\w*)$} ) {
199    
200                          my $by = $1;                          my $by = $1;
201                          my $offset = 0;                          my $offset = 0;
202                          my $startkey = delete $arg->{startkey};                          my $startkey = delete $arg->{startkey};
203                               $startkey ||= delete $arg->{startkey_docid}; # XXX key == id
204                          my $endkey   = delete $arg->{endkey};                          my $endkey   = delete $arg->{endkey};
205                          my $limit    = delete $arg->{limit};                          my $limit    = delete $arg->{limit};
206                            my $skip     = delete $arg->{skip};
207                          my $total_rows = 0;                          my $total_rows = 0;
208                            my $collected_rows = 0;
209    
210                          my @docs = grep { length $_ } map {                          my @docs = grep { length $_ } map {
211                                  return '' if defined $limit && $total_rows == $limit;  
212                                    $total_rows++;
213                    
214                                  s{^$path/$database/}{};                                  if ( $limit > 0 && $collected_rows == $limit ) {
215                                  return '' if defined $endkey && $_ gt $endkey;                                          '';
216                                    } else {
217            
218                                            s{^$path/$database/}{};
219    
220                                  if ( $startkey ) {                                          if ( defined $endkey && $_ gt $endkey ) {
221                                          if ( $_ ge $startkey ) {                                                  '';
222                                                  $total_rows++;                                          } elsif ( $startkey ) {
223                                                  $_;                                                  if ( $_ ge $startkey ) {
224                                                            $collected_rows++;
225                                                            $_;
226                                                    } else {
227                                                            $offset++;
228                                                            '';
229                                                    }
230                                          } else {                                          } else {
231                                                  $offset++;                                                  $collected_rows++;
232                                                  return '';                                                  $_;
233                                          }                                          }
                                 } else {  
                                         $total_rows++;  
                                         $_;  
234                                  }                                  }
235    
236                          } glob( "$path/$database/*" );                          } glob( "$path/$database/*" );
237    
238                            $offset += $skip if $skip;
239    
240                          warn "## docs $startkey -> $endkey limit $limit ", dump( @docs ); # if $debug;                          warn "## docs $startkey -> $endkey limit $limit ", dump( @docs ); # if $debug;
241    
242                          $json = {                          $json = {
# Line 222  L<http://wiki.apache.org/couchdb/HTTP_Do Line 261  L<http://wiki.apache.org/couchdb/HTTP_Do
261                                          id => $id,                                          id => $id,
262                                          key => $id,                                          key => $id,
263                                          value => {                                          value => {
264                                                  rev => (stat($p))[9], # mtime                                                  rev => file_rev $p,
265                                          }                                          }
266                                  };                                  };
267                          }                          }
# Line 237  L<http://wiki.apache.org/couchdb/HTTP_Do Line 276  L<http://wiki.apache.org/couchdb/HTTP_Do
276                                  push @{ $json->{rows} }, $rows->{$id};                                  push @{ $json->{rows} }, $rows->{$id};
277                          }                          }
278    
279                            $status = 200;
280    
281                  } elsif ( $method eq 'PUT' ) {                  } elsif ( $method eq 'PUT' ) {
282                    
283                          warn "## ",dump( $tx->req ) if $debug;                          warn "## ",dump( $tx->req ) if $debug;
284    
285                          my $data = $tx->req->content->file->slurp;                          my $data = $tx->req->content->file->slurp;
286    
287                            my $db_path = "$path/$database";
288                            make_path $db_path unless -e $db_path;
289    
290                          Storable::store( from_json($data), $p );                          Storable::store( from_json($data), $p );
291                          warn "store $p ", -s $p, " bytes: $data\n";                          my $rev = file_rev $p;
292                            warn "store $p $rev size ", -s $p, " bytes | $data\n";
293    
294                          $status = 201; # Created                          $status = 201; # Created
295                                    $json = {
296                                    id => $id,
297                                    ok => JSON::true,
298                                    rev => $rev,
299                            };
300    
301                  } elsif ( $method eq 'GET' ) {                  } elsif ( $method eq 'GET' ) {
302                          if ( ! -e $p ) {                          if ( ! -e $p ) {
303                                  $status = 404;                                  $status = 404;
304                          } else {                          } else {
305                                  warn "retrive $p ", -s $p, " bytes\n";                                  warn "retrive $p ", -s $p, " bytes\n";
306                                  $json = Storable::retrieve( $p );                                  $json = Storable::retrieve( $p );
307                                    if ( delete $arg->{revs_info} ) {
308                                            my $rev = file_rev $p;
309                                            $json->{_rev} = $rev;
310                                            $json->{_revs_info} = [
311                                                    { rev => $rev, status => 'available' }
312                                            ];
313                                    }
314                                    $status = 200;
315    
316                          }                          }
317                  } elsif ( $method eq 'DELETE' ) {                  } elsif ( $method eq 'DELETE' ) {
318                          if ( -e $p ) {                          if ( -e $p ) {
319                                  unlink $p || { $status = 500 };                                  unlink $p && ok || { $status = 500 };
320                          } else {                          } else {
321                                  $status = 404;                                  $status = 404;
322                          }                          }
323                    } elsif ( $method eq 'POST' ) {
324                            my $data = data_from_tx( $tx );
325    
326                            # FIXME implement real view server and return 200
327                            $json = { total_rows => 0, offset => 0 };
328                            $status = 202;
329    
330                  } else {                  } else {
331                          $status = 501;                          $status = 501;
332                  }                  }
333    
334                  warn "WARNING: arg left from $url = ",dump( $arg ),$/ if keys %$arg;                  if ( keys %$arg ) {
335                            warn "WARNING: arg left from $url = ",dump( $arg ),$/;
336                            $status = 501;
337                    }
338    
339          }          }
340    
# Line 275  L<http://wiki.apache.org/couchdb/HTTP_Do Line 345  L<http://wiki.apache.org/couchdb/HTTP_Do
345          }          }
346    
347          $tx->res->code( $status );          $tx->res->code( $status );
348          $tx->res->headers->content_type( 'text/json' );          $tx->res->headers->content_type( 'text/plain;charset=utf-8' );
349          my $body = to_json $json;          my $body = to_json $json;
350          $tx->res->body( $body );          $tx->res->body( $body );
351          warn "CouchDB API: $method $url $status $body\n";          $tx->res->headers->add_line( 'Cache-Control' => 'must-revalidate' );
352            $tx->res->headers->add_line( 'Server' => "Frey::CouchAPI/$VERSION" );
353    
354            print "$method $url $status\n$body\n";
355    
356          warn "## headers ", $tx->res->headers->to_string;          warn "## headers ", $tx->res->headers->to_string;
357    
# Line 288  L<http://wiki.apache.org/couchdb/HTTP_Do Line 361  L<http://wiki.apache.org/couchdb/HTTP_Do
361    
362  sub database_get {  sub database_get {
363          my ($db_name) = @_;          my ($db_name) = @_;
364          my $path = $config->{path};          my $path = $config->{database}->{path} || die;
365          warn "# collecting docs from $path/$db_name/*\n";          warn "# collecting docs from $path/$db_name/*\n";
366          my @docs = glob "$path/$db_name/*";          my @docs = glob "$path/$db_name/*";
367          my $json = {          my $json = {

Legend:
Removed from v.1052  
changed lines
  Added in v.1071

  ViewVC Help
Powered by ViewVC 1.1.26