Search code examples
javapythonjmsmessageamqp

sending a piece of code in message


I am not sure it's reasonable, but sending a piece of code through message(AMQP, JMS, ZeroMQ) makes much sense in some situation.

We usually use message as plain data which is information made up of primitives(for example, integer, long, string ...). The problem of plain data is it can not represent logic. For instance I have a message like

class OperationMsg {
     String conditionA;
     String conditionB;
     String conditionC;
}

Service A sends this message to other services to instruct them to do some operations. The operation flow is not only decided by conditions encapsulated in message but also the context that services currently have. Then each service has to hard code like:

if (msg.conditionA == something && self.context.someContext == something) {
   doSomethingA();
} else if (msg.conditionB == somethind && msg.conditionA != something && self.context.sometContext == something) {
   doSomethingB();
}

If we want to decouple these code from service we have to use some visitor pattern(GoF), however, it's not possible as we are communicating through message and each service may not be in the same process or machine.

So I am thinking if we can send code in message which would do similar like visitor pattern but through message. For dynamic language like Python it's doable because of eval() function, for static language like Java, it's much harder and I am thinking of using some expression language.

However, I am not sure if this idea sounds weird, please free feel to share your thoughts.


Solution

  • I would not recommend representing logic inside of a message payload. There exists the chance for code injection issues, and it seems like it would be messier to represent logic inside of a generally free-form message from an SCM perspective, etc.

    You can represent logic at a higher level -- to a point -- using the routing key.

    i.e. you could include the general type inside of the routing key, and then your code can parse the routing key and handle the logic accordingly. That way, the message influences the logic, but doesn't contain the actual logic, per se.