The great invocation services rethink of 2002! Rearchitected the remote

method invocation services and converted everything to the new style.
Could this be my biggest checkin ever?


git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@1642 542714f4-19e9-0310-aa3c-eee0fc999fb1
This commit is contained in:
Michael Bayne
2002-08-14 19:08:01 +00:00
parent 4481c5f835
commit e54a4d41f4
161 changed files with 6083 additions and 2805 deletions
@@ -1,70 +1,69 @@
//
// $Id: InvocationDirector.java,v 1.20 2002/04/16 21:37:23 mdb Exp $
// $Id: InvocationDirector.java,v 1.21 2002/08/14 19:07:54 mdb Exp $
package com.threerings.presents.client;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import com.samskivert.util.HashIntMap;
import com.samskivert.util.StringUtil;
import com.samskivert.util.ResultListener;
import com.samskivert.util.StringUtil;
import com.threerings.presents.Log;
import com.threerings.presents.data.*;
import com.threerings.presents.dobj.*;
import com.threerings.presents.util.ClassUtil;
import com.threerings.presents.client.InvocationReceiver.Registration;
import com.threerings.presents.data.ClientObject;
import com.threerings.presents.data.InvocationMarshaller.ListenerMarshaller;
import com.threerings.presents.data.InvocationMarshaller;
import com.threerings.presents.dobj.DEvent;
import com.threerings.presents.dobj.DObject;
import com.threerings.presents.dobj.DObjectManager;
import com.threerings.presents.dobj.EventListener;
import com.threerings.presents.dobj.InvocationNotificationEvent;
import com.threerings.presents.dobj.InvocationRequestEvent;
import com.threerings.presents.dobj.InvocationResponseEvent;
import com.threerings.presents.dobj.ObjectAccessException;
import com.threerings.presents.dobj.Subscriber;
/**
* The invocation services provide client to server invocations (service
* requests) and server to client invocations (responses and
* notifications). Via this mechanism, the client can make requests of the
* server, be notified of its response and the server can asynchronously
* invoke code on the client.
*
* <p> Invocations are like remote procedure calls in that they are named
* and take arguments. They are simple in that the arguments can only be
* of a small set of supported types (the set of distributed object field
* types) and there is no special facility provided for referencing
* non-local objects (it is assumed that the distributed object facility
* will already be in use for any objects that should be shared).
*
* <p> The client invocation director delivers invocation requests to the
* server invocation manager and maps the responses back to the proper
* response target objects when they arrive. It also maintains the mapping
* of invocation receivers that can receive asynchronous invocation
* notifications at any time from the server.
* Handles the client side management of the invocation services.
*/
public class InvocationDirector
implements MessageListener
implements EventListener
{
/**
* Initializes the invocation director.
* Initializes the invocation director. This is called when the client
* establishes a connection with the server.
*
* @param omgr the distributed object manager via which the invocation
* manager will send and receive events.
* @param cloid the oid of the object on which invocation
* notifications as well as invocation responses will be received.
* @param imoid the oid of the object on the server to which to
* deliver invocation requests.
* @param initListener a result listener that will be notified when
* the invocation director is up and running (meaning it has
* subscribed successfully to the client object and is ready to
* process invocation requests); or when initialization has failed.
*/
public void init (DObjectManager omgr, final int cloid, int imoid,
public void init (DObjectManager omgr, final int cloid,
final ResultListener initListener)
{
// keep this for later
_omgr = omgr;
_imoid = imoid;
_cloid = cloid;
// add ourselves as a subscriber to the client object
_omgr.subscribeToObject(cloid, new Subscriber() {
public void objectAvailable (DObject object)
{
// keep a handle on this bad boy
_clobj = (ClientObject)object;
// add ourselves as a message listener
object.addListener(InvocationDirector.this);
_clobj.addListener(InvocationDirector.this);
// assign a mapping to already registered receivers
assignReceiverIds();
// let the client know that we're ready to go now that
// we've got our subscription to the client object
@@ -83,224 +82,243 @@ public class InvocationDirector
}
/**
* Sends an invocation request to the server. If a response target is
* supplied, the response will be delivered to that object by calling
* a member function on it whose name is defined in the response
* generated by the invocation implementation. In general, this is a
* derivative of the invocation procedure name. For example, if the
* caller invoked a procedure named <code>Switch</code>, the response
* may be delivered via a call to the <code>handleSwitchSuccess</code>
* method on the response target object. The signature of that method
* would be defined by the arguments provided in the response message
* with the addition of a first argument which is the invocation
* identifier for this particular request (that is also returned by
* this function).
*
* @param module the name of the invocation module to use.
* @param procedure the name of the procedure within that module.
* @param args the arguments of the invocation.
* @param rsptarget the object that will receive the response, or null
* if no response is desired.
*
* @return a unique identifier associated with this invocation
* request. This identifier will be passed as the first argument to
* the response function.
* Clears out our session information. This is called when the client
* ends its session with the server.
*/
public int invoke (String module, String procedure, Object[] args,
Object rsptarget)
public void cleanup ()
{
int invid = nextInvocationId();
// wipe our client object, receiver mappings and listener mappings
_clobj = null;
_receivers.clear();
_listeners.clear();
// if null arguments were supplied, assume zero arguments
if (args == null) {
args = new Object[0];
// also reset our counters
_requestId = 0;
_receiverId = 0;
}
/**
* Registers an invocation notification receiver by way of its
* notification event decoder.
*/
public void registerReceiver (InvocationDecoder decoder)
{
// add the receiver to the list
_reclist.add(decoder);
// if we're already online, assign a receiver id to this decoder
if (_clobj != null) {
assignReceiverId(decoder);
}
}
/**
* Removes a receiver registration.
*/
public void unregisterReceiver (String receiverCode)
{
// remove the receiver from the list
for (Iterator iter = _reclist.iterator(); iter.hasNext(); ) {
InvocationDecoder decoder = (InvocationDecoder)iter.next();
if (decoder.getReceiverCode().equals(receiverCode)) {
iter.remove();
}
}
// we need an args array for a message that can contain the
// invocation names, an invocation id and the invocation arguments
Object[] iargs = new Object[args.length+3];
iargs[0] = module;
iargs[1] = procedure;
iargs[2] = new Integer(invid);
System.arraycopy(args, 0, iargs, 3, args.length);
// create a message event on the invocation manager object
MessageEvent event = new MessageEvent(
_imoid, InvocationObject.REQUEST_NAME, iargs);
// if we have a response target, register that for later receipt
// of the response
if (rsptarget != null) {
_targets.put(invid, rsptarget);
// if we're logged on, clear out any receiver id mapping
if (_clobj != null) {
_clobj.removeFromReceivers(receiverCode);
}
}
/**
* Assigns a receiver id to this decoder and publishes it in the
* {@link ClientObject#receivers} field.
*/
protected void assignReceiverId (InvocationDecoder decoder)
{
Registration reg = new Registration(
decoder.getReceiverCode(), nextReceiverId());
// stick the mapping into the client object
_clobj.addToReceivers(reg);
// and map the receiver in our receivers table
_receivers.put(reg.receiverId, decoder);
}
/**
* Called when we log on; generates mappings for all receivers
* registered prior to logon.
*/
protected void assignReceiverIds ()
{
// pack all the set add events into a single transaction
_clobj.startTransaction();
try {
for (Iterator iter = _reclist.iterator(); iter.hasNext(); ) {
assignReceiverId((InvocationDecoder)iter.next());
}
} finally {
_clobj.commitTransaction();
}
}
/**
* Requests that the specified invocation request be packaged up and
* sent to the supplied invocation oid.
*/
public void sendRequest (
int invOid, int invCode, int methodId, Object[] args)
{
// configure any invocation listener marshallers among the
// arguments
int acount = args.length;
for (int ii = 0; ii < acount; ii++) {
Object arg = args[ii];
if (arg instanceof ListenerMarshaller) {
ListenerMarshaller lm = (ListenerMarshaller)arg;
lm.callerOid = _clobj.getOid();
lm.requestId = nextRequestId();
// create a mapping for this marshaller so that we can
// properly dispatch responses sent to it
_listeners.put(lm.requestId, lm);
}
}
// create an invocation request event
InvocationRequestEvent event =
new InvocationRequestEvent(invOid, invCode, methodId, args);
// because invocation directors are used on the server, we set the
// source oid here so that invocation requests are properly
// attributed to the right client object when created by
// server-side entities only sort of pretending to be a client
event.setSourceOid(_cloid);
event.setSourceOid(_clobj.getOid());
// and finally ship off the invocation message
// Log.info("Sending invocation request " + event + ".");
// now dispatch the event
_omgr.postEvent(event);
return invid;
}
/**
* Registers the supplied invocation receiver instance as the handler
* for all invocation notifications for the specified module.
* Process notification and response events arriving on user object.
*/
public void registerReceiver (String module, InvocationReceiver receiver)
public void eventReceived (DEvent event)
{
if (_receivers == null) {
_receivers = new HashMap();
}
_receivers.put(module, receiver);
}
if (event instanceof InvocationResponseEvent) {
InvocationResponseEvent ire = (InvocationResponseEvent)event;
handleInvocationResponse(
ire.getRequestId(), ire.getMethodId(), ire.getArgs());
/**
* Removes the registration for the supplied invocation receiver
* instance as the handler for invocation notifications for the
* specified module.
*/
public void unregisterReceiver (String module)
{
if (_receivers != null) {
_receivers.remove(module);
} else if (event instanceof InvocationNotificationEvent) {
InvocationNotificationEvent ine =
(InvocationNotificationEvent)event;
handleInvocationNotification(
ine.getReceiverId(), ine.getMethodId(), ine.getArgs());
}
}
/**
* Process incoming message requests on user object.
* Dispatches an invocation response.
*/
public void messageReceived (MessageEvent event)
protected void handleInvocationResponse (
int reqId, int methodId, Object[] args)
{
String name = event.getName();
if (name.equals(InvocationObject.RESPONSE_NAME)) {
handleInvocationResponse(event.getArgs());
} else if (name.equals(InvocationObject.NOTIFICATION_NAME)) {
handleInvocationNotification(event.getArgs());
}
}
/**
* Processes an invocation response message.
*/
protected void handleInvocationResponse (Object[] args)
{
String name = (String)args[0];
int invid = ((Integer)args[1]).intValue();
Object rsptarg = _targets.get(invid);
if (rsptarg == null) {
Log.warning("No target for invocation response " +
"[args=" + StringUtil.toString(args) + "].");
// look up the invocation marshaller registered for that response
ListenerMarshaller listener = (ListenerMarshaller)
_listeners.remove(reqId);
if (listener == null) {
Log.warning("Received invocation response for which we have " +
"no registered listener [reqId=" + reqId +
", methId=" + methodId +
", args=" + StringUtil.toString(args) + "].");
return;
}
// prune the invocation id and method arguments from the full
// message arguments
Object[] rargs = new Object[args.length-1];
System.arraycopy(args, 1, rargs, 0, rargs.length);
// Log.info("Dispatching invocation response " +
// "[listener=" + listener + ", methId=" + methodId +
// ", args=" + StringUtil.toString(args) + "].");
// and invoke the response method; we'd cache these but the key
// for the method would have to include all of the class names of
// all of the arguments and would probably be more expensive to
// create than just reflecting the method (we should really test
// this because that's half intuition and half wild-ass guess, but
// we're going with it for now)
String mname = "handle" + name;
Method rspmeth = ClassUtil.getMethod(mname, rsptarg, rargs);
if (rspmeth == null) {
Log.warning("Unable to resolve response method " +
"[target=" + rsptarg.getClass().getName() +
", method=" + mname +
", args=" + StringUtil.toString(rargs) + "].");
return;
}
// and invoke it
// dispatch the response
try {
// Log.info("Invoking method [meth=" +
// rsptarg.getClass().getName() + "." + rspmeth.getName() +
// ", args=" + StringUtil.toString(rargs) + "].");
rspmeth.invoke(rsptarg, rargs);
} catch (Exception e) {
Log.warning("Error invoking response target method " +
"[target=" + rsptarg + ", method=" + rspmeth + "].");
Log.logStackTrace(e);
listener.dispatchResponse(methodId, args);
} catch (Throwable t) {
Log.warning("Invocation response listener choked " +
"[listener=" + listener + ", methId=" + methodId +
", args=" + StringUtil.toString(args) + "].");
Log.logStackTrace(t);
}
}
/**
* Processes an invocation notification message.
* Dispatches an invocation notification.
*/
protected void handleInvocationNotification (Object[] args)
protected void handleInvocationNotification (
int receiverId, int methodId, Object[] args)
{
String module = (String)args[0];
String proc = (String)args[1];
InvocationReceiver receiver = null;
if (_receivers != null) {
receiver = (InvocationReceiver)_receivers.get(module);
}
if (receiver == null) {
Log.warning("No receiver registered for notification " +
"[args=" + StringUtil.toString(args) + "].");
// look up the decoder registered for this receiver
InvocationDecoder decoder = (InvocationDecoder)
_receivers.get(receiverId);
if (decoder == null) {
Log.warning("Received notification for which we have no " +
"registered receiver [recvId=" + receiverId +
", methodId=" + methodId +
", args=" + StringUtil.toString(args) + "].");
return;
}
// prune the method arguments from the full message arguments
Object[] nargs = new Object[args.length-2];
System.arraycopy(args, 2, nargs, 0, nargs.length);
// Log.info("Dispatching invocation notification " +
// "[receiver=" + decoder.receiver + ", methodId=" + methodId +
// ", args=" + StringUtil.toString(args) + "].");
// and invoke the receiver method; we'd cache these but the key
// for the method would have to include all of the class names of
// all of the arguments and would probably be more expensive to
// create than just reflecting the method (we should really test
// this because that's half intuition and half wild-ass guess, but
// we're going with it for now)
String mname = "handle" + proc + "Notification";
Method rspmeth = ClassUtil.getMethod(mname, receiver, nargs);
if (rspmeth == null) {
Log.warning("Unable to resolve receiver method " +
"[target=" + receiver.getClass().getName() +
", method=" + mname +
", args=" + StringUtil.toString(nargs) + "].");
return;
}
// and invoke it
try {
rspmeth.invoke(receiver, nargs);
} catch (Exception e) {
Log.warning("Error invoking receiver method " +
"[receiver=" + receiver + ", method=" + rspmeth + "].");
Log.logStackTrace(e);
decoder.dispatchNotification(methodId, args);
} catch (Throwable t) {
Log.warning("Invocation notification receiver choked " +
"[receiver=" + decoder.receiver +
", methId=" + methodId +
", args=" + StringUtil.toString(args) + "].");
Log.logStackTrace(t);
}
}
public synchronized int nextInvocationId ()
/**
* Used to generate monotonically increasing invocation request ids.
*/
protected synchronized short nextRequestId ()
{
return _invocationId++;
return _requestId++;
}
protected static class Response
/**
* Used to generate monotonically increasing invocation receiver ids.
*/
protected synchronized short nextReceiverId ()
{
public String name;
public Object target;
public Response (String name, Object target)
{
this.name = name;
this.target = target;
}
return _receiverId++;
}
/** The distributed object manager with which we interact. */
protected DObjectManager _omgr;
protected int _imoid;
protected int _cloid;
protected int _invocationId;
protected HashIntMap _targets = new HashIntMap();
protected HashMap _receivers = new HashMap();
/** Our client object; invocation responses and notifications are
* received on this object. */
protected ClientObject _clobj;
/** Used to generate monotonically increasing request ids. */
protected short _requestId;
/** Used to generate monotonically increasing receiver ids. */
protected short _receiverId;
/** Used to keep track of invocation service listeners which will
* receive responses from invocation service requests. */
protected HashIntMap _listeners = new HashIntMap();
/** Used to keep track of invocation notification receivers. */
protected HashIntMap _receivers = new HashIntMap();
/** All registered receivers are maintained in a list so that we can
* assign receiver ids to them when we go online. */
protected ArrayList _reclist = new ArrayList();
}