I was thinking that it would be cool to notify clients in real time when something changes in the Repo. My question is: where should I put the notification code? The controller or the context?
If I put them inside the context I’m sure all Repo changes will be captured and will generate notifications (this is probably not a good idea, but let’s assume it is). But this couples the context to the web part of my application, which is undesirable, right?
If I put them inside the controller, I keep the separation between the web part and the context, but I can’t be sure I’ve captured all changes.
Should I have a
NotificationManager module that tests whether if the web application is running before sending a notification? Is this level of “uncoupling” enough?
I’m not sure I’ll ever want to do this in production, so this is mainly a theoretical question about design.
Sine I’m on mobile only brief…
If something generates an update message it should be the context or even closer to the repo. It will always emit a message then to a genserver, which then relays this message to any topic, beam process or message queue or whatever you want and has subscribed in any way. Perhaps even layered through a tree like structure of processes.
This way you’ll get also changed made by non web parts of your application. But you still won’t catch changes that were made directly in the db.
Just abstract thinking here (since I’m currently at work ), I would think this is a perfect use case for Pub-sub pattern. As we know, the data of your app is handled inside its own contexts outside of the web layer. How I imagine it is that you have a context that exposes a
subscribe_to_updates function. The client (in this case, your web layer or something) calls that function on start and provide a handler (callback?) specifying what to do when it receives an update notification.
Everytime there’s an update, the context will iterate to the registered subscribers and call their respective handlers. This way you can decouple the subscriber from your context.
Now, how to implement that in Elixir seems to be an interesting challenge ^^
I do not think that the “context” should know who is interested in updates. It should just know that there might be someone.
If the context itself were iterating all the possible receivers each time there is an update, it could take quite a long time and massively influence the speed of database access.
Therefore I opt for a single “relay” as described in my post, but aside of that our ideas are similar.
Indeed, yep, your solution would scale better than mine. Using dedicated message queues or process should be better in the long run…
Thanks, that’s what I thought too.
I can see some advantages in doing this and must investigate further. Thanks
I’m aware of that. That would require having the DB itself notifying my code. I’m planning on only interacting with the DB using ecto, so that’s something I’m not interested in.