NodeJS Service Layer asynchronous communication - node.js

If I have to invoke ServiceB.action as a result of ServiceA.action being invoked, should I call ServiceB.action from ServiceA.action at the appropriate time, or should I emit an event from ServiceA and let ServiceB react to that event?
I can use an EventEmitter, but it works synchronously, in a sense that the callbacks are invoked sequentially without waiting the previous to resolve, which is ok for me. What isn't, though, is that the $emit will not wait until all of the listeners have resolved.
For a more real world scenario, lets assume that I have a Subscription service, and when a new subscription is created, the Email service needs to know about it so that it can notify somebody by email.
const SubscriptionService = {
async create(user) {
await Subscription.create(user)
// Notify email service
}
}
const EmailService = {
async notify(user) {...}
}
One way I could do it, is call the EmailService.notify(user) from SubscriptionService.create and pass in the user.
Another way I could do it is with an event emitter
async create(user) {
await Subscription.create(user)
Emitter.$emit('subscription', user)
}
The second approach seems clean, because I'm not mixing things together, the notifications happen as a result of the subscription being created and the create method is not polluted with extra logic. Also, adding more side-effects like the notification one would be simpler.
The subscription service's create method, however, will not wait until all of the listeners have resolved, which is an issue. What if the Notification fails? The user will not get the email, in this scenario. What about error handling? In the first scenario I can handle the errors on spot when I invoke the EmailService.notify, but not with the emitter.
Is not meant for similar use-cases or am I looking at the problem in a wrong way?

The event pattern is the most appropriate for the scenario you described. Rather than using std event emitters you could use promise-events which should let you do error handling as it seems you described.
Hope this helps.

Since the create method returns a Promise, you can just do something like:
SubscriptionService.create(user).then((user) => EmailService.notify(user));
Note: The above depends on where and how you're calling these methods.

Both of the approaches are appliable and correct for specific scenarios.
Pub/Sub is great for the applications where there are few subscribers and does various jobs in the background. Publishers(SubscriptionService.create) are loosely coupled to the subscribers-(EmailService.notify)
Service layer exists for applying business logics, and nothing wrong with using function composition for more than one methods which serves for a single operation. If it should notify user after subscription has been created, yes those two methods can work together. Also, if you want to use EmailService.notify method in somewhere else, you have to publish a new event, and create a new subscriber for that too, because you can't just use the previously created subscriber.
Personally, I would prefer, calling ServiceB.action inside ServiceA.action on your scenario. Publishing an event and creating a subscriber in the ServiceB is looks a bit much.

Related

Is it good practice to internally call an API within the server?

I have some codes as follows
// [DELETE] /api/v1/authors/:id
async deleteAuthor(req, res) {
const author = await Author.findByIdAndRemove(req.params.id);
// delete blogs of the author
axios.delete(
`http://localhost:${process.env.PORT}/api/v1/blogs/author/${author._id}`,
{
headers: {
Authorization: req.headers.authorization
}
}
);
res.status(200).send();
}
By this, I want to delete an author and all their blogs. I know the naming of the uri is not good but is it overall a good way to code like this or there are other ways to do the same thing. I'm using Node.js and Mongoose
I think is not a good practice, you should avoid making circular HTTP Calls (Not optimal, can unnecessary duplicate logic, and is more difficult to read your code)
What do I suggest? Following DDD & Hex. Architecture:
Have separated services e.g. RemoveAuthor & RemoveAuthorBlogs
(Following the SRP principle of SOLID, one service do only one
thing)
Your HTTP endpoints (E.g. DELETE /author/:id & DELETE /blogs/author/:id) will invoke those services.
If you need to delete the author and his blogs in the same request.
a. Create a high service that calls to RemoveAuthor and RemoveAuthorBlogs (E.g. RemoveAuthorReferences)
b. (My vote is for this) => The service RemoveAuthor remove from DB the author as the first step and as the second step will dispatch a domain event (E.g. AuthorDeleted that will be listened to by an EventHandler (E.g. DeleteBlogsOnAuthorDeleted who will remove the blogs of the author)
In my opinion, your services shouldn't make internal HTTP requests when you can use your own services, in this way, if the logic changes, you'll only need to modify the service

ServiceStack.SSE: How do I get an instance o IServerEvents?

I have the SSE plugin running in ServiceStack, and it works to access for example /event-stream etc.
Now, let's assume there are subscribers, but otherwise no action from outside. Suddenly, the server decides "I need to push this information to channel X". How do I do that? I seem to need in instance of IServerEvents, but I don't know where I get that instance.
I see it's injected into different Service implementations, but in this case, there is no service called, so I need to get this IServerEvents elsewhere. Let's assume an event is trigged, that fires a method inside the AppSelfHostBase implementation, so OnObjectChange(...) is triggered.
How do I then push some data out to a channel/subscriber in the OnObjectChanged method? Where do I get the IServerEvents?
It seems that this code works almost anywhere:
IServerEvents test = TryResolve<IServerEvents>();
The IServerEvents instance will be returned and seems to function.

Using HttpContext.Current in WebApi is dangerous because of async

My question is a bit related to this: WebApi equivalent for HttpContext.Items with Dependency Injection.
We want to inject a class using HttpContext.Current in WebApi area using Ninject.
My concern is, this could be very dangerous, as in WebApi (everything?) is async.
Please correct me if I am wrong in these points, this is what I investigated so far:
HttpContext.Current gets the current context by Thread (I looked into the implementation directly).
Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread.
WebApi uses IHttpController with method Task<HttpResponseMessage> ExecuteAsync => every request is async => you cannot use HttpContext.Current inside of action method. It could even happen, more Request are executed on the same thread by coicidence.
For creating controllers with injected stuff into constructors IHttpControllerActivator is used with sync method IHttpController Create. This is, where ninject creates Controller with all its dependencies.
If I am correct in all of these 4 points, using of HttpContext.Current inside of an action method or any layer below is very dangerous and can have unexpected results. I saw on StackOverflow lot of accepted answers suggesting exactly this. In my opinion this can work for a while, but will fail under load.
But when using DI to create a Controller and its dependencies, it is Ok, because this runs on one separated thread. I could get a value from the HttpContext in the constructor and it would be safe?. I wonder if each Controller is created on single thread for every request, as this could cause problem under heavy loads, where all threads from IIS could be consumed.
Just to explain why I want to inject HttpContext stuff:
one solution would be to get the request in controller action method and pass the needed value all the layers as param until its used somewhere deep in the code.
our wanted solution: all the layers between are not affected by this, and we can use the injected request somewhere deep in code (e.g. in some ConfigurationProvider which is dependent on URL)
Please give me your opinion if I am totally wrong or my suggestions are correct, as this theme seems to be very complicated.
HttpContext.Current gets the current context by Thread (I looked into the implementation directly).
It would be more correct to say that HttpContext is applied to a thread; or a thread "enters" the HttpContext.
Using HttpContext.Current inside of async Task is not possible, because it can run on another Thread.
Not at all; the default behavior of async/await will resume on an arbitrary thread, but that thread will enter the request context before resuming your async method.
The key to this is the SynchronizationContext. I have an MSDN article on the subject if you're not familiar with it. A SynchronizationContext defines a "context" for a platform, with the common ones being UI contexts (WPF, WinPhone, WinForms, etc), the thread pool context, and the ASP.NET request context.
The ASP.NET request context manages HttpContext.Current as well as a few other things such as culture and security. The UI contexts are all tightly associated with a single thread (the UI thread), but the ASP.NET request context is not tied to a specific thread. It will, however, only allow one thread in the request context at a time.
The other part of the solution is how async and await work. I have an async intro on my blog that describes their behavior. In summary, await by default will capture the current context (which is SynchronizationContext.Current unless it is null), and use that context to resume the async method. So, await is automatically capturing the ASP.NET SynchronizationContext and will resume the async method within that request context (thus preserving culture, security, and HttpContext.Current).
If you await ConfigureAwait(false), then you're explicitly telling await to not capture the context.
Note that ASP.NET did have to change its SynchronizationContext to work cleanly with async/await. You have to ensure that the application is compiled against .NET 4.5 and also explicitly targets 4.5 in its web.config; this is the default for new ASP.NET 4.5 projects but must be explicitly set if you upgraded an existing project from ASP.NET 4.0 or earlier.
You can ensure these settings are correct by executing your application against .NET 4.5 and observing SynchronizationContext.Current. If it is AspNetSynchronizationContext, then you're good; if it's LegacyAspNetSynchronizationContext, then the settings are wrong.
As long as the settings are correct (and you are using the ASP.NET 4.5 AspNetSynchronizationContext), then you can safely use HttpContext.Current after an await without worrying about it.
I am using a web api, which is using async/await methodology.
also using
1) HttpContext.Current.Server.MapPath
2) System.Web.HttpContext.Current.Request.ServerVariables
This was working fine for a good amount of time which broke suddenly for no code change.
Spending a lot of time by reverting back to previous old versions, found the missing key causes the issue.
< httpRuntime targetFramework="4.5.2" /> under system.web
I am not an expert technically. But I suggest to add the key to your web config and give it a GO.
I found very good article describing exactly this problem: http://byterot.blogspot.cz/2012/04/aspnet-web-api-series-part-3-async-deep.html?m=1
author investigated deeply, how the ExecuteAsync method is called in the WebApi framework and came to this conclusion:
ASP.NET Web API actions (and all the pipeline methods) will be called asynchronously only if you return a Task or Task<T>. This might sound obvious but none of the pipeline methods with Async suffix will run in their own threads. Using blanket Async could be a misnomer. [UPDATE: ASP.NET team indeed have confirmed that the Async is used to denote methods that return Task and can run asynchronously but do not have to]
What I understood from the article is, that the Action methods are called synchronously, but it is the caller decision.
I created a small test app for this purpose, something like this:
public class ValuesController : ApiController
{
public object Get(string clientId, string specialValue)
{
HttpRequest staticContext = HttpContext.Current.Request;
string staticUrl = staticContext.Url.ToString();
HttpRequestMessage dynamicContext = Request;
string dynamicUrl = dynamicContext.RequestUri.ToString();
return new {one = staticUrl, two = dynamicUrl};
}
}
and one Async version returning async Task<object>
I tried to do a little DOS attack on it with jquery and could not determine any issue until I used await Task.Delay(1).ConfigureAwait(false);, which is obvious it would fail.
What I took from the article is, that the problem is very complicated and Thread switch can happen when using async action method, so it is definetly NOT a good idea to use HttpContext.Current anywhere in the code called from the action methods. But as the controller is created synchronously, using HttpContext.Current in the constructor and as well in dependency injection is OK.
When somebody has another explanation to this problem please correct me as this problem is very complicated an I am still not 100% convinced.
diclaimer:
I ignore for now the problem of self-hosted Web-Api withoud IIS, where HttpContext.Current would not work probably anyway. We now rely on IIS.

Uploading photos using Grails Services

I would like to ask, What would be the most suitable scope for my upload photo service in Grails ? I created this PhotoService in my Grails 2.3.4 web app, all it does is to get the request.getFile("myfile") and perform the necessary steps to save it on the hard drive whenever a user wants to upload an image. To illustrate what it looks like, I give a skeleton of these classes.
PhotoPageController {
def photoService
def upload(){
...
photoService.upload(request.getFile("myfile"))
...
}
}
PhotoService{
static scope="request"
def upload(def myFile){
...
// I do a bunch of task to save the photo
...
}
}
The code above isn't the exact code, I just wanted to show the flow. But my question is:
Question:
I couldn't find the exact definition of these different grails scopes, they have a one liner explanation but I couldn't figure out if request scope means for every request to the controller one bean is injected, or each time a request comes to upload action of the controller ?
Thoughts:
Basically since many users might upload at the same time, It's not a good idea to use singleton scope, so my options would be prototype or request I guess. So which one of them works well and also which one only gets created when the PhotoService is accessed only ?
I'm trying to minimize the number of services being injected into the application context and stays as long as the web app is alive, basically I want the service instance to die or get garbage collect at some point during the web app life time rather than hanging around in the memory while there is no use for it. I was thinking about making it session scope so when the user's session is terminated the service is cleaned up too, but in some cases a user might not want to upload any photo and the service gets created for no reason.
P.S: If I move the "def photoService" within the upload(), does that make it only get injected when the request to upload is invoked ? I assume that might throw exception because there would be a delay until Spring injects the service and then the ref to def photoService would be n
I figured out that Singleton scope would be fine since I'm not maintaining the state for each request/user. Only if the service is supposed to maintain state, then we can go ahead and use prototype or other suitable scopes. Using prototype is safer if you think the singleton might cause unexpected behavior but that is left to testing.

What is lost from the stack when a service handles async messages in ServiceStack?

I'm using the messaging feature of ServiceStack for back end transactions I expect to involve database locks where consistency is very important.
I've registered handlers as explained in the documentation:
mqHost.RegisterHandler<Hello>(m => {
return this.ServiceController.ExecuteMessage(m);
});
I've noticed the Filters don't get called. Presumably, they're really "Http" filters similar to MVC. So it makes sense they're ignored.
How does Authorization work with message handlers, is it ignored too?
And as I want to keep my async services internal, and always async, is there any benefit in making them inherit from ServiceBase at all?
As I'm thinking of creating another envelop layer between IMessage and Body for some Identity data that can be passed from my public services out of AuthSession and to the Async service.

Resources