I'm implementing a CQRS system with Akka persistence and I'm trying to understand the request response bit of CQRS.
There are few answers on SO on how to send response back to client and this article also mentions a few good patterns. But instead of generalising using big words can someone please explain how should I send response back to the client in CQRS for the following simple use case.
Use case
Suppose the user is on a page which displays users profile which displays the following information
Username
Address
Phone number
And In my system I have one Actor per User which stores that user's profile information.
On the UI user wants to update the address and the following things happen:
User makes an AJAX REST call to update address of user
UpdateUserAddressCommand(address:String) generated
UpdateUserAddressEvent(address:String) generated
UserAddressUpdatedEvent(updatedAddress:String) generated (state of the UserActor updated)
Now how do I send back the full state of UserProfile in the system ? Since CQRS discourages sending response for a Command ?
With respect to the CQRS pattern, the REST layer can be considered a client of the system using CQRS, and therefore you may send a response (from the REST server to the web browser) without violating a "principle".
In your case, it's quite simple:
REST call to /api/endpoint/1234 -> REST server generates the command as above.
Server returns code "202 Accepted" and sets the Location: header to
something like /api/user/profile/1234
Client queries /api/user/profile/1234 to query the full state of the UserProfile.
You can combine 3. with HTTP long polling if you are using asynchronous query side updates/eventual consistency.
Related
I am designing a microservice architecture, using a database per service pattern.
Following the example of Order Service and Shipping Service, when a user makes an HTTP REST request to the Order Service, this one fires an event to notify shipping service. All this happens asynchronously. So, what happens with the user experience? I mean, the user needs an immediate response from the HTTP request. How can I handle this scenario?
All this happens asynchronously. So, What happen with the user experience? I mean, the user needs an immediately response from the HTTP request. How can I handle this scenario?
Respond as soon as you have stored the request.
Part of the point of microservices is that you have a system composed of independently deployable elements that do not require coordination.
If you want a system that is reliable even though the services don't have 100% uptime, then you need to have some form of durable message storage so that the sender and the receiver don't need to be running at the same time.
Therefore, your basic pattern for data from the outside is that the information from the incoming HTTP request is copied, not directly into a running service, but instead into the message store, to be processed by the service at some later time.
In other words, your REST API is a facade in front of your storage, not in front of the service itself.
The actor model may be a useful analogy; information moves around by copying messages into different inboxes, and are later consumed by the subscribing actor.
From the perspective of the client, the HTTP response is an acknowledgement that the request has been received and recognized as valid. Think "thank you for your order, we'll send you an email when your purchase is ready for pick up."
On the web, we would include in the response links to other useful resources; click here to see the status of your order, click there to see your history of recent orders, and so on.
An auth system I work on has this new function:
1. Auth system allows users to specify Relying Parties they transact with,
2. The Relying Party can approve/deny/maybe the request (authorisation) - maybe causes a redirect to the RP website for further authorisation questions by the RP.
The RP has to implement a web service specified by the Auth System to perform the approve/deny/maybe request that the auth system generates.
My problem is what this looks like as a REST service. As the auth system can't really dictate the URI style for the RP system, i would like to specifying that the path does not have any parameters in it, auth system just needs to know the URI of the service. The data of the request (user name/id) might be in a bit of json in the request body (suggesting POST http verb. GET might be OK, but loath to expose user ids in the URI). The auth system does not care what the RP does with the request data, the auth system just wants a "yes/no/maybe" reply (so may not really be a GET/POST/PATCH/DELETE/etc paradigm).
What would be the best verb to use? and how to facilitate the reply; its not really a success/failure response as there are 3 possible results to the query, is it acceptable to have some json returned with the response (then what http verb to use)?
I'm a bit baffled by this. GET seems the most obvious
GET /api/user_link_authorize/{userid}
except then i'm forced to put user ids in the URI (which I dont want to do)...
Any suggestions?
My problem is what this looks like as a REST service.
Think about how it would look as a web site.
You would start with some known URI in your list of bookmarks. Fetching that page would give you a representation of a form, which would have input controls that describe what data needs to be provided (and possibly includes default values). The client provides the data it knows about, and submits the form. The data in the form is used to create a HTTP request as described by HTML's form processing rules. The response to that request includes a representation of the answer, or possibly the next bit of work to be done.
That's REST.
Retrieving the form (via the bookmarked URI) would be a GET of course; we're just updating our locally cached copy of the forms "current" representation. Submitting the form could be a GET or a POST; we don't necessarily need to know that in advance, because that information is carried in the representation of the form itself.
GET vs POST involves a number of trade offs. Semantically, GET is safe, it implies that the resource can be fetched at any time, that spiders can crawl it, that accessing the resource in that way is "free". Which is great when the resource is free, because clients on an unreliable network can automatically retry the request if the response is lost. On the other hand, announcing to the world that the request is safe when it is actually expensive to produce responses is not a winning play.
Furthermore, GET doesn't support a message body (more precisely, the payload has no defined semantics). That means that information provided by the client needs to be part of the target resource identifier itself. If you are dealing with sensitive information, that can be problematic -- not necessarily in transit (you can use a secured socket), but certainly in making sure that the URI with sensitive information is not logged where the sensitive data can leak.
POST supports including a payload with the request, but it doesn't promise that the query is safe, which means that generic components won't know if they can automatically retry the request when a response is lost.
Given that you don't want the user id in the URI, that's a point against GET, and therefore in favor of POST.
I use an authentication service Auth0 to allow users to log into my application. The application is a Q&A platform much like stackoverflow. I store a user profile on my server with information such as: 'about me', votes, preferences, etc.
When new user signs in i need to do 1 of 2 things:
For an existing user - retrieve the user profile from my api server
For a new user - create a new profile on the database
After the user signs in, Auth0(the authentication service) will send me some details(unique id, name and email) about the user but it does not indicate whether this is a new user(a sign up) or a existing user(a sign in).
This is not a complex problem but it would be good to understand best practice. I can think of 2 less than ideal ways to deal with this:
**Solution 1 - GET request **
Send a get request to api server passing the unique id
If a record is found return it
Else create new profile on db and return the new profile
This seems incorrect because the GET request should not be writing to the server.
**Solution 2 - One GET and a conditional POST request **
Send a get request to api server passing the unique id
The server checks the db and returns the profile or an error message
If the api server returns an error message send a post request to create a new profile
Else redirect to the home page
This seems inefficient because we need 2 requests to achieve a simple result.
Can anyone shed some light on what's best practice?
There's an extra option. You can use a rule in Auth0 to send a POST to the /users/create endpoint in your API server when it's the first time the user is logging in, assuming both the user database in Auth0 and in your app are up-to-date.
It would look something like this:
[...]
var loginCount = context.stats.loginsCount;
if (loginCount == 1) {
// send POST to your API and create the user
// most likely you'll want to await for response before moving on with the login flow
}
[...]
If, on the other hand, you're referring to proper API design and how to implement a find-or-create endpoint that's RESTful, maybe this answer is useful.
There seems to be a bit of disagreement on the best approach and some interesting subtleties as discussed in this post: REST Lazy Reference Create GET or POST?
Please read the entire post but I lean towards #Cormac Mulhall and #Blake Mitchell answers:
The client wants the current state of the resource from the server. It is not aware this might mean creating a resource and it does not care one jolt that this is the first time anyone has attempted to get this resource before, nor that the server has to create the resource on its end.
The following quote from The RESTful cookbook provided by #Blake Mitchell makes a subtle distinction which also supports Mulhall's view:
What are idempotent and/or safe methods?
Safe methods are HTTP methods that do not modify resources. For instance, using GET or HEAD on a resource URL, should NEVER change the resource. However, this is not completely true. It means: it won't change the resource representation. It is still possible, that safe methods do change things on a server or resource, but this should not reflect in a different representation.
Finally this key distinction is made in Section 9.1.1 of the HTTP specification:
Naturally, it is not possible to ensure that the server does not
generate side-effects as a result of performing a GET request; in
fact, some dynamic resources consider that a feature. The important
distinction here is that the user did not request the side-effects,
so therefore cannot be held accountable for them.
Going back to the initial question, the above seems to support Solution 1 which is to create the profile on the server if it does not already exist.
I had a use case that there is a server that can have n number of source. There can be several clients that can connect to this server and get the sources list and then can subscribe to the server to listen the source add, update and delete operation.
To implement this with REST principle, I have thought that first time when the client gets connected, the server gives the full source list along with the session id. Then with this session id, the client polls the url after a configured time interval and listen to the source updates.
The communication will looks like
Client>
GET: /Federation/Sources
Server>>
{"sessionId":xyz,"data":{"source1"...........}}
Client>
GET: /Federation/Sources/{sessionId}
Server>>
{"sessionId":xyz,"data":{"sourceadded"...........}}
Client>
PUT: /Federation/Sources/{sessionId}
{"data":{"Recieved"}}
This client call will then updates the server to remove the source correspond to this session id.
And then client poll continues with the session id.
Can expert please give their feedbacks or comments if this is a good approach or can there be any alternative good approach that can be follow with REST principle?
Instead of passing back id's for the client to use to build the URL, simply pass back the entire URL to the client. Perhaps with more information about what the URL is for. This is the HATEOAS part of REST.
Without moving away from the RESTful paradigm, how could you model object validation in a RESTful way? Best to explain the theoretical use case I've come up with...
Imagine you have a system with a very thin web layer making calls to back-end RESTful services. Say a user visited a registration form and submitted it, the web layer would send the unvalidated data straight to a back-end service and, if the service responds with validation errors in JSON format, these can be sent back to the user as HTML.
However, imagine we want to have AJAX behaviour on the form. For example, the user enters their email address and we want to validate using AJAX, sending an error to the user if their email address is already registered.
Would it make sense to implement a single call to validate just the email address, or could the whole object be sent and validated in a back-end service? If the latter, what URL could you use to only validate an object, rather than actually create it?
In the past I have used the notion of a sandbox sub-resource to do what you are suggesting,
http://example.com/customer/23/sandbox
This allows me to POST deltas and have the changes applied and validated but not actually committed. This works quite well for the traditional "save/cancel" type dialogs.
However, I found dealing with those deltas to be a real pain, so I developed a different media type that recorded a sequence of events on the client and then posted that document to the sandbox resource. By replaying the sequence of events I could update and validate the server side resource in a simpler fashion.
Later on I realized that I really didn't need the distinct "sandbox" resource and now I just post the "sequence of events" document directly to the resource it is affecting. I have some data in the document itself that determines whether the changes are going to be permanent or just transient. It just depends if the user has pressed the save button yet or not.
Validating a single form field can improve user experience while the user is filling the form, but when the form is submitted, I would validate the whole object, because it's less error prone. The URL can be simply https://mysite.com/users/emailvalidator for validating the e-mail only (a single field), and the form could be POSTed to https://mysite.com/users (the whole object). In the former case, the URL tells clearly that the resource you want to use is an object which is able to validate an e-mail.