1 use strict; use warnings;
2 package OpenILS::Utils::CStoreEditor;
3 use OpenILS::Application::AppUtils;
4 use OpenSRF::AppSession;
5 use OpenSRF::EX qw(:try);
6 use OpenILS::Utils::Fieldmapper;
9 use OpenSRF::Utils::JSON;
10 use OpenSRF::Utils::Logger qw($logger);
11 my $U = "OpenILS::Application::AppUtils";
20 # 'biblio.record_entry' => { update => 'UPDATE_MARC' },
21 # 'asset.copy' => { update => 'UPDATE_COPY'},
22 # 'asset.call_number' => { update => 'UPDATE_VOLUME'},
23 # 'action.circulation' => { retrieve => 'VIEW_CIRCULATIONS'},
26 sub flush_forced_xacts {
27 for my $k ( keys %xact_ed_cache ) {
29 $xact_ed_cache{$k}->rollback;
33 delete $xact_ed_cache{$k};
37 # -----------------------------------------------------------------------------
38 # Export some useful functions
39 # -----------------------------------------------------------------------------
40 use vars qw(@EXPORT_OK %EXPORT_TAGS);
42 use base qw/Exporter/;
43 push @EXPORT_OK, ( 'new_editor', 'new_rstore_editor' );
44 %EXPORT_TAGS = ( funcs => [ qw/ new_editor new_rstore_editor / ] );
46 sub new_editor { return OpenILS::Utils::CStoreEditor->new(@_); }
48 sub new_rstore_editor {
49 my $e = OpenILS::Utils::CStoreEditor->new(@_);
50 $e->app('open-ils.reporter-store');
55 # -----------------------------------------------------------------------------
57 # -----------------------------------------------------------------------------
58 use constant E => 'error';
59 use constant W => 'warn';
60 use constant I => 'info';
61 use constant D => 'debug';
62 use constant A => 'activity';
66 # -----------------------------------------------------------------------------
68 # xact=><true> : creates a storage transaction
69 # authtoken=>$token : the login session key
70 # -----------------------------------------------------------------------------
72 my( $class, %params ) = @_;
73 $class = ref($class) || $class;
74 my $self = bless( \%params, $class );
75 $self->{checked_perms} = {};
86 my( $self, $app ) = @_;
87 $self->{app} = $app if $app;
88 $self->{app} = 'open-ils.cstore' unless $self->{app};
93 # -----------------------------------------------------------------------------
94 # Log the editor metadata along with the log string
95 # -----------------------------------------------------------------------------
97 my( $self, $lev, $str ) = @_;
101 } elsif ($self->{xact}) {
106 $s .= "0" unless $self->requestor;
107 $s .= $self->requestor->id if $self->requestor;
109 $logger->$lev("$s $str");
112 # -----------------------------------------------------------------------------
113 # Verifies the auth token and fetches the requestor object
114 # -----------------------------------------------------------------------------
117 $self->log(D, "checking auth token ".$self->authtoken);
119 my $content = $U->simplereq(
121 'open-ils.auth.session.retrieve', $self->authtoken, 1);
123 if(!$content or $U->event_code($content)) {
124 $self->event( ($content) ? $content : OpenILS::Event->new('NO_SESSION'));
128 $self->{authtime} = $content->{authtime};
129 return $self->{requestor} = $content->{userobj};
135 $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
136 $self->log(D, "checking cached auth token ".$self->authtoken);
137 my $user = $cache->get_cache("oils_auth_".$self->authtoken);
138 return $self->{requestor} = $user->{userobj} if $user;
139 $self->event(OpenILS::Event->new('NO_SESSION'));
145 # -----------------------------------------------------------------------------
146 # Returns the last generated event
147 # -----------------------------------------------------------------------------
149 my( $self, $evt ) = @_;
150 $self->{event} = $evt if $evt;
151 return $self->{event};
154 # -----------------------------------------------------------------------------
155 # Destroys the transaction and disconnects where necessary,
156 # then returns the last event that occurred
157 # -----------------------------------------------------------------------------
168 # -----------------------------------------------------------------------------
169 # Clears the last caught event
170 # -----------------------------------------------------------------------------
173 $self->{event} = undef;
177 my($self, $died) = @_;
178 $self->{died} = $died if defined $died;
179 return $self->{died};
183 my( $self, $auth ) = @_;
184 $self->{authtoken} = $auth if $auth;
185 return $self->{authtoken};
189 my( $self, $auth ) = @_;
190 $self->{authtime} = $auth if $auth;
191 return $self->{authtime};
196 $self->{timeout} = $to if defined $to;
197 return defined($self->{timeout}) ? $self->{timeout} : 60;
200 # -----------------------------------------------------------------------------
201 # fetches the session, creating if necessary. If 'xact' is true on this
202 # object, a db session is created
203 # -----------------------------------------------------------------------------
205 my( $self, $session ) = @_;
206 $self->{session} = $session if $session;
208 if(!$self->{session}) {
209 $self->{session} = OpenSRF::AppSession->create($self->app);
211 if( ! $self->{session} ) {
212 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
214 throw OpenSRF::EX::ERROR ($str);
217 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
218 $self->xact_begin if $self->{xact} or $always_xact;
221 $xact_ed_cache{$self->{xact_id}} = $self if $always_xact and $self->{xact_id};
222 return $self->{session};
226 # -----------------------------------------------------------------------------
227 # Starts a storage transaction
228 # -----------------------------------------------------------------------------
231 return $self->{xact_id} if $self->{xact_id};
232 $self->session->connect unless $self->session->state == OpenSRF::AppSession::CONNECTED();
233 $self->log(D, "starting new database transaction");
234 unless($self->{xact_id}) {
235 my $stat = $self->request($self->app . '.transaction.begin');
236 $self->log(E, "error starting database transaction") unless $stat;
237 $self->{xact_id} = $stat;
240 return $self->{xact_id};
243 # -----------------------------------------------------------------------------
244 # Commits a storage transaction
245 # -----------------------------------------------------------------------------
248 return unless $self->{xact_id};
249 $self->log(D, "comitting db session");
250 my $stat = $self->request($self->app.'.transaction.commit');
251 $self->log(E, "error comitting database transaction") unless $stat;
252 delete $self->{xact_id};
253 delete $self->{xact};
257 # -----------------------------------------------------------------------------
258 # Rolls back a storage stransaction
259 # -----------------------------------------------------------------------------
262 return unless $self->{session} and $self->{xact_id};
263 $self->log(I, "rolling back db session");
264 my $stat = $self->request($self->app.".transaction.rollback");
265 $self->log(E, "error rolling back database transaction") unless $stat;
266 delete $self->{xact_id};
267 delete $self->{xact};
272 # -----------------------------------------------------------------------------
273 # Savepoint functions. If no savepoint name is provided, the same name is used
274 # for each successive savepoint, in which case only the last savepoint set can
275 # be released or rolled back.
276 # -----------------------------------------------------------------------------
279 my $name = shift || 'savepoint';
280 return unless $self->{session} and $self->{xact_id};
281 $self->log(I, "setting savepoint '$name'");
282 my $stat = $self->request($self->app.".savepoint.set", $name)
283 or $self->log(E, "error setting savepoint '$name'");
287 sub release_savepoint {
289 my $name = shift || 'savepoint';
290 return unless $self->{session} and $self->{xact_id};
291 $self->log(I, "releasing savepoint '$name'");
292 my $stat = $self->request($self->app.".savepoint.release", $name)
293 or $self->log(E, "error releasing savepoint '$name'");
297 sub rollback_savepoint {
299 my $name = shift || 'savepoint';
300 return unless $self->{session} and $self->{xact_id};
301 $self->log(I, "rollback savepoint '$name'");
302 my $stat = $self->request($self->app.".savepoint.rollback", $name)
303 or $self->log(E, "error rolling back savepoint '$name'");
308 # -----------------------------------------------------------------------------
309 # Rolls back the transaction and disconnects
310 # -----------------------------------------------------------------------------
316 $self->xact_rollback;
320 $ret = $self->disconnect
322 throw $err if ($err);
328 $self->session->disconnect if
330 $self->{session}->state == OpenSRF::AppSession::CONNECTED();
331 delete $self->{session};
335 # -----------------------------------------------------------------------------
336 # commits the db session and destroys the session
337 # returns the status of the commit call
338 # -----------------------------------------------------------------------------
341 return unless $self->{xact_id};
342 my $stat = $self->xact_commit;
347 # -----------------------------------------------------------------------------
348 # clears all object data. Does not commit the db transaction.
349 # -----------------------------------------------------------------------------
353 $$self{$_} = undef for (keys %$self);
357 # -----------------------------------------------------------------------------
359 # -----------------------------------------------------------------------------
371 throw $err if ($err);
377 # -----------------------------------------------------------------------------
378 # Does a simple storage request
379 # -----------------------------------------------------------------------------
381 my( $self, $method, @params ) = @_;
385 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
386 my $locale = $self->session->session_locale;
388 $self->log(I, "request $locale $method $argstr");
390 if( ($self->{xact} or $always_xact) and
391 $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
392 #$logger->error("CStoreEditor lost it's connection!!");
393 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
399 my $req = $self->session->request($method, @params);
401 if($self->substream) {
402 $self->log(D,"running in substream mode");
404 while( my $resp = $req->recv(timeout => $self->timeout) ) {
405 push(@$val, $resp->content) if $resp->content and not $self->discard;
409 my $resp = $req->recv(timeout => $self->timeout);
412 $self->log(E, "request error $method : $argstr : $err");
414 $val = $resp->content if $resp;
422 $self->log(E, "request error $method : $argstr : $err");
430 my( $self, $bool ) = @_;
431 $self->{substream} = $bool if defined $bool;
432 return $self->{substream};
435 # -----------------------------------------------------------------------------
436 # discard response data instead of returning it to the caller. currently only
437 # works in conjunction with substream mode.
438 # -----------------------------------------------------------------------------
440 my( $self, $bool ) = @_;
441 $self->{discard} = $bool if defined $bool;
442 return $self->{discard};
446 # -----------------------------------------------------------------------------
447 # Sets / Returns the requestor object. This is set when checkauth succeeds.
448 # -----------------------------------------------------------------------------
450 my($self, $requestor) = @_;
451 $self->{requestor} = $requestor if $requestor;
452 return $self->{requestor};
457 # -----------------------------------------------------------------------------
458 # Holds the last data received from a storage call
459 # -----------------------------------------------------------------------------
461 my( $self, $data ) = @_;
462 $self->{data} = $data if defined $data;
463 return $self->{data};
467 # -----------------------------------------------------------------------------
468 # True if this perm has already been checked at this org
469 # -----------------------------------------------------------------------------
471 my( $self, $perm, $org ) = @_;
472 $self->{checked_perms}->{$org} = {}
473 unless $self->{checked_perms}->{$org};
474 my $checked = $self->{checked_perms}->{$org}->{$perm};
476 $self->{checked_perms}->{$org}->{$perm} = 1;
484 # -----------------------------------------------------------------------------
485 # Returns true if the requested perm is allowed. If the perm check fails,
486 # $e->event is set and undef is returned
487 # The perm user is $e->requestor->id and perm org defaults to the requestor's
489 # if perm is an array of perms, method will return true at the first allowed
490 # permission. If none of the perms are allowed, the perm_failure event
491 # is created with the last perm to fail
492 # -----------------------------------------------------------------------------
496 transform => 'permission.usr_has_perm',
506 my $OBJECT_PERM_QUERY = {
509 transform => 'permission.usr_has_object_perm',
520 my( $self, $perm, $org, $object, $hint ) = @_;
521 my $uid = $self->requestor->id;
522 $org ||= $self->requestor->ws_ou;
524 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
526 for $perm (@$perms) {
527 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
532 # determine the ID field and json_hint from the object
533 my $id_field = $object->Identity;
534 $params = [$perm, $object->json_hint, $object->$id_field];
536 # we were passed an object-id and json_hint
537 $params = [$perm, $hint, $object];
539 push(@$params, $org) if $org;
540 $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
541 $OBJECT_PERM_QUERY->{where}->{id} = $uid;
542 return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
545 $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
546 $PERM_QUERY->{where}->{id} = $uid;
547 return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
551 # set the perm failure event if the permission check returned false
552 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
558 # -----------------------------------------------------------------------------
559 # Returns the list of object IDs this user has object-specific permissions for
560 # -----------------------------------------------------------------------------
561 sub objects_allowed {
562 my($self, $perm, $obj_type) = @_;
564 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
567 for $perm (@$perms) {
569 select => {puopm => ['object_id']},
572 ppl => {field => 'id',fkey => 'perm'}
576 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
577 '+ppl' => {code => $perm}
581 my $list = $self->json_query($query);
582 push(@ids, 0+$_->{object_id}) for @$list;
586 $trim{$_} = 1 for @ids;
587 return [ keys %trim ];
591 # -----------------------------------------------------------------------------
592 # checks the appropriate perm for the operation
593 # -----------------------------------------------------------------------------
595 my( $self, $ptype, $action, $org ) = @_;
596 $org ||= $self->requestor->ws_ou;
597 my $perm = $PERMS{$ptype}{$action};
599 return undef if $self->perm_checked($perm, $org);
600 return $self->event unless $self->allowed($perm, $org);
602 $self->log(I, "no perm provided for $ptype.$action");
609 # -----------------------------------------------------------------------------
610 # Logs update actions to the activity log
611 # -----------------------------------------------------------------------------
613 my( $self, $type, $action, $arg ) = @_;
614 my $str = "$type.$action";
615 $str .= _prop_string($arg);
623 my @props = $obj->properties;
626 my $prop = $obj->$_() || "";
627 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
634 sub __arg_to_string {
636 return "" unless defined $arg;
637 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
638 my $idf = $arg->Identity;
639 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
641 return OpenSRF::Utils::JSON->perl2JSON($arg);
646 # -----------------------------------------------------------------------------
647 # This does the actual storage query.
649 # 'search' calls become search_where calls and $arg can be a search hash or
650 # an array-ref of storage search options.
652 # 'retrieve' expects an id
653 # 'update' expects an object
654 # 'create' expects an object
655 # 'delete' expects an object
657 # All methods return true on success and undef on failure. On failure,
658 # $e->event is set to the generated event.
659 # Note: this method assumes that updating a non-changed object and
660 # thereby receiving a 0 from storage, is a successful update.
662 # The method will therefore return true so the caller can just do
663 # $e->update_blah($x) or return $e->event;
664 # The true value returned from storage for all methods will be stored in
665 # $e->data, until the next method is called.
667 # not-found events are generated on retrieve and serach methods.
668 # action=search methods will return [] (==true) if no data is found. If the
669 # caller is interested in the not found event, they can do:
670 # return $e->event unless @$results;
671 # -----------------------------------------------------------------------------
673 my( $self, $action, $type, $arg, $options ) = @_;
677 if( $action eq 'retrieve' ) {
678 if(! defined($arg) ) {
679 $self->log(W,"$action $type called with no ID...");
680 $self->event(_mk_not_found($type, $arg));
682 } elsif( ref($arg) =~ /Fieldmapper/ ) {
683 $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
684 my $idf = $arg->Identity;
689 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
690 my $method = $self->app.".direct.$type.$action";
692 if( $action eq 'search' ) {
693 $method .= '.atomic';
695 } elsif( $action eq 'batch_retrieve' ) {
697 @arg = ( { id => $arg } );
698 $method =~ s/batch_retrieve/search/o;
699 $method .= '.atomic';
701 } elsif( $action eq 'retrieve_all' ) {
703 $method =~ s/retrieve_all/search/o;
706 my $fmobj = "Fieldmapper::$tt";
707 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
708 $method .= '.atomic';
711 $method =~ s/search/id_list/o if $options->{idlist};
713 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
714 $self->timeout($$options{timeout});
715 $self->discard($$options{discard});
717 # remove any stale events
720 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
721 if(!($self->{xact} or $always_xact)) {
722 $logger->error("Attempt to update DB while not in a transaction : $method");
723 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
725 $self->log_activity($type, $action, $arg);
728 if($$options{checkperm}) {
729 my $a = ($action eq 'search') ? 'retrieve' : $action;
730 my $e = $self->_checkperm($type, $a, $$options{permorg});
741 $obj = $self->request($method, @arg);
742 } catch Error with { $err = shift; };
746 $self->log(I, "request returned no data : $method");
748 if( $action eq 'retrieve' ) {
749 $self->event(_mk_not_found($type, $arg));
751 } elsif( $action eq 'update' or
752 $action eq 'delete' or $action eq 'create' ) {
753 my $evt = OpenILS::Event->new(
754 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
760 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
761 payload => $arg, debug => "$err" ));
768 if( $action eq 'create' and $obj == 0 ) {
769 my $evt = OpenILS::Event->new(
770 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
775 # If we havn't dealt with the error in a nice way, go ahead and throw it
778 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
779 payload => $arg, debug => "$err" ));
783 if( $action eq 'search' ) {
784 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
785 $self->event(_mk_not_found($type, $arg)) unless @$obj;
788 if( $action eq 'create' ) {
789 my $idf = $obj->Identity;
790 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
791 $arg->$idf($obj->$idf);
794 $self->data($obj); # cache the data for convenience
796 return ($obj) ? $obj : 1;
801 my( $type, $arg ) = @_;
802 (my $t = $type) =~ s/\./_/og;
804 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
809 # utility method for loading
813 $str =~ s/Fieldmapper:://o;
819 # -------------------------------------------------------------
820 # Load up the methods from the FM classes
821 # -------------------------------------------------------------
824 no warnings; # Here we potentially redefine subs via eval
825 my $map = $Fieldmapper::fieldmap;
826 for my $object (keys %$map) {
827 my $obj = __fm2meth($object, '_');
828 my $type = __fm2meth($object, '.');
829 foreach my $command (qw/ update retrieve search create delete batch_retrieve retrieve_all /) {
830 eval "sub ${command}_$obj {return shift()->runmethod('$command', '$type', \@_);}\n";
832 # TODO: performance test against concatenating a big string of all the subs and eval'ing only ONCE.
836 init(); # Add very many subs to this namespace
839 my( $self, $arg, $options ) = @_;
841 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
842 my $method = $self->app.'.json_query.atomic';
843 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
845 $self->timeout($$options{timeout});
846 $self->discard($$options{discard});
852 $obj = $self->request($method, @arg);
853 } catch Error with { $err = shift; };
857 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
858 payload => $arg, debug => "$err" ));
862 $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));