Difference between revisions of "Refining the implementation"

From GCube System
Jump to: navigation, search
(A Faultful Interface)
(A Faultful Implementation)
Line 140: Line 140:
 
* <code>getDefaultException()</code> is a method which <code>ServiceContext</code> inherits from <code>GCUBEServiceContext</code>. If not overridden, the method will wrap any exception into a <code>GCUBERetryEquivalentException</code>,  but it may be overridden to reflect more optimistic or less optimistic assumptions.
 
* <code>getDefaultException()</code> is a method which <code>ServiceContext</code> inherits from <code>GCUBEServiceContext</code>. If not overridden, the method will wrap any exception into a <code>GCUBERetryEquivalentException</code>,  but it may be overridden to reflect more optimistic or less optimistic assumptions.
  
'''Note:''' <code>about()</code> '''must''' declare explicitly all the gCube faults it may throw. If it did not, specific faults would arrive at the client as generic gCube faults, so defeating their purpose. This is unfortunately one limitation of the technologies underlying the current implementation of gCore. In addition, <code>about()</code> '''must''' also declare to throw the generic gCube fault because the method <code>toFault()</code> of gCube exceptions returns it.
+
'''Note:''' <code>about()</code> '''must''' declare explicitly all the gCube faults it may throw. If it did not, specific faults would arrive at the client as generic gCube faults, so defeating their purpose. This is unfortunately one limitation of the technologies underlying the current implementation of gCore. In addition, <code>about()</code> '''must''' declare to throw the generic gCube fault because the method <code>toFault()</code> of gCube exceptions returns it.
 +
 
  
 
After having rebuilt and redeployed <code>SampleService</code>, adapt our <code>StatelessClient</code> to catch faults of the different types and then test it.
 
After having rebuilt and redeployed <code>SampleService</code>, adapt our <code>StatelessClient</code> to catch faults of the different types and then test it.

Revision as of 16:08, 16 April 2008

Now that we have exemplified the tasks which comprise the development cycle of a gCube service, we can progressively inject more structure and functionality into the implementation of SampleService. We do so incrementally, of course, tackling first a number of issues which are common to all service implementations and yet do not imply big changes to the internal structure of our SampleService.

A Faultful PortType

Things not always go according to plans. Unpredictable circumstances at runtime may cause deviations form the control flow we expect within our service implementation. Some of these deviations are the result of genuine programming errors which we hope to capture as early as possible during testing. Others are more exceptional and we cannot blame our code for them, rather a malformed client request or simply a local or remote environment which does not satisfy normal expectations. When this happens and there is a client waiting for a response, all we can do is return a fault which explains the problem and may induce a client to react in some useful way.

Faults & Exceptions

Simply put, a fault is an exception which escapes the service implementation. More precisely, it wraps such an exception in a way which is suitable for it to travel over the network and back to clients. By default, the gHN wraps exceptions which escape the service boundary in a generic SOAP fault. There is no much a client can do with it, beside desisting gracefully from doing whatever it was trying to do. However, we can define our own fault types as specialisations of the generic one.

gCF offer three pre-defined fault specialisations. They model prototypical fault causes, still generic but informative enough for clients to react more usefully than by giving up:

  • GCUBERetrySameFault, which basically means: couldn't do it now, but try again later I might make it then.
  • GCUBERetryEquivalentFault which basically means: couldn't do it myself, but other Running Instances they might.
  • GCUBEUnrecoverableFault, which basically means: couldn't do it now, won't do it later, and there is no point asking someone else. Just forget about it.

A client presented with either one of the first two fault types can try to recover accordingly, while a client presented with the last knows that there is little point in insisting, neither later nor elsewhere. Of course, when or which of these faults should be returned depends on the precise semantics of our service.

So, how about our SampleService? Well, at the moment our Stateless port-type can hardly go wrong, because if its single about() method completes successfully once, it is very likely that it will complete successfully all the time. At the very best, we could play safe and declare that we might return a GCUBEUnrecoverableFault, in the assumption that if something goes wrong then there aren't many chances it will ever go right. In fact, a modicum of testing could immediately eliminate this possibility: either the service does not activate properly within the gHN or, if it does, it will behave correctly.

So, to illustrate fully the case of 'faultful' port-types, we are going to introduce artificially the possibility of a wider range of faults into the interface and implementation of the about() method.

Before we do that, however, a final observation. Faults are 'heavyweight' exceptions and are best raised and caught at the ‘edge’ of a service implementations, i.e. in the code directly invoked by clients and in the code which directly call the methods of other services. Accordingly, gCF mirrors gCube faults with equivalent but 'lightweight' exception for use inside the service implementation:

  • GCUBERetrySameException ~ GCUBERetrySameFault
  • GCUBERetryEquivalentException ~ GCUBERetryEquivalentFault
  • GCUBEUnrecoverableException ~ GCUBEUnrecoverableFault

gCube exceptions and gCube faults are freely convertible. Typically, a gCube exception raised within the service should be converted into a gCube fault before it escapes the service. Similary, a gCube fault received from interacting with another service ought to be converted into a gCube exception before it perculates up backwords the call stack.

Note: gCube exceptions complement but do not replace all the other Java exceptions, of course. The code which observes a failure may or may not be aware of its implications in the broader context of the request process. If it does, then it should raise a gCube exception. If it does not (e.g. is a generic routine), then it should raise whatever Java exception seems most appropriate.

Note: All gCube faults share a common root GCUBEFault, both as interface elements and implementation objects. Similary, all gCube exceptions derive GCUBEException. As we shall see, these roots are mostly useful in the implementation, where they simplify exception handling.

A Faultful Interface

First of all, let us declare the possibility of failures in the port-type interface:

<?xml version="1.0" encoding="UTF-8"?>
<definitions name="Stateless" targetNamespace="http://acme.org/sample" xmlns:tns="http://acme.org/sample"
  	xmlns="http://schemas.xmlsoap.org/wsdl/"  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:corefaults="http://gcube-system.org/namespaces/common/core/faults">
    
    <import namespace="http://gcube-system.org/namespaces/common/core/faults" location="../gcube/common/core/faults/GCUBEFaults.wsdl"/>
    
 	<types>
	<xsd:schema targetNamespace="http://acme.org/sample">
  
  		<xsd:element name="about" type="xsd:string" />
		<xsd:element name="aboutResponse" type="xsd:string" />	
	
	</xsd:schema>
	</types>

	<message name="aboutInputMessage">
		<part name="request" element="tns:about"/>
	</message>
	<message name="aboutOutputMessage">
		<part name="response" element="tns:aboutResponse"/>
	</message>

	<portType name="StatelessPortType">
	
		<operation name="about">
			<input message="tns:aboutInputMessage"/>
			<output message="tns:aboutOutputMessage"/>
			<fault name="unrecoverablefault" message="corefaults:GCUBEUnrecoverableFaultMessage"/>
			<fault name="retrysamefault" message="corefaults:GCUBERetrySameFaultMessage"/>
			<fault name="retryequivalentfault" message="corefaults:GCUBERetryEquivalentFaultMessage" />
        	</operation>
	
	</portType>

</definitions>


The thing to notice here is that we import pre-defined fault messages from a standard gCore WSDL:

<import namespace="http://gcube-system.org/namespaces/common/core/faults" location="../gcube/common/core/faults/GCUBEFaults.wsdl"/>

and then use them in the declartion of the about() operation:

	<operation name="about">
			<input message="tns:aboutInputMessage"/>
			<output message="tns:aboutOutputMessage"/>
			<fault name="unrecoverablefault" message="corefaults:GCUBEUnrecoverableFaultMessage"/>
			<fault name="retrysamefault" message="corefaults:GCUBERetrySameFaultMessage"/>
			<fault name="retryequivalentfault" message="corefaults:GCUBERetryEquivalentFaultMessage" />
        </operation>

Note: The location makes sense with respect to the temporary build used by our buildfile and will succeed because the buildfile will copy all the the pre-defined gCore WSDL in that folder at the point of building. You do not need to worry about it, just make sure you are copying this correctly.

That's all for the interface of Stateless. This is the right time to rebuild the stubs though.

A Faultful Implementation

Now the implementation of the port-type and the simulation of failure we promised:

package org.acme.sample.stateless;
import ...

public class Stateless extends GCUBEStartupPortType {

	/** {@inheritDoc} */
	protected GCUBEServiceContext getServiceContext() {return ServiceContext.getContext();}

	protected static void simulateRequestProcessing() throws Exception {
		if (Math.random()<.60) { //simulating an error
			switch ((int) (Math.random()*4+1)) {//randomly choosing error type
				case 1 : throw new GCUBEUnrecoverableException("just give up");
				case 2 : throw new GCUBERetryEquivalentException("maybe someone else?");
				case 3: throw new GCUBERetrySameException("maybe in a bit?");
				case 4: throw new Exception("some problem with unclear semantics");
	}}}
	
	public String about(String name) throws GCUBEFault,GCUBERetryEquivalentFault,GCUBERetrySameFault,GCUBEUnrecoverableFault {		

              try {
		      simulateRequestProcessing();
                      return ("Hello " + name + ", you have invoked service ")+this.getServiceContext().getName() + 
                                                             " ("+this.getServiceContext().getServiceClass() + ")";
		}
		catch(GCUBEException e) {throw e.toFault();}
		catch(Exception e) {throw sctx.getDefaultException("Problem of unknown semantics", e).toFault();}
	}
}

A few things to comment upon here:

  • the method simulatRequestProcessing() emulates an arbitrarily complex process which may fail in more than one different way. In a real scenario, the process would be likely distributed among many implementation components, and it would probably reach very 'deeply' within the call stack. Here we use a 'flat' method in which we throw a die and simulate a failure in 60% of the outcomes. When we do so, we throw another 4-faced die to simulate the different types of failures which may occur inside a gCube Service: the three types of gCube exceptions gCube plus a fourth type of generic failure.
  • the method about() invokes simulatRequestProcessing() and catches potential exceptions. All gCube exceptions are converted to the corresponding gCube fault. Any other Java exception is embedded into the type of gCube exception set as default before being also converted to a gCube fault.
  • getDefaultException() is a method which ServiceContext inherits from GCUBEServiceContext. If not overridden, the method will wrap any exception into a GCUBERetryEquivalentException, but it may be overridden to reflect more optimistic or less optimistic assumptions.

Note: about() must declare explicitly all the gCube faults it may throw. If it did not, specific faults would arrive at the client as generic gCube faults, so defeating their purpose. This is unfortunately one limitation of the technologies underlying the current implementation of gCore. In addition, about() must declare to throw the generic gCube fault because the method toFault() of gCube exceptions returns it.


After having rebuilt and redeployed SampleService, adapt our StatelessClient to catch faults of the different types and then test it.