final versions of Route caching functions
[spider.git] / perl / Route / User.pm
index 8c1c824de5f58d4bf5e389aee4b40d675f259c65..bbd289d292755a0bf89cf3041b0d152d68f21bcf 100644 (file)
@@ -11,6 +11,8 @@ package Route::User;
 use DXDebug;
 use Route;
 use DXUtil;
+use DXJSON;
+use Time::HiRes qw(gettimeofday);
 
 use strict;
 
@@ -21,6 +23,8 @@ $filterdef = $Route::filterdef;
 %list = ();
 $max = 0;
 
+our $cachefn = localdata('route_user_cache');
+
 sub count
 {
        my $n = scalar(keys %list);
@@ -94,6 +98,37 @@ sub delparent
     return $self->_dellist('parent', @_);
 }
 
+sub TO_JSON { return { %{ shift() } }; }
+
+sub write_cache
+{
+       my $json = DXJSON->new;
+       $json->canonical(isdbg('routecache'));
+       
+       my $ta = [ gettimeofday ];
+       my @s;
+       eval {
+               while (my ($k, $v) = each  %list) {
+                   push @s, "$k:" . $json->encode($v) . "\n";
+           }
+       };
+       if (!$@ && @s) {
+               my $fh = IO::File->new(">$cachefn") or confess("writing $cachefn $!");
+               if (isdbg("routecache")) {
+                       $fh->print(sort @s);
+               }
+               else {
+                       $fh->print(@s);
+               }
+               $fh->close;
+       } else {
+               dbg("Route::User:Write_cache error '$@'");
+               return;
+       }
+       my $diff = _diffms($ta);
+       dbg("Route::User:WRITE_CACHE time to write: $diff mS");
+}
+
 #
 # generic AUTOLOAD for accessors
 #