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

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.

Related

Node.js express app architecture with testing

Creating new project with auto-testing feature.
It uses basic express.
The question is how to orginize the code in order to be able to test it properly. (with mocha)
Almost every controller needs to have access to the database in order to fetch some data to proceed. But while testing - reaching the actual database is unwanted.
There are two ways as I see:
Stubbing a function, which intends to read/write from/to database.
Building two separate controller builders, one of each will be used to reach it from the endpoints, another one from tests.
just like that:
let myController = new TargetController(AuthService, DatabaseService...);
myController.targetMethod()
let myTestController = new TargetController(FakeAuthService, FakeDatabaseService...);
myTestController.targetMethod() // This method will use fake services which doesnt have any remote connection functionality
Every property passed will be set to a private variable inside the constructor of the controller. And by aiming to this private variable we could not care about what type of call it is. Test or Production one.
Is that a good approach of should it be remade?
Alright, It's considered to be a good practice as it is actually a dependency injection pattern

NodeJS Service Layer asynchronous communication

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.

Getting ExecutionContext in other libraries/projects in Azure Function App

The execution context that is injected to a function (https://github.com/Azure/azure-functions-host/wiki/Retrieving-information-about-the-currently-running-function), is it possible to get it in some other helper libraries.
I want to get the InvocationId of the current function in some other libraries. For e.g. let's say I have written a logger and I need to add the Invocation ID for every log. One trivial way to achieve this would be to pass the Invocation ID from the function to all the helpers, but it may not be possible especially if one is working with legacy code.
In App services we could solve this problem by getting access to the HttpContext via the IHttpContextAccessor.
Is there any alternative to this in Azure function?

Is the default behaviour for NSManagedObjectContext save() method a blocking method?

To be very specific: If I get the managed object context from the app delegate and do not set any parameters on it, what happens when running inserts, updates followed by save()?
Does the app block on save() until done?
Yes, the save method blocks. It's not even a default-- that's how it is, always. Does't matter if the context came from the app delegate or somewhere else, save is a synchronous method.
This what it came down to:
Normally, when I create an object, I only set the main key (properties that don't change through the lifecycle of the object) on creation. I then use an update method to complete the creation. In this particular case, I changed one property on the server from 'creational' property to 'updateable' property, but I missed it in the app. So the app was deleting the objects only to have the server create them again a bit later...

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.

Resources