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);
118 my ($reqr, $evt) = $U->checkses($self->authtoken);
119 $self->event($evt) if $evt;
120 return $self->{requestor} = $reqr;
127 $cache = OpenSRF::Utils::Cache->new('global') unless $cache;
128 $self->log(D, "checking cached auth token ".$self->authtoken);
129 my $user = $cache->get_cache("oils_auth_".$self->authtoken);
130 return $self->{requestor} = $user->{userobj} if $user;
131 $self->event(OpenILS::Event->new('NO_SESSION'));
137 # -----------------------------------------------------------------------------
138 # Returns the last generated event
139 # -----------------------------------------------------------------------------
141 my( $self, $evt ) = @_;
142 $self->{event} = $evt if $evt;
143 return $self->{event};
146 # -----------------------------------------------------------------------------
147 # Destroys the transaction and disconnects where necessary,
148 # then returns the last event that occurred
149 # -----------------------------------------------------------------------------
158 # -----------------------------------------------------------------------------
159 # Clears the last caught event
160 # -----------------------------------------------------------------------------
163 $self->{event} = undef;
167 my($self, $died) = @_;
168 $self->{died} = $died if defined $died;
169 return $self->{died};
173 my( $self, $auth ) = @_;
174 $self->{authtoken} = $auth if $auth;
175 return $self->{authtoken};
180 $self->{timeout} = $to if defined $to;
181 return defined($self->{timeout}) ? $self->{timeout} : 60;
184 # -----------------------------------------------------------------------------
185 # fetches the session, creating if necessary. If 'xact' is true on this
186 # object, a db session is created
187 # -----------------------------------------------------------------------------
189 my( $self, $session ) = @_;
190 $self->{session} = $session if $session;
192 if(!$self->{session}) {
193 $self->{session} = OpenSRF::AppSession->create($self->app);
195 if( ! $self->{session} ) {
196 my $str = "Error creating cstore session with OpenSRF::AppSession->create()!";
198 throw OpenSRF::EX::ERROR ($str);
201 $self->{session}->connect if $self->{xact} or $self->{connect} or $always_xact;
202 $self->xact_begin if $self->{xact} or $always_xact;
205 $xact_ed_cache{$self->{xact_id}} = $self if $always_xact and $self->{xact_id};
206 return $self->{session};
210 # -----------------------------------------------------------------------------
211 # Starts a storage transaction
212 # -----------------------------------------------------------------------------
215 return $self->{xact_id} if $self->{xact_id};
216 $self->session->connect unless $self->session->state == OpenSRF::AppSession::CONNECTED();
217 $self->log(D, "starting new database transaction");
218 unless($self->{xact_id}) {
219 my $stat = $self->request($self->app . '.transaction.begin');
220 $self->log(E, "error starting database transaction") unless $stat;
221 $self->{xact_id} = $stat;
224 return $self->{xact_id};
227 # -----------------------------------------------------------------------------
228 # Commits a storage transaction
229 # -----------------------------------------------------------------------------
232 return unless $self->{xact_id};
233 $self->log(D, "comitting db session");
234 my $stat = $self->request($self->app.'.transaction.commit');
235 $self->log(E, "error comitting database transaction") unless $stat;
236 delete $self->{xact_id};
237 delete $self->{xact};
241 # -----------------------------------------------------------------------------
242 # Rolls back a storage stransaction
243 # -----------------------------------------------------------------------------
246 return unless $self->{session} and $self->{xact_id};
247 $self->log(I, "rolling back db session");
248 my $stat = $self->request($self->app.".transaction.rollback");
249 $self->log(E, "error rolling back database transaction") unless $stat;
250 delete $self->{xact_id};
251 delete $self->{xact};
256 # -----------------------------------------------------------------------------
257 # Savepoint functions. If no savepoint name is provided, the same name is used
258 # for each successive savepoint, in which case only the last savepoint set can
259 # be released or rolled back.
260 # -----------------------------------------------------------------------------
263 my $name = shift || 'savepoint';
264 return unless $self->{session} and $self->{xact_id};
265 $self->log(I, "setting savepoint '$name'");
266 my $stat = $self->request($self->app.".savepoint.set", $name)
267 or $self->log(E, "error setting savepoint '$name'");
271 sub release_savepoint {
273 my $name = shift || 'savepoint';
274 return unless $self->{session} and $self->{xact_id};
275 $self->log(I, "releasing savepoint '$name'");
276 my $stat = $self->request($self->app.".savepoint.release", $name)
277 or $self->log(E, "error releasing savepoint '$name'");
281 sub rollback_savepoint {
283 my $name = shift || 'savepoint';
284 return unless $self->{session} and $self->{xact_id};
285 $self->log(I, "rollback savepoint '$name'");
286 my $stat = $self->request($self->app.".savepoint.rollback", $name)
287 or $self->log(E, "error rolling back savepoint '$name'");
292 # -----------------------------------------------------------------------------
293 # Rolls back the transaction and disconnects
294 # -----------------------------------------------------------------------------
297 $self->xact_rollback;
303 $self->session->disconnect if
305 $self->{session}->state == OpenSRF::AppSession::CONNECTED();
306 delete $self->{session};
310 # -----------------------------------------------------------------------------
311 # commits the db session and destroys the session
312 # returns the status of the commit call
313 # -----------------------------------------------------------------------------
316 return unless $self->{xact_id};
317 my $stat = $self->xact_commit;
322 # -----------------------------------------------------------------------------
323 # clears all object data. Does not commit the db transaction.
324 # -----------------------------------------------------------------------------
328 $$self{$_} = undef for (keys %$self);
332 # -----------------------------------------------------------------------------
334 # -----------------------------------------------------------------------------
343 # -----------------------------------------------------------------------------
344 # Does a simple storage request
345 # -----------------------------------------------------------------------------
347 my( $self, $method, @params ) = @_;
351 my $argstr = __arg_to_string( (scalar(@params)) == 1 ? $params[0] : \@params);
352 my $locale = $self->session->session_locale;
354 $self->log(I, "request $locale $method $argstr");
356 if( ($self->{xact} or $always_xact) and
357 $self->session->state != OpenSRF::AppSession::CONNECTED() ) {
358 #$logger->error("CStoreEditor lost it's connection!!");
359 throw OpenSRF::EX::ERROR ("CStore connection timed out - transaction cannot continue");
365 my $req = $self->session->request($method, @params);
367 if($self->substream) {
368 $self->log(D,"running in substream mode");
370 while( my $resp = $req->recv(timeout => $self->timeout) ) {
371 push(@$val, $resp->content) if $resp->content and not $self->discard;
375 my $resp = $req->recv(timeout => $self->timeout);
378 $self->log(E, "request error $method : $argstr : $err");
380 $val = $resp->content if $resp;
388 $self->log(E, "request error $method : $argstr : $err");
396 my( $self, $bool ) = @_;
397 $self->{substream} = $bool if defined $bool;
398 return $self->{substream};
401 # -----------------------------------------------------------------------------
402 # discard response data instead of returning it to the caller. currently only
403 # works in conjunction with substream mode.
404 # -----------------------------------------------------------------------------
406 my( $self, $bool ) = @_;
407 $self->{discard} = $bool if defined $bool;
408 return $self->{discard};
412 # -----------------------------------------------------------------------------
413 # Sets / Returns the requestor object. This is set when checkauth succeeds.
414 # -----------------------------------------------------------------------------
416 my($self, $requestor) = @_;
417 $self->{requestor} = $requestor if $requestor;
418 return $self->{requestor};
423 # -----------------------------------------------------------------------------
424 # Holds the last data received from a storage call
425 # -----------------------------------------------------------------------------
427 my( $self, $data ) = @_;
428 $self->{data} = $data if defined $data;
429 return $self->{data};
433 # -----------------------------------------------------------------------------
434 # True if this perm has already been checked at this org
435 # -----------------------------------------------------------------------------
437 my( $self, $perm, $org ) = @_;
438 $self->{checked_perms}->{$org} = {}
439 unless $self->{checked_perms}->{$org};
440 my $checked = $self->{checked_perms}->{$org}->{$perm};
442 $self->{checked_perms}->{$org}->{$perm} = 1;
450 # -----------------------------------------------------------------------------
451 # Returns true if the requested perm is allowed. If the perm check fails,
452 # $e->event is set and undef is returned
453 # The perm user is $e->requestor->id and perm org defaults to the requestor's
455 # if perm is an array of perms, method will return true at the first allowed
456 # permission. If none of the perms are allowed, the perm_failure event
457 # is created with the last perm to fail
458 # -----------------------------------------------------------------------------
462 transform => 'permission.usr_has_perm',
472 my $OBJECT_PERM_QUERY = {
475 transform => 'permission.usr_has_object_perm',
486 my( $self, $perm, $org, $object, $hint ) = @_;
487 my $uid = $self->requestor->id;
488 $org ||= $self->requestor->ws_ou;
490 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
492 for $perm (@$perms) {
493 $self->log(I, "checking perms user=$uid, org=$org, perm=$perm");
498 # determine the ID field and json_hint from the object
499 my $id_field = $object->Identity;
500 $params = [$perm, $object->json_hint, $object->$id_field];
502 # we were passed an object-id and json_hint
503 $params = [$perm, $hint, $object];
505 push(@$params, $org) if $org;
506 $OBJECT_PERM_QUERY->{select}->{au}->[0]->{params} = $params;
507 $OBJECT_PERM_QUERY->{where}->{id} = $uid;
508 return 1 if $U->is_true($self->json_query($OBJECT_PERM_QUERY)->[0]->{has_perm});
511 $PERM_QUERY->{select}->{au}->[0]->{params} = [$perm, $org];
512 $PERM_QUERY->{where}->{id} = $uid;
513 return 1 if $U->is_true($self->json_query($PERM_QUERY)->[0]->{has_perm});
517 # set the perm failure event if the permission check returned false
518 my $e = OpenILS::Event->new('PERM_FAILURE', ilsperm => $perm, ilspermloc => $org);
524 # -----------------------------------------------------------------------------
525 # Returns the list of object IDs this user has object-specific permissions for
526 # -----------------------------------------------------------------------------
527 sub objects_allowed {
528 my($self, $perm, $obj_type) = @_;
530 my $perms = (ref($perm) eq 'ARRAY') ? $perm : [$perm];
533 for $perm (@$perms) {
535 select => {puopm => ['object_id']},
538 ppl => {field => 'id',fkey => 'perm'}
542 '+puopm' => {usr => $self->requestor->id, object_type => $obj_type},
543 '+ppl' => {code => $perm}
547 my $list = $self->json_query($query);
548 push(@ids, 0+$_->{object_id}) for @$list;
552 $trim{$_} = 1 for @ids;
553 return [ keys %trim ];
557 # -----------------------------------------------------------------------------
558 # checks the appropriate perm for the operation
559 # -----------------------------------------------------------------------------
561 my( $self, $ptype, $action, $org ) = @_;
562 $org ||= $self->requestor->ws_ou;
563 my $perm = $PERMS{$ptype}{$action};
565 return undef if $self->perm_checked($perm, $org);
566 return $self->event unless $self->allowed($perm, $org);
568 $self->log(I, "no perm provided for $ptype.$action");
575 # -----------------------------------------------------------------------------
576 # Logs update actions to the activity log
577 # -----------------------------------------------------------------------------
579 my( $self, $type, $action, $arg ) = @_;
580 my $str = "$type.$action";
581 $str .= _prop_string($arg);
589 my @props = $obj->properties;
592 my $prop = $obj->$_() || "";
593 $prop = substr($prop, 0, 128) . "..." if length $prop > 131;
600 sub __arg_to_string {
602 return "" unless defined $arg;
603 if( UNIVERSAL::isa($arg, "Fieldmapper") ) {
604 my $idf = $arg->Identity;
605 return (defined $arg->$idf) ? $arg->$idf : '<new object>';
607 return OpenSRF::Utils::JSON->perl2JSON($arg);
612 # -----------------------------------------------------------------------------
613 # This does the actual storage query.
615 # 'search' calls become search_where calls and $arg can be a search hash or
616 # an array-ref of storage search options.
618 # 'retrieve' expects an id
619 # 'update' expects an object
620 # 'create' expects an object
621 # 'delete' expects an object
623 # All methods return true on success and undef on failure. On failure,
624 # $e->event is set to the generated event.
625 # Note: this method assumes that updating a non-changed object and
626 # thereby receiving a 0 from storage, is a successful update.
628 # The method will therefore return true so the caller can just do
629 # $e->update_blah($x) or return $e->event;
630 # The true value returned from storage for all methods will be stored in
631 # $e->data, until the next method is called.
633 # not-found events are generated on retrieve and serach methods.
634 # action=search methods will return [] (==true) if no data is found. If the
635 # caller is interested in the not found event, they can do:
636 # return $e->event unless @$results;
637 # -----------------------------------------------------------------------------
639 my( $self, $action, $type, $arg, $options ) = @_;
643 if( $action eq 'retrieve' ) {
644 if(! defined($arg) ) {
645 $self->log(W,"$action $type called with no ID...");
646 $self->event(_mk_not_found($type, $arg));
648 } elsif( ref($arg) =~ /Fieldmapper/ ) {
649 $self->log(D,"$action $type called with an object.. attempting Identity retrieval..");
650 my $idf = $arg->Identity;
655 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
656 my $method = $self->app.".direct.$type.$action";
658 if( $action eq 'search' ) {
659 $method .= '.atomic';
661 } elsif( $action eq 'batch_retrieve' ) {
663 @arg = ( { id => $arg } );
664 $method =~ s/batch_retrieve/search/o;
665 $method .= '.atomic';
667 } elsif( $action eq 'retrieve_all' ) {
669 $method =~ s/retrieve_all/search/o;
672 my $fmobj = "Fieldmapper::$tt";
673 @arg = ( { $fmobj->Identity => { '!=' => undef } } );
674 $method .= '.atomic';
677 $method =~ s/search/id_list/o if $options->{idlist};
679 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
680 $self->timeout($$options{timeout});
681 $self->discard($$options{discard});
683 # remove any stale events
686 if( $action eq 'update' or $action eq 'delete' or $action eq 'create' ) {
687 if(!($self->{xact} or $always_xact)) {
688 $logger->error("Attempt to update DB while not in a transaction : $method");
689 throw OpenSRF::EX::ERROR ("Attempt to update DB while not in a transaction : $method");
691 $self->log_activity($type, $action, $arg);
694 if($$options{checkperm}) {
695 my $a = ($action eq 'search') ? 'retrieve' : $action;
696 my $e = $self->_checkperm($type, $a, $$options{permorg});
707 $obj = $self->request($method, @arg);
708 } catch Error with { $err = shift; };
712 $self->log(I, "request returned no data : $method");
714 if( $action eq 'retrieve' ) {
715 $self->event(_mk_not_found($type, $arg));
717 } elsif( $action eq 'update' or
718 $action eq 'delete' or $action eq 'create' ) {
719 my $evt = OpenILS::Event->new(
720 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
726 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
727 payload => $arg, debug => "$err" ));
734 if( $action eq 'create' and $obj == 0 ) {
735 my $evt = OpenILS::Event->new(
736 'DATABASE_UPDATE_FAILED', payload => $arg, debug => "$err" );
741 # If we havn't dealt with the error in a nice way, go ahead and throw it
744 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
745 payload => $arg, debug => "$err" ));
749 if( $action eq 'search' ) {
750 $self->log(I, "$type.$action : returned ".scalar(@$obj). " result(s)");
751 $self->event(_mk_not_found($type, $arg)) unless @$obj;
754 if( $action eq 'create' ) {
755 my $idf = $obj->Identity;
756 $self->log(I, "created a new $type object with Identity " . $obj->$idf);
757 $arg->$idf($obj->$idf);
760 $self->data($obj); # cache the data for convenience
762 return ($obj) ? $obj : 1;
767 my( $type, $arg ) = @_;
768 (my $t = $type) =~ s/\./_/og;
770 return OpenILS::Event->new("${t}_NOT_FOUND", payload => $arg);
775 # utility method for loading
779 $str =~ s/Fieldmapper:://o;
785 # -------------------------------------------------------------
786 # Load up the methods from the FM classes
787 # -------------------------------------------------------------
790 no warnings; # Here we potentially redefine subs via eval
791 my $map = $Fieldmapper::fieldmap;
792 for my $object (keys %$map) {
793 my $obj = __fm2meth($object, '_');
794 my $type = __fm2meth($object, '.');
795 foreach my $command (qw/ update retrieve search create delete batch_retrieve retrieve_all /) {
796 eval "sub ${command}_$obj {return shift()->runmethod('$command', '$type', \@_);}\n";
798 # TODO: performance test against concatenating a big string of all the subs and eval'ing only ONCE.
802 init(); # Add very many subs to this namespace
805 my( $self, $arg, $options ) = @_;
807 my @arg = ( ref($arg) eq 'ARRAY' ) ? @$arg : ($arg);
808 my $method = $self->app.'.json_query.atomic';
809 $method =~ s/\.atomic$//o if $self->substream($$options{substream} || 0);
811 $self->timeout($$options{timeout});
812 $self->discard($$options{discard});
818 $obj = $self->request($method, @arg);
819 } catch Error with { $err = shift; };
823 OpenILS::Event->new( 'DATABASE_QUERY_FAILED',
824 payload => $arg, debug => "$err" ));
828 $self->log(I, "json_query : returned ".scalar(@$obj). " result(s)") if (ref($obj));