| RPC-XML documentation | Contained in the RPC-XML distribution. |
RPC::XML::Procedure - Object encapsulation of server-side RPC procedures
require RPC::XML::Procedure;
...
$method_1 = RPC::XML::Procedure->new({ name => 'system.identity',
code => sub { ... },
signature => [ 'string' ] });
$method_2 = RPC::XML::Procedure->new('/path/to/status.xpl');
This package is comprised of the code that was formerly RPC::XML::Method. The package was renamed when the decision was made to support procedures and methods as functionally different entities. It is not necessary to include both this module and RPC::XML::Method -- this module provides the latter as an empty subclass. In time, RPC::XML::Method will be removed from the distribution entirely.
The RPC::XML::Procedure package is designed primarily for behind-the-scenes
use by the RPC::XML::Server class and any subclasses of it. It is
documented here in case a project chooses to sub-class it for their purposes
(which would require setting the method_class attribute when creating
server objects, see RPC::XML::Server).
This package grew out of the increasing need to abstract the operations that related to the methods a given server instance was providing. Previously, methods were passed around simply as hash references. It was a small step then to move them into a package and allow for operations directly on the objects themselves. In the spirit of the original hashes, all the key data is kept in clear, intuitive hash keys (rather than obfuscated as the other classes do). Thus it is important to be clear on the interface here before sub-classing this package.
The following methods are provided by this class:
Creates a new object of the class, and returns a reference to it. The arguments to the constructor are variable in nature, depending on the type:
If there is exactly on argument that is not a reference, it is assumed to be a filename from which the method is to be loaded. This is presumed to be in the XPL format descibed below (see "XPL File Structure"). If the file cannot be opened, or if once opened cannot be parsed, an error is raised.
If there is exactly one argument that is a reference, it is assumed to be a hash with the relevant information on the same keys as the object itself uses. This is primarily to support backwards-compatibility to code written when methods were implemented simply as hash references.
If there is more than one argument in the list, then the list is assumed to be
a sort of "ersatz" hash construct, in that one of the keys (signature) is
allowed to occur multiple times. Otherwise, each of the following is allowed,
but may only occur once:
The name of the method, as it will be presented to clients
A reference to a subroutine, or an anonymous subroutine, that will receive calls for the method
(May appear more than once) Provides one calling-signature for the method, as either a space-separated string of types or a list-reference
The help-text for a method, which is generally used as a part of the introspection interface for a server
The version number/string for the method
A boolean (true or false) value indicating whether the method should be hidden from introspection and similar listings
Note that all of these correspond to the values that can be changed via the accessor methods detailed later.
If any error occurs during object creation, an error message is returned in lieu of the object reference.
Create a copy of the calling object, and return the new reference. All
elements are copied over cleanly, except for the code reference stored on the
code hash key. The clone will point to the same code reference as the
original. Elements such as signature are copied, so that changes to the
clone will not impact the original.
Returns the name by which the server is advertising the method. Unlike the next few accessors, this cannot be changed on an object. In order to streamline the managment of methods within the server classes, this must persist. However, the other elements may be used in the creation of a new object, which may then be added to the server, if the name absolutely must change.
If the procedure object was created from a file, or if the instantiation included namespace information, this accessor will return the namespace that the underlying code executes in. Otherwise, it returns an empty string. This cannot be altered (even if the code method is used to replace the code routine).
Returns or sets the code-reference that will receive calls as marshalled by the server. The existing value is lost, so if it must be preserved, then it should be retrieved prior to the new value being set.
Return a list reference containing the signatures, or set it. Each element of the list is a string of space-separated types (the first of which is the return type the method produces in that calling context). If this is being used to set the signature, then an array reference must be passed that contains one or more strings of this nature. Nested list references are not allowed at this level. If the new signatures would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is silently restored.
Returns or sets the help-text for the method. As with code, the previous value is lost.
Returns or sets the hidden status of the method. Setting it loses the previous value.
Returns or sets the version string for the method (overwriting as with the other accessors).
Returns a true/false value as to whether the object currently has enough content to be a valid method for a server to publish. This entails having at the very least a name, one or more signatures, and a code-reference to route the calls to. A server created from the classes in this software suite will not accept a method that is not valid.
Add one or more signatures (which may be a list reference or a string) to the internal tables for this method. Duplicate signatures are ignored. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned.
Deletes the signature or signatures (list reference or string) from the internal tables. Quietly ignores any signature that does not exist. If the new signature would cause a conflict (a case in which the same set of input types are specified for different output types), the old set is restored and an error message is returned.
Check that the passed-in signature is known to the method, and if so returns
the type that the method should be returning as a result of the call. Returns
a zero (0) otherwise. This differs from other signature operations in that the
passed-in signature (which may be a list-reference or a string) does not
include the return type. This method is provided so that servers may check a
list of arguments against type when marshalling an incoming call. For example,
a signature of 'int int' would be tested for by calling
$M->match_signature('int') and expecting the return value to be int.
Execute the code that this object encapsulates, using the list of parameters
passed in PARAMLIST. The SERVER argument should be an object derived from the
RPC::XML::Server class. For some types of procedure objects, this becomes
the first argument of the parameter list to simulate a method call as if it
were on the server object itself. The return value should be a data object
(possibly a RPC::XML::fault), but may not always be pre-encoded. Errors
trapped in $@ are converted to fault objects. This method is generally used
in the dispatch method of the server class, where the return value is
subsequently wrapped within a RPC::XML::response object.
Instruct the object to reload itself from the file it originally was loaded from, assuming that it was loaded from a file to begin with. Returns an error if the method was not originally loaded from a file, or if an error occurs during the reloading operation.
In addition to the attributes managed by the accessors documented earlier, the following hash keys are also available for use. These are also not strongly protected, and the same care should be taken before altering any of them:
When the method was loaded from a file, this key contains the path to the file used.
If the code is loaded from a file, this hash key will reflect what namespace
the code executes in. If the file specified a namespace, that is the value
you will get (any occurrence of . in the specified namespace will have been
converted to ::). If no explicit namespace was provided, the namespace
of the class you called new from will be used. See "Namespaces".
When the method was loaded from a file, this key contains the
modification-time of the file, as a UNIX-style time value. This is used to
check for changes to the file the code was originally read from.
When the method is being used by one of the server classes provided in this software suite, this key is incremented each time the server object dispatches a request to the method. This can later be checked to provide some indication of how frequently the method is being invoked.
This section focuses on the way in which methods are expressed in these files,
referred to here as "XPL files" due to the *.xpl filename extension
(which stands for "XML Procedure Layout"). This mini-dialect, based on XML,
is meant to provide a simple means of specifying method definitions separate
from the code that comprises the application itself. Thus, methods may
theoretically be added, removed, debugged or even changed entirely without
requiring that the server application itself be rebuilt (or, possibly, without
it even being restarted).
The XPL Procedure Layout dialect is a very simple application of XML to the problem of expressing the method in such a way that it could be useful to other packages than this one, or useful in other contexts than this one.
The lightweight DTD for the layout can be summarized as:
<!ELEMENT proceduredef (name, namespace?, version?, hidden?,
signature+, help?, code)>
<!ELEMENT methoddef (name, namespace?, version?, hidden?,
signature+, help?, code)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT namespace (#PCDATA)>
<!ELEMENT version (#PCDATA)>
<!ELEMENT hidden EMPTY>
<!ELEMENT signature (#PCDATA)>
<!ELEMENT help (#PCDATA)>
<!ELEMENT code (#PCDATA)>
<!ATTLIST code language (#PCDATA)>
The containing tag is always one of <methoddef> or
<proceduredef>. The tags that specify name, signatures and the code
itself must always be present. Some optional information may also be
supplied. The "help" text, or what an introspection API would expect to use to
document the method, is also marked as optional. Having some degree of
documentation for all the methods a server provides is a good rule of thumb,
however.
The default methods that this package provides are turned into XPL files by the make_method tool (see make_method). The final forms of these may serve as examples of what the file should look like.
Some of the information in the XPL file is only for book-keeping: the version
stamp of a method is never involved in the invocation. The server also keeps
track of the last-modified time of the file the method is read from, as well
as the full directory path to that file. The <hidden /> tag is used
to identify those methods that should not be exposed to the outside world
through any sort of introspection/documentation API. They are still available
and callable, but the client must possess the interface information in order
to do so.
The name, signatures and code must be present for obvious reasons. The
<name> tag tells the server what external name this procedure is
known by. The <signature> tag, which may appear more than once,
provides the definition of the interface to the function in terms of what
types and quantity of arguments it will accept, and for a given set of
arguments what the type of the returned value is. Lastly is the
<code> tag, without which there is no procedure to remotely call.
Note that the <code> tag is the only one with an attribute, in this
case "language". This is designed to allow for one XPL file to provide a given
method in multiple languages. Why, one might ask, would there be a need for
this?
It is the hope behind this package that collections of RPC suites may one day
be made available as separate entities from this specific software package.
Given this hope, it is not unreasonable to suggest that such a suite of code
might be implemented in more than one language (each of Perl, Python, Ruby and
Tcl, for example). Languages which all support the means by which to take new
code and add it to a running process on demand (usually through an "eval"
keyword or something similar). If the file A.xpl is provided with
implementations in all four of the above languages, the name, help text,
signature and even hidden status would likely be identical. So, why not share
the non-language-specific elements in the spirit of re-use?
make_method UtilityThe utility script make_method is provided as a part of this software
suite. It allows for the automatic creation of XPL files from either
command-line information or from template files. It has a wide variety of
features and options, and is out of the scope of this particular manual
page. The package Makefile.PL features an example of engineering the
automatic generation of XPL files and their delivery as a part of the normal
Perl module build process. Using this tool is highly recommended over managing
XPL files directly. For the full details, see make_method.
As default behavior, Perl code that is passed to eval when a XPL file is
loaded gets put into the same namespace as the package used to load the XPL.
It is not an issue when you create your own RPC::XML::Procedure (or
::Method or ::Function) objects, as the code is already instantiated
into a given namespace. This can be important if your code expects to call
routines in other loaded packages, utilize package-level globals, etc.
To give developers control over the namespace in XPL code, a new optional
tag <namespace> was added in the 0.65 release. If this tag is present
in the XPL being read, it defines the namespace that the <code> block
is evaluated in.
The value of the namespace tag is a string providing the namespace in either
the Perl-style of hierarchy parts separated by ::, or the style used by
Java, Perl6, etc., in which the parts are separated by .. The latter
form is converted to Perl style for the evaluation of the code. If there is
no namespace declaration in a XPL file, the namespace of the class that
loads the XPL is used.
Unless otherwise noted in the individual documentation sections, all methods return the object reference on success, or a (non-reference) text string containing the error message upon failure.
Moving the method management to a separate class adds a good deal of overhead to the general system. The trade-off in reduced complexity and added maintainability should offset this.
Please report any bugs or feature requests to
bug-rpc-xml at rt.cpan.org, or through the web interface at
http://rt.cpan.org/NoAuth/ReportBug.html?Queue=RPC-XML. I will be
notified, and then you'll automatically be notified of progress on
your bug as I make changes.
This file and the code within are copyright (c) 2010 by Randy J. Ray.
Copying and distribution are permitted under the terms of the Artistic License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php) or the GNU LGPL 2.1 (http://www.opensource.org/licenses/lgpl-2.1.php).
The XML-RPC standard is Copyright (c) 1998-2001, UserLand Software, Inc. See <http://www.xmlrpc.com> for more information about the XML-RPC specification.
RPC::XML::Server, make_method
Randy J. Ray <rjray@blackperl.com>
| RPC-XML documentation | Contained in the RPC-XML distribution. |
############################################################################### # # This file copyright (c) 2001-2010 Randy J. Ray, all rights reserved # # Copying and distribution are permitted under the terms of the Artistic # License 2.0 (http://www.opensource.org/licenses/artistic-license-2.0.php) or # the GNU LGPL (http://www.opensource.org/licenses/lgpl-2.1.php). # ############################################################################### # # Description: This class abstracts out all the procedure-related # operations from the RPC::XML::Server class # # Functions: new # name \ # code \ # signature \ These are the accessor functions for the # help / data in the object, though it's visible. # version / # hidden / # clone # is_valid # add_signature # delete_signature # make_sig_table # match_signature # reload # load_XPL_file # # Libraries: XML::Parser (used only on demand in load_XPL_file) # File::Spec # # Global Consts: $VERSION # # Environment: None. # ############################################################################### package RPC::XML::Procedure; use 5.006001; use strict; use warnings; use vars qw($VERSION); use subs qw(new is_valid name code signature help version hidden add_signature delete_signature make_sig_table match_signature reload load_XPL_file); use AutoLoader 'AUTOLOAD'; use File::Spec; use Scalar::Util 'blessed'; use RPC::XML 'smart_encode'; # This module also provides RPC::XML::Method ## no critic (ProhibitMultiplePackages) $VERSION = '1.21'; $VERSION = eval $VERSION; ## no critic (ProhibitStringyEval) ############################################################################### # # Sub Name: new # # Description: Create a new object of this class, storing the info on # regular keys (no obfuscation used here). # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $class in scalar Class to bless into # @argz in variable Disposition is variable; see # below # # Returns: Success: object ref # Failure: error string # ############################################################################### sub new { my ($class , @argz) = @_; my $data; # This will be a hashref that eventually gets blessed $class = ref($class) || $class; # # There are three things that @argz could be: # if (ref $argz[0]) { # 1. A hashref containing all the relevant keys $data = {}; %{$data} = %{$argz[0]}; } elsif (@argz == 1) { # 2. Exactly one non-ref element, a file to load # And here is where I cheat in a way that makes even me uncomfortable. # # Loading code from an XPL file, it can actually be of a type other # than how this constructor was called. So what we are going to do is # this: If $class is undef, that can only mean that we were called # with the intent of letting the XPL file dictate the resulting object. # If $class is set, then we'll call load_XPL_file normally, as a # method, to allow for subclasses to tweak things. if (defined $class) { $data = $class->load_XPL_file($argz[0]); if (! ref $data) { # load_XPL_path signalled an error return $data; } } else { # Spoofing the "class" argument to load_XPL_file makes me feel # even dirtier... $data = load_XPL_file(\$class, $argz[0]); if (! ref $data) { # load_XPL_path signalled an error return $data; } $class = "RPC::XML::$class"; } } else { # 3. If there is more than one arg, it's a sort-of-hash. That is, the # key 'signature' is allowed to repeat. my ($key, $val); $data = {}; $data->{signature} = []; while (@argz) { ($key, $val) = splice @argz, 0, 2; if ($key eq 'signature') { # Since there may be more than one signature, we allow it to # repeat. Of course, that's also why we can't just take @argz # directly as a hash. *shrug* push @{$data->{signature}}, ref $val ? join q{ } => @{$val} : $val; } elsif (exists $data->{$key}) { return "${class}::new: Key '$key' may not be repeated"; } else { $data->{$key} = $val; } } } if (! (exists $data->{signature} && (ref($data->{signature}) eq 'ARRAY') && scalar(@{$data->{signature}}) && $data->{name} && $data->{code})) { return "${class}::new: Missing required data"; } bless $data, $class; # This needs to happen post-bless in case of error (for error messages) return $data->make_sig_table; } ############################################################################### # # Sub Name: make_sig_table # # Description: Create a hash table of the signatures that maps to the # corresponding return type for that particular invocation. # Makes looking up call patterns much easier. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $self # Failure: error message # ############################################################################### sub make_sig_table { my $self = shift; my ($return, $rest); delete $self->{sig_table}; for my $sig (@{$self->{signature}}) { ($return, $rest) = split / /, $sig, 2; if (! $rest) { $rest = q{}; } # If the key $rest already exists, then this is a collision if ($self->{sig_table}->{$rest}) { return ref($self) . '::make_sig_table: Cannot have two different ' . "return values for one set of params ($return vs. " . "$self->{sig_table}->{$rest})"; } $self->{sig_table}->{$rest} = $return; } return $self; } # # These are basic accessor/setting functions for the various attributes # sub name { return shift->{name}; } # "name" cannot be changed at this level sub namespace { return shift->{namespace} || q{}; } # Nor can "namespace" sub help { my ($self, $value) = @_; $value and $self->{help} = $value; return $self->{help}; } sub version { my ($self, $value) = @_; $value and $self->{version} = $value; return $self->{version}; } sub hidden { my ($self, $value) = @_; $value and $self->{hidden} = $value; return $self->{hidden}; } sub code { my ($self, $value) = @_; ref $value eq 'CODE' and $self->{code} = $value; return $self->{code}; } sub signature { my ($self, $sig) = @_; if ($sig and ref $sig eq 'ARRAY') { my $old = $self->{signature}; $self->{signature} = $sig; if (! ref $self->make_sig_table) { # If it failed to re-init the table, restore the old list (and old # table). We don't have to check this return, since it had worked # before. $self->{signature} = $old; $self->make_sig_table; } } # Return a copy of the array, not the original return [ @{$self->{signature}} ]; } package RPC::XML::Method; use strict; use base qw(RPC::XML::Procedure); # Needed for AutoSplit to be happy: package RPC::XML::Procedure; 1; __END__
############################################################################### # # Sub Name: clone # # Description: Create a near-exact copy of the invoking object, save that # the listref in the "signature" key is a copy, not a ref # to the same list. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $new_self # Failure: error message # ############################################################################### sub clone { my $self = shift; my $new_self = {}; for (keys %{$self}) { next if $_ eq 'signature'; $new_self->{$_} = $self->{$_}; } $new_self->{signature} = []; @{$new_self->{signature}} = @{$self->{signature}}; return bless $new_self, ref $self; } ############################################################################### # # Sub Name: is_valid # # Description: Boolean test to tell if the calling object has sufficient # data to be used as a server method for RPC::XML::Server or # Apache::RPC::Server. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object to test # # Returns: Success: 1, valid/complete # Failure: 0, invalid/incomplete # ############################################################################### sub is_valid { my $self = shift; return ( (ref($self->{code}) eq 'CODE') and $self->{name} and (ref($self->{signature}) && scalar(@{$self->{signature}}))); } ############################################################################### # # Sub Name: add_signature # delete_signature # # Description: This pair of functions may be used to add and remove # signatures from a method-object. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # @args in list One or more signatures # # Returns: Success: $self # Failure: error string # ############################################################################### sub add_signature { my ($self, @args) = @_; my (%sigs, $tmp, $old); # Preserve the original in case adding the new one causes a problem $old = $self->{signature}; %sigs = map { $_ => 1 } @{$self->{signature}}; for my $one_sig (@args) { $tmp = (ref $one_sig) ? join q{ } => @{$one_sig} : $one_sig; $sigs{$tmp} = 1; } $self->{signature} = [ keys %sigs ]; $tmp = $self->make_sig_table; if (! ref $tmp) { # Because this failed, we have to restore the old table and return # an error $self->{signature} = $old; $self->make_sig_table; return ref($self) . '::add_signature: Error re-hashing table: ' . $tmp; } return $self; } sub delete_signature { my ($self, @args) = @_; my (%sigs, $tmp, $old); # Preserve the original in case adding the new one causes a problem $old = $self->{signature}; %sigs = map { $_ => 1 } @{$self->{signature}}; for my $one_sig (@args) { $tmp = (ref $one_sig) ? join q{ } => @{$one_sig} : $one_sig; delete $sigs{$tmp}; } $self->{signature} = [ keys %sigs ]; $tmp = $self->make_sig_table; if (! ref $tmp) { # Because this failed, we have to restore the old table and return # an error $self->{signature} = $old; $self->make_sig_table; return ref $self . '::delete_signature: Error re-hashing table: ' . $tmp; } return $self; } ############################################################################### # # Sub Name: match_signature # # Description: Determine if the passed-in signature string matches any # of this method's known signatures. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $sig in scalar Signature to check for # # Returns: Success: return type as a string # Failure: 0 # ############################################################################### sub match_signature { my $self = shift; my $sig = shift; if (ref $sig) { $sig = join q{ } => @{$sig}; } return $self->{sig_table}->{$sig} || 0; } ############################################################################### # # Sub Name: reload # # Description: Reload the method's code and ancillary data from the file # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # # Returns: Success: $self # Failure: error message # ############################################################################### sub reload { my $self = shift; if (! $self->{file}) { return sprintf '%s::reload: No file associated with method %s', ref $self, $self->{name}; } my $tmp = $self->load_XPL_file($self->{file}); if (ref $tmp) { # Update the information on this actual object for (keys %{$tmp}) { $self->{$_} = $tmp->{$_}; } # Re-calculate the signature table, in case that changed as well return $self->make_sig_table; } return $tmp; } ############################################################################### # # Sub Name: load_XPL_file # # Description: Load a XML-encoded method description (generally denoted # by a *.xpl suffix) and return the relevant information. # # Note that this does not fill in $self if $self is a hash # or object reference. This routine is not a substitute for # calling new() (which is why it isn't part of the public # API). # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $file in scalar File to load # # Returns: Success: hashref of values # Failure: error string # ############################################################################### sub load_XPL_file { my $self = shift; my $file = shift; require XML::Parser; my ($me, $data, $signature, $code, $codetext, $accum, $P, %attr); if (ref($self) eq 'SCALAR') { $me = __PACKAGE__ . '::load_XPL_file'; } else { $me = (ref $self) || $self || __PACKAGE__; $me .= '::load_XPL_file'; } $data = {}; # So these don't end up undef, since they're optional elements $data->{hidden} = 0; $data->{version} = q{}; $data->{help} = q{}; $data->{called} = 0; $P = XML::Parser->new( ErrorContext => 1, Handlers => { Char => sub { $accum .= $_[1] }, Start => sub { %attr = splice @_, 2 }, End => sub { my $elem = $_[1]; $accum =~ s/^[\s\n]+//; $accum =~ s/[\s\n]+$//; if ($elem eq 'signature') { $data->{signature} ||= []; push @{$data->{signature}}, $accum; } elsif ($elem eq 'code') { if (! ($attr{language} && $attr{language} ne 'perl')) { $data->{$elem} = $accum; } } elsif ('def' eq substr $elem, -3) { # Don't blindly store the container tag... # We may need it to tell the caller what # our type is if (ref $self eq 'SCALAR') { ${$self} = ucfirst substr $elem, 0, -3; } } else { $data->{$elem} = $accum; } %attr = (); $accum = q{}; } } ); if (! $P) { return "$me: Error creating XML::Parser object"; } open my $fh, '<', $file or return "$me: Error opening $file for reading: $!"; # Trap any errors eval { $P->parse($fh); }; ## no critic (RequireCheckingReturnValueOfEval) close $fh or return "$me: Error closing $file: $!"; if ($@) { return "$me: Error parsing $file: $@"; } # Try to normalize $codetext before passing it to eval # First step is set the namespace the code will live in. The default is # the package that we're in (be it ::Procedure, ::Method, etc.). If they # specify one, use it instead. if ($data->{namespace}) { # Fudge a little and let them '.' as a synonym for '::' in the # namespace hierarchy. $data->{namespace} =~ s{\.}{::}g; } else { $data->{namespace} = __PACKAGE__; } # Next step is to munge away any actual subroutine name so that the eval # yields an anonymous sub. Also insert the namespace declaration. ($codetext = $data->{code}) =~ s/sub[\s\n]+([\w:]+)?[\s\n]*\{/sub \{ package $data->{namespace}; /x; $code = eval $codetext; ## no critic (ProhibitStringyEval) return "$me: Error creating anonymous sub: $@" if $@; $data->{code} = $code; # Add the file's mtime for when we check for stat-based reloading $data->{mtime} = (stat $file)[9]; $data->{file} = $file; return $data; } ############################################################################### # # Sub Name: call # # Description: Encapsulates the invocation of the code block that the # object is abstracting. Manages parameters, signature # checking, etc. # # Arguments: NAME IN/OUT TYPE DESCRIPTION # $self in ref Object of this class # $srv in ref An object derived from the # RPC::XML::Server class # @dafa in list The params for the call itself # # Globals: None. # # Environment: None. # # Returns: Success: value # Failure: dies with RPC::XML::Fault object as message # ############################################################################### sub call { my ($self, $srv, @data) = @_; my (@paramtypes, @params, $signature, $resptype, $response, $name, $noinc); $name = $self->name; # Create the param list. # The type for the response will be derived from the matching signature @paramtypes = map { $_->type } @data; @params = map { $_->value } @data; $signature = join q{ } => @paramtypes; $resptype = $self->match_signature($signature); # Since there must be at least one signature with a return value (even # if the param list is empty), this tells us if the signature matches: if (! $resptype) { return $srv->server_fault( badsignature => "method $name has no matching signature for the argument list: " . "[$signature]" ); } # Make sure that the response-type is a valid XML-RPC type if (($resptype ne 'scalar') && (! "RPC::XML::$resptype"->can('new'))) { return $srv->server_fault(badsignature => "Signature [$signature] for method $name has unknown " . "return-type '$resptype'"); } # Set these in case the server object is part of the param list local $srv->{signature} = ## no critic (ProhibitLocalVars) [ $resptype, @paramtypes ]; local $srv->{method_name} = $name; ## no critic (ProhibitLocalVars) # If the method being called is "system.status", check to see if we should # increment the server call-count. $noinc = (($name eq 'system.status') && @data && ($paramtypes[0] eq 'boolean') && $params[0]) ? 1 : 0; # For RPC::XML::Method (and derivatives), pass the server object if ($self->isa('RPC::XML::Method')) { unshift @params, $srv; } # Now take a deep breath and call the method with the arguments if (! eval { $response = $self->{code}->(@params); 1; }) { # On failure, propagate user-generated RPC::XML::fault exceptions, or # transform Perl-level error/failure into such an object if ($@) { return (blessed $@ and $@->isa('RPC::XML::fault')) ? $@ : $srv->server_fault(execerror => "Method $name returned error: $@"); } } if (! $noinc) { $self->{called}++; } # Create a suitable return value if (! ref $response) { if ($resptype eq 'scalar') { # Server code from the RPC::XML::Function class doesn't use # signatures, so if they didn't encode the returned value # themselves they're trusting smart_encode() to get it right. $response = smart_encode($response); } else { # We checked that this was valid earlier, so no need for further # tests here. $response = "RPC::XML::$resptype"->new($response); } } return $response; }