Passing values from request to all the layers below controller - scala

If a Play controller retrieves a values from the Request (e.g. logged in user and his role) and those values need to be passed to all the layers down to controllers (e.g. service layer, DAO layer etc) what's the best way to create a "threadlocal" type of object, which can be used by any class in the Application to retrieve those "user" and "userRole" values for that particular request? I am trying to avoid adding implicit parameters to a bunch of methods and Play Cache doesn't look like an appropriate fit here. Also play's different scope (session, flash etc) wouldn't behave right given all the code is asynchronous. Controller methods are async, service methods returns Future etc. That "threadlocal" type of effect in an asynchronous environment is desired.

Alternatives that are not a good fit
These alternatives are probably not helpful, because they assume a global state accessible by all functions across the processing of a request:
Thread local storage is a technique that is helpful for applications that process the request in a single thread, and that block until a response is generated. Although it's possible to do this with Play Framework, it's usually not the optimal design, since Play's strengths are of more benefit for asynchronous, non-blocking applications.
Session and flash are meant to carry data across HTTP requests. They're not globally available to all classes in an application; it would be necessary to pass the modified request across function calls to retrieve them.
A cache could in theory be used to carry this information, but it would have to have a unique key for each request, and it would be necessary to pass this key in each function call. Additionally, it would be necessary to make sure the cache data is not at risk of being evicted while processing the request, not even when cache memory is full.
Alternatives that may be a good fit
Assuming the controller, possibly though the Action call, retrieves the security data (user, role, etc.), and that the controller only deals with validating the request and generating a response, delegating domain logic to a domain object (possibly a service object):
Using the call stack: Pass the security data to all functions that need it, through an implicit parameter. Although the question is about finding an alternative to doing that, this approach makes it explicit what is being sent to the called function, and which functions require this data, instead of resorting to state maintained elsewhere.
Using OOP: Pass the security data in the constructor of the domain object, and in the domain object's methods, retrieve the security data from the object's instance.
Using actors: Pass the security data in the message sent to the actor.
If a domain object's method calls a function that also needs the security data, the same pattern would be applied: either pass it as (a possibly implicit) parameter, through a constructor, or in a message.

Related

Should model of a request for a PUT method be the same class with the model of the response of the GET method?

In my app, the backend will use an endpoint to get and update data (with GET and PUT method). The exact same JSON schema is used for both operations. The question is, should I also use the same model for the update request body and the get response body for this or not? Can you tell me the pros and cons of either separating and combining them?
Thanks.
Should model of a request for a PUT method be the same class with the model of the response of the GET method?
See RFC 7231:
A successful PUT of a given representation would suggest that a subsequent GET on that same target resource will result in an equivalent representation being sent in a 200 (OK) response.
It is normal that the PUT request will have the same Media Type as a successful GET response for that target-uri.
HTTP defines the semantics of the messages, but doesn't constrain the implementation (see Fielding 2002).
That said, if GET and PUT are using representations that change for the same reason, then a common implementation is reasonable, so it will likely be easier to maintain your code when those two paths share the same underlying model.
what about the Single Responsibility Principle if it's the same class?
My answer is that the Single Responsibility Principle doesn't actually make your code better in this case, so you don't use it. There are different ways you can try to generalize that idea; one is that you are working with a data structure, not an "object". Another is that this information is crossing a boundary, and at the boundaries, applications are not object-oriented.
Expressing that idea somewhat differently: what you have here is a single responsibility (manage some in memory representation of the message), but two different roles; an outbound role for the GET scenario (where you need to be able to convert the message into bytes, describe the content-type, and so on), and an inbound role for the PUT scenario (where you need to extract units of information from the data structure).

Dependency between data store

TL;DR
What's the best way to handle dependency between types of data that is loaded asynchronously from different backend endpoints?
Problem
My app fetches data from a backend, for each entity I have an endpoint to fetch all instances.
For example api.myserver.com/v1/users for User model and api.myserver.com/v1/things for Thing model.
This data is parsed and placed into data store objects (e.g. UserDataStore and ThingDataStore) that serve these models to the rest of the app.
Question
What should I do if the data that comes from /things depends on data that comes from /users and the fetch operations are async. In my case /things returns the id of a user that created them. This means that if /things returns before /users, then I won't have enough data to create the Thing model.
Options
Have /things return also relevant /users data nested.
This is bad because:
I'll then have multiple model instances User for the same actual user - one that came from /users and one that came nested in /things.
Increases the total payload size transferred.
In a system with some permission policy, data that is returned for /users can be different to /things, and then it'll allow partially populated models to be in the app.
Create an operational dependency between the two data stores, so that ThingsDataStore will have to wait for UserDataStore to be populated before it attempts to load its own data.
This is also bad because:
Design-wise this dependency is not welcome.
Operational-wise, it will very quickly become complicated once you throw in another data stores (e.g. dependency cycles, etc).
What is the best solution for my problem and in general?
This is obviously not platform / language dependent.
I see two possible solutions:
Late initialization of UserDataStore in ThingDataStore. You will have to allow for creation an object that is not fully valid. And you will also need to add method that will give you an information whether UserDataStore is initialized or not. Not perfect, because for some time there will exists an invalid instance.
Create some kind of proxy or maybe a buider object for ThingDataStore that will hold all information about particular thing and will create ThingDataStore object as soon as UserDataStore related with this instance will be received.
Maybe it will help you. Good luck!

Is there a way in scala to execute arbitrary code on a remote node around using RemoteActor?

For example, I have a trusted client and a server. The client wants to execute arbitrary code on the server. Can this be achieved using RemoteActor (serialize a function and send it across the network, deserialize it and execute it)?
Here's an example of using URLClassLoader with remote actors, to fetch the classes via http from the client and execute generic computations on the server.
You may also be interested in HotSwap technique applied to serializable Akka Actors.
Not currently. Serializing a function means storing its fields into a object output stream and deserializing it means reading the function object from an object input stream somewhere else. Deserialization presumes that the class of the object being read from the object input stream is known to the JVM. Remember - functions are just objects behind the scene.
In this case, the server does not know the actual concrete class of the function object you're serializing, just possibly that it implements the Function interface. To support such a functionality, you'd have to locate the class file of the function in question, send it to the server, and load it on the server using a custom classloader. Then, if the object has any kind of state, you could serialize the object on the client, send it over the network and deserialize it on the server. Only then can you run its methods. Assuming your function objects are stateless, which is usually the case, you could skip the serialization/deserialization step.
EDIT:
Remember, also, that functions may internally hold references to their calling environments. This means you might end up serializing the environment of a function object along with it, which can potentially be your entire program data..

How should I deal with object hierarchies in a RESTful API?

I am currently designing the API for an existing PHP application, and to this end am investigating REST as a sensible architectural approach.
I believe I have a reasonable grasp of the key concepts, but I'm struggling to find anybody that has tackled object hierarchies and REST.
Here's the problem...
In the [application] business object hierarchy we have:
Users
L which have one-to-many Channel objects
L which have one-to-many Member objects
In the application itself we use a lazy load approach to populate the User object with arrays of these objects as required. I believe in OO terms this is object aggregation, but I have seen various naming inconsistencies and do not care to start a war about the precise naming convention </flame war>.
For now, consider I have some loosely coupled objects that I may / may not populate depending on application need.
From a REST perspective, I am trying to ascertain what the approach should be. Here is my current thinking (considering GET only for the time being):
Option 1 - fully populate the objects:
GET api.example.com/user/{user_id}
Read the User object (resource) and return the User object with all possible Channel and Member objects pre-loaded and encoded (JSON or XML).
PROS: reduces the number of objects, no traversal of object hierarchies required
CONS: objects must be fully populated (expensive)
Option 2 - populate the primary object and include links to the other object resources:
GET api.example.com/user/{user_id}
Read the User object (resource) and return the User object User data populated and two lists.
Each list references the appropriate (sub) resource i.e.
api.example.com/channel/{channel_id}
api.example.com/member/{member_id}
I think this is close to (or exactly) the implications of hypermedia - the client can get the other resources if it wants (as long as I tag them sensibly).
PROS: client can choose to load the subordinates or otherwise, better separation of the objects as REST resources
CONS: further trip required to get the secondary resources
Option 3 - enable recursive retrieves
GET api.example.com/user/{user_id}
Read the User object and include links to lists of the sub-objects i.e.
api.example.com/user/{user_id}/channels
api.example.com/user/{user_id}/members
the /channels call would return a list of channel resources in the form (as above):
api.example.com/channel/{channel_id}
PROS: primary resources expose where to go to get the subordinates but not what they are (more RESTful?), no requirement to get the subordinates up front, the subordinate list generators (/channels and /members) provide interfaces (method like) making the response more service like.
CONS: three calls now required to fully populate the object
Option 4 - (re)consider the object design for REST
I am re-using the [existing] application object hierarchy and trying to apply it to REST - or perhaps more directly, provide an API interface to it.
Perhaps the REST object hierarchy should be different, or perhaps the new RESTful thinking is exposing limitations of the existing object design.
Any thoughts on the above welcomed.
There's no reason not to combine these.
api.example.com/user/{user_id} – return a user representation
api.example.com/channel/{channel_id} – return a channel representation
api.example.com/user/{user_id}/channels – return a list of channel representations
api.example.com/user/{user_id}/channel_list – return a list of channel ids (or links to their full representations, using the above links)
When in doubt, think about how you would display the data to a human user without "API" concerns: a user wants both index pages ({user_id}/channel_list) and full views ({user_id}/channels).
Once you have that, just support JSON instead of (or in addition to) HTML as the representation format, and you have REST.
The best advice I can give is to try and avoid thinking about your REST api as exposing your objects. The resources you create should support the use cases you need. If necessary you might create resources for all three options:
api.example.com/completeuser/{id}
api.example.com/linkeduser/{id}
api.example.com/lightweightuser/{id}
Obviously my names are a bit goofy, but it really doesn't matter what you call them. The idea is that you use the REST api to present data in the most logical way for the particular usage scenario. If there are multiple scenarios, create multiple resources, if necessary. I like to think of my resources more like UI models rather than business entities.
I would recommend Restful Obects which is standards for exposing domain model's restful
The idea of Restful Objects is to provide a standard, generic RESTful interface for domain object models, exposing representations of their structure using JSON and enabling interactions with domain object instances using HTTP GET, POST, PUT and DELETE.
According to the standard, the URIs will be like:
api.example.com/object/user/31
api.example.com/object/user/31/properties/username
api.example.com/object/user/31/collections/channels
api.example.com/object/user/31/collections/members
api.example.com/object/user/31/actions/someFunction
api.example.com/object/user/31/actions/someFunction/invoke
There are also other resources
api.example.com/services
api.example.com/domain-types
The specification defines a few primary representations:
object (which represents any domain object or service)
list (of links to other objects)
property
collection
action
action result (typically containing either an object or a list, or just feedback messages)
and also a small number of secondary representations such as home, and user
This is interesting as you’ll see that representations are fully self-describing, opening up the possibility of generic viewers to be implemented if required.
Alternatively, the representations can be consumed directly by a bespoke application.
Here's my conclusions from many hours searching and with input from the responders here:
Where I have an object that is effectively a multi-part object, I need to treat that as a single resource. Thus if I GET the object, all the sub-ordinates should be present. This is required in order that the resource is cacheable. If I part load the object (and provide an ETag stamp) then other requestors may receive a partial object when they expected a full one. Conclude - objects should be fully populated if they are being made available as resources.
Associated object relationships should be made available as links to other (primary) resources. In this way the objects are discoverable by traversing the API.
Also, the object hierarchy that made sense for main application site may appear not be what you need to act in RESTful manner, but is more likely revealing problems with the existing hierarchy. Having said this the API may require more specialised use cases than had been previously envisaged, and specialised resources may be required.
Hope that helps someone

Isn't resource-oriented really object-oriented?

When you think about it, doesn't the REST paradigm of being resource-oriented boil down to being object-oriented (with constrained functionality, leveraging HTTP as much as possible)?
I'm not necessarily saying it's a bad thing, but rather that if they are essentially the same very similar then it becomes much easier to understand REST and the implications that such an architecture entails.
Update: Here are more specific details:
REST resources are equivalent to public classes. Private classes/resources are simply not exposed.
Resource state is equivalent to class public methods or fields. Private methods/fields/state is simply not exposed (this doesn't mean it's not there).
While it is certainly true that REST does not retain client-specific state across requests, it does retain resource state across all clients. Resources have state, the same way classes have state.
REST resources are are globally uniquely identified by a URI in the same way that server objects are globally uniquely identified by their database address, table name and primary key. Granted there isn't (yet) a URI to represent this, but you can easily construct one.
REST is similar to OO in that they both model the world as entities that accept messages (i.e., methods) but beyond that they're different.
Object orientation emphasizes encapsulation of state and opacity, using as many different methods necessary to operate on the state. REST is about transfer of (representation of) state and transparency. The number of methods used in REST is constrained and uniform across all resources. The closest to that in OOP is the ToString() method which is very roughly equivalent to an HTTP GET.
Object orientation is stateful--you refer to an object and can call methods on it while maintaining state within a session where the object is still in scope. REST is stateless--everything you want to do with a resource is specified in a single message and all you ever need to know regarding that message is sent back in a single response.
In object-orientation, there is no concept of universal object identity--objects either get identity from their memory address at any particular moment, a framework-specific UUID, or from a database key. In REST all resources are identified with a URI and don't need to be instantiated or disposed--they always exist in the cloud unless the server responds with a 404 Not Found or 410 Gone, in whch case you know there's no resource with that URI.
REST has guarantees of safety (e.g., a GET message won't change state) and idempotence (e.g., a PUT request sent multiple times has same effect as just one time). Although some guidelines for particular object-oriented technologies have something to say about how certain constructs affect state, there really isn't anything about object orientation that says anything about safety and idempotence.
I think there's a difference between saying a concept can be expressed in terms of objects and saying the concept is the same as object orientation.
OO offers a way to describe REST concepts. That doesn't mean REST itself implements OO.
You are right. Dan Connolly wrote an article about it in 1997. The Fielding thesis also talks about it.
Objects bundle state and function together. Resource-orientation is about explicitly modeling state(data), limiting function to predefined verbs with universal semantics (In the case of HTTP, GET/PUT/POST/DELETE), and leaving the rest of the processing to the client.
There is no equivalent for these concepts in the object-orientation world.
Only if your objects are DTOs (Data Transfer Objects) - since you can't really have behavior other than persistence.
Yes, your parallel to object-orientation is correct.
The thing is, most webservices (REST, RESTful, SOAP,..) can pass information in the form of objects, so that isn't what makes it different. SOAP tends to lead to fewer services with more methods. REST tends to lead to more services (1 per resource type) with a few calls each.
Yes, REST is about transfer of objects. But it isn't the whole object; just the object's current state. The implicit assumption is that the class definitions on both sides of the REST are potentially similar; otherwise the object state has been coerced into some new object.
REST only cares about 4 events in the life on an object, create (POST), retrieve (GET), update (PUT) and delete. They're significant events, but there's only these four.
An object can participate in lots of other events with lots of other objects. All the rest of this behavior is completely outside the REST approach.
There's a close relationship -- REST moves Objects -- but saying they're the same reduces your objects to passive collections of bits with no methods.
REST is not just about objects, its also about properties :: a post request to /users/john/phone_number with a new phone number is not adding a new object, its setting a property of the user object 'john'
This is not even the whole state of the object, but only a change to a small part of the state.
It's certainly not a 1:1 match.