Creating Self-Documenting Actors in Scala - scala

I'm looking at implementing a JSON-RPC based web service in Scala using finagle. I'm trying to work out how best to structure the RPC invocation code (ie. taking the deserialized request and invoking the appropriate method).
The service needs to be able to spit out a help page on all the possible requests accepted and their parameters. In Java, I would simply use annotations (to both expose and document functions) and then have the RPC service reflect on the appropriate classes, detect all exposed methods and then use the reflected MethodInfo's to invoke the functions where appropriate.
What is the idiomatic Scala way to achieve something similar? Should I use a message-passing approach (ie. just pass a request object into an actor, have it determine if it can invoke it, etc.)

We had success doing something similar to the approach suggested by #Jan above. More specifically, we defined a parent class for all request objects which takes the expected return type as a type parameter. Going one step further, we're generating our protocol IDL and serialization bindings by reflecting on API objects (little more than sets of requests).
In the future, the experimental typed channels feature in Akka may help with some of the mechanics.

Related

CDK constructs: passing values to constructors vs using the context values

I wrote a small cdk construct that parses the logs in a cloudwatch log group via a lambda and sends a mail when a pattern is matched. This allows a developer to be notified via an sns topic, should an error appear in the logs.
The construct needs to know which log group to monitor, and which pattern to look for. These are currently passed in as parameters to its constructor. The user of my small construct library is supposed to use this construct as part of his stack. However, one could also define them as parameters, or better yet given what the docs say values in a context - basically using this construct in a standalone app.
Would this be an appropriate use of the context? What else it is useful for?
It's hard to say a definitive answer, but I would recommend always passing in properties to a construct explicitly on the constructor.
A) This creates consistency with the rest of the constructs.
B) Nothing is 'hidden' in your construct definition.
The only thing I've generally found context useful for is passing in parameters from the CLI, but even that is pretty rare and there are often better ways to do it.

Validating input parameters for JAX-RS methods

I'm writing a JAX-RS API, and am using the Response class as the return type of each method. However, I'm trying to figure out the "best" approach to validate parameters.
I've written some REST APIs before, and would usually have custom validation routines in the method and then have a custom return object with validation messages in it. I'm thinking I want to do the same here, but is that "preferred"?
I know there are annotations like #NotNull, etc. that you can apply and provide custom validation messages, but I don't really like the way that ends up looking.
So, what I did is that I wrote a return object bean that I'm using as the .entity() for my JAX-RS response, and I'm putting all of my validation messages in there. I use the same return object for Successes and Failures, but it's just a matter of which parameters I populate in there depending on the scenario. This is an internal API, so there won't be any external consumers. I just wanted to standardize the return type so it always returns the same "object".
Does that sound like a good approach? I'm a little rusty on REST API best practices, and I've been googling around like crazy but haven't really come to any best practices conclusions.
Input validation for RestAPI is not straight forward. There are a lot of internet resources, but none covers an elegant way of doing this.
As you mentioned the trivial input validations can be done using the annotation of different implementations of jax-rs library.
These annotations can be sophisticated as regex is supported. Which will help you cover more validation cases than #NotNull, #size , etc.
Theses annotations also accept message as input, which will help you customize a message that has to be returned to a user.
Those annotations may not look sexy (specially when regex is involved); but I would still prefer it over writing my own validator.
The other concern of validation which is a little bit tricky is when you want to validate constraints (more like a logic),
say for example you have this requirement: if parameter A has value X, Parameter B must have not be empty, otherwise it is OK to have parameter B empty.
This is not something you could handle using the usual javax.validation.constraints.*. I didn't find a good library that could handle this.
take a look at
javax.validation.ConstraintViolation
you could write your own custom validation logic that will be called whenever the library intercepts call to your API.

Method contract without Traits in Scala

I'm trying to add some re-usability to a Java library which has some common methods across classes, but whose methods are not part of a common hierarchy. I'm pretty certain I've seen it previously that Scala allows non-trait based contracts for parameter classes, but for the life of me I cannot find this information anywhere at the moment.
Does my memory serve me correctly? Would anybody be able to point me in the right direction for documentation on said language feature (if I am not mistaken)?
For some added context, I'm trying to reduce duplicate code when using some Google Java libraries where things like getNextPageToken(), setPageToken(), etc. are common between many classes, but are not implemented further up in the hierarchy where I would have the option to specify a common parent class as the parameter type. So essentially I'd like to enforce that these methods exist and offload the duplicate request & pagination code to a common function using said method contracts.
You probably want to use structural types:
example:
def method(param: { def getNextPageToken(): Unit })
param will be required to have getNextPageToken method with no parameters and returning Unit. It is handled using reflection.

jsonrpc2 returning remote reference

I'm exploring jsonrpc 2 for a web service. I have some experience with java rmi and very much liked that. To make things easy I using the zend framework so I think I like to use that library. There is however one thing i am missing. how do I make a procedure send back a reference to an other object.
I get that is not within the protocol because its about procedures but it would still be a useful thing. Like with the java rmi I could pick objects to send by value (serialize) or reference (remote object proxy). So what is the best way do solve this? are there any standards for this that most library's use?
I spend a view hours on google looking for this and can think of a solution (like return a url) but, I would rather use a standard then design something new.
There is one other thing i would like your opinion on. I heard an architect rand about the protocol's feature of sending batches of call's. Are the considered nice or dirty? (he thinks they where ugly but i can think of use for then)
update
I think the nicesed way is just to return a remoteref object with a url to the object. That way its only a small wrappen and a litle documentation. Yet i would like to know if there is a commen way to do this.
SMD Posibilitie's
There might be some way to specify the return type in my smd, is there anyone with idears of how to give a reference to another page in my smd return type? Or does anyone know a good explenation for the zend_json_smd class?
You can't return a reference of any kind via JSON-RPC.
There is no standard to do so (afaik) because RPC is stateless, and most developers prefer it that way. This simplicity is what makes JSON-RPC so desirable to client-side developers over SOAP (and other messes).
You could however adopt a convention in your return values that some JSON constructs should be treated as "cues" to manufacture remote "object" proxies. For example, you could create a modified JSON de-serialiser that turns:
{
"__remote_object": {
"class": "Some.Remote.Class",
"remote_id": 54625143,
"smd": "http://domain/path/to/further.smd",
"init_with": { ... Initial state of object ... }
}
}
Into a remote object proxy by:
creating a local object with a prototype named after class, initialised via init_with
downloading & processing the smd URL
creating a local proxy method (in the object proxy) for each procedure exposed via the API, such that they pass the remote_id to the server with each call (so that the server knows which remote object proxy maps to which server-side object.)
While this scheme would be workable, there are plenty of moving parts, and the code is much larger and more complicated on the client-side than for normal JSON-RPC.
JSON-RPC itself is not well standardised, so most extensions (even SMD) are merely conventions around method-names and payloads.

Creating A Single Generic Handler For Agatha?

I'm using the Agatha request/response library (and StructureMap, as utilized by Agatha 1.0.5.0) for a service layer that I'm prototyping, and one thing I've noticed is the large number of handlers that need to be created. It generally makes sense that any request/response type pair would need their own handler. However, as this scales to a large enterprise environment that's going to be A LOT of handlers.
What I've started doing is dividing up the enterprise domain into logical processor classes (dozens of processors instead of many hundreds or possibly eventually thousands handlers). The convention is that each request/response type (all of which inherit from a domain base request/response pair, which inherit from Agatha's) gets exactly one function in a processor somewhere.
The generic handler (which inherits from Agatha's RequestHandler) then uses reflection in the Handle method to find the method for the given TREQUEST/TRESPONSE and invoke it. If it can't find one or if it finds more than one, it returns a TRESPONSE containing an error message (messages are standardized in the domain's base response class).
The goal here is to allow developers across the enterprise to just concern themselves with writing their request/response types and processor functions in the domain and not have to spend additional overhead creating handler classes which would all do exactly the same thing (pass control to a processor function).
However, it seems that I still need to have defined a handler class (albeit empty, since the base handler takes care of everything) for each request/response type pair. Otherwise, the following exception is thrown when dispatching a request to the service:
StructureMap Exception Code: 202
No Default Instance defined for PluginFamily Agatha.ServiceLayer.IRequestHandler`1[[TSFG.Domain.DTO.Actions.HelloWorldRequest, TSFG.Domain.DTO, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], Agatha.ServiceLayer, Version=1.0.5.0, Culture=neutral, PublicKeyToken=6f21cf452a4ffa13
Is there a way that I'm not seeing to tell StructureMap and/or Agatha to always use the base handler class for all request/response type pairs? Or maybe to use Reflection.Emit to generate empty handlers in memory at application start just to satisfy the requirement?
I'm not 100% familiar with these libraries and am learning as I go along, but so far my attempts at both those possible approaches have been unsuccessful. Can anybody offer some advice on solving this, or perhaps offer another approach entirely?
I'm not familiar with Agatha. But if you want all requests for IRequestHandler<T> to be fulfilled by BaseHandler<T>, you can use the following StructureMap registration:
For(typeof(IRequestHandler<>)).Use(typeof(BaseHandler<>));
When something asks for an IRequestHandler<Foo>, it should get a BaseHandler<Foo>.