With some downtime over the holidays I decided to tackle something I’d been dreaming about for a while — using Phoenix’s relatively new Presence support to give our customers a list of their online teammates. After getting up to speed with this new feature, implementing it turned out to be pretty straightforward!
Here’s how I knocked it out…
Adding Phoenix Presence Support
We’ve been using Phoenix Channels in production for roughly a year now with great success. We use them to sync state changes and send notifications to our users in realtime — new messages arrive, business settings are updated, new users get added, etc. If you’re not already using Phoenix Channels then you’ll have a lot more work to do before you can start using Presence. Lets assume you are.
First lets add Presence support to our existing Phoenix application. This was way easier than I thought it would be and is fully backwards compatible for the client-side as well. Our front-end clients just wind up ignoring the newly triggered events until we add in handling for them.
Run the generator which will create your application’s Presence module for you.
~jeangrey(master)$ mix phoenix.gen.presence
* creating web/channels/presence.exAdd your new module to your supervision tree,in lib/jeangrey.ex:children = [...supervisor(Jeangrey.Presence, []),]You're all set! See the Phoenix.Presence docs for more details:http://hexdocs.pm/phoenix/Phoenix.Presence.html
Follow the steps in the output to add the module to your supervisor tree.
Press enter or click to view image in full size
I next made a simple change to our socket to ensure we assign the connecting user’s ID to the socket for later use. I’ve intentionally omitted a bunch of irrelevant code here — if you’re already assigning whatever makes sense as a presence key in your app you can skip this step.
Next up is the actual presence implementation. I decided to use one of our existing business-level channels, private-business-updates:* — it’s scoped to a single business and all users automatically connect to it regardless of where they are in the application.
Following along more or less from the Presence docs/tutorial, we have to update our Channel module as follows…
So what’s going on here?
Well we added a new function, handle_info/2, which we trigger when a user successfully joins our channel. We use Phoenix.Presence.track/3 to register the channel’s process as a presence for the user_id pulled from our socket — this is why made that socket connect change above.
We also make sure we broadcast a presence_state event for the newly joined user. Phoenix takes care of broadcasting the presence_diff event in real time as client connection status changes.
It feels a bit odd to me that we have to manually broadcast after join (and can change the name of the
presence_stateevent) but have no control over thepresence_diffbroadcasts. ShouldPresence.track/3automatically push our presence_state for us instead? Perhaps this is something that will change as the system evolves over time…
That’s it for the Phoenix side of things! Honestly I was skeptical if it was even working or not — it seemed too simple. I tried refreshing our front-end application. Nothing broken there so that’s good.
I wanted to use Phoenix.Presence.list/2 to get some insight into our presence implementation but I was never able to actually get back any data from it for some reason. I fired up a console and…
jeangrey(master)$ iex -S mix
Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace]Interactive Elixir (1.3.1) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> Phoenix.Presence.list(Jeangrey.Presence, "private-business-updates:d44b00dc-f47f-4dbd-8374-824a082671f6")
%{}
iex(2)> Jeangrey.Presence.list("private-business-updates:d44b00dc-f47f-4dbd-8374-824a082671f6")
%{}
iex(3)> Jeangrey.Presence.list("private-business-updates:*")
%{}
iex(4)> Jeangrey.Presence.list(nil)
%{}
¯\_(ツ)_/¯
I give up… obviously I’m doing something wrong here…
Get Brian McManus’s stories in your inbox
Join Medium for free to get updates from this writer.
I checked the front-end application’s websocket connection and saw the new presence_state and presence_diff events coming in so despite my failure in the console everything seemed to be working.
Because this is a fully backwards-compatible, independent change I was able to deploy to production and then move on to the front-end.
Adding Presence to our Ember.js App
That’s cool that we’re tracking and sending Presence data now on our Phoenix channel but now we have to actually do something with it. We want to showcase our shiny new Presence tracking in the following ways:
- Provide a globally accessible list of online users. This will give our customers greater insight into who is available to help out (e.g. when @mentioning someone). It could also be expanded to allow simple in-app user-to-user messaging.
- Indicate users’ online status throughout the application wherever we are displaying their avatar.
With the new presence events being sent by Phoenix, it was pretty easy to add this to our Ember application.
Before I jump in, since this is a commercial application, I can’t show you everything. We have a custom Ember service wrapper around Phoenix’s javascript library to support our application’s needs. It’s not open source (yet) but it handles most of the channel/event heavy lifting for us. It was not modified in any way for this feature.
Here’s the strategy I decided on:
- We’ll add Phoenix presence support alongside our existing
private-business-updates:*channel event handling. Presence amounts to two new events to handle. - We will add a new transient
onlineboolean property to our User model. Making it transient ensures that we do not send this value to our server since it is only used in the client. Our presence code will update this value on the user models in our localstore. - We can then use this new
onlineproperty wherever we need to throughout our application. - Profit…
All of the Phoenix Presence-related changes wound up nicely encapsulated in the controller that was already handling this channel’s events. Here are the modifications…
This looks like a lot but it’s really not that bad.
- We first import the Phoenix Presence module so we can make use of the
Presence.syncStateandPresence.syncDiffhelper functions. - We add our new callbacks for the presence events to what we’re already listening for in our
init()method. - Phoenix expects you to track presence state in the client so we add a new
presencesproperty to our controller and use thesyncStateandsyncDiffto keep it updated. These helpers return the presences after syncing your current state and will only include online users. This posed a slight problem when users go offline since they are not in the updatedpresencesobject. To avoid tracking additional state or looping through users we leverage the optionalonJoinandonLeavecallbacks. These receive the presence key (for us that’s our user’s ID), the current presence state for that key (after the event is processed), and the specific presence data that triggered the event. - We use the
onJoincallback to set a user’sonlinestatus to true. We do this when there is nocurrentpresence info indicating this is the first time we’ve seen the user join. Despite its name this fires for all currently connected users insyncState, not just those that join. - We use the
onLeavecallback to set a user’sonlinestatus to false. Again we check thecurrentpresence info but this time we check the length of themetasproperty on our presence object. This will be empty when the user has disconnected from all devices. (We did not need it butleftPreswould contain the metadata for the user that triggered theonLeavecallback which is no longer incurrent.metas)
The Result
With those changes in place, whenever we are dealing with users in our application we get access to their online status which gets updated in real-time by Phoenix’s presence support.
What can we do with that info?
List Online Users
Press enter or click to view image in full size
Online-status Avatar Indicators
Press enter or click to view image in full size
And just like that, my dream has been realized. Thanks to the amazing features provided by Phoenix and Ember, what would normally be a complicated and error prone implementation was made almost trivial. If you haven’t checked these frameworks out yet you owe it to yourself to do so.
Hopefully you learned something from this. Let me know if you have any questions — I’ll be around to answer them, RSVP.Promise.