ActionCable and WebSockets – Part 2(The Implementation)

THE RAILS WAY…

When you create a new rails 5 application, rails generates some files for you:

For any implementation of a websocket connection, we need both the client and the server parts of the code.

CLIENT SIDE

For the client side Rails providesÂ app/assets/javascripts/cable.js which loads action_cable js and all files in channels directory.

On page load, a consumer is created and exposed via App.cable.

If we would go a little bit into the client side code for action_cable, we would find that rails does all the heavy loading like instantiating subscriptions and connections…monitoring connections etc. pretty cool.. right ?

Here, identified_by is a connection identifier.
Therefore, we can use it to retrieve, and thereby disconnect, all open connections for a given user.

If you implement connect method, the same will be called while handling a websocket open request.

You can call reject_unauthorized_access if you don’t want the current_user to connect

The app/channels/application_cable/channel.rb contains your ApplicationCable::Channel where you put shared logic forÂ your channels.
It’sÂ similar to ApplicationController for controllers.

All that came right out of the box.

Let’s go ahead and implement a common use case… The Chat Application.

For a chat application, we would have these three basic requirements:

We should be able to subscribe to a channel,

Publish something on that channel

Receive the published message on the subscribed channel.

THE channel GENERATOR

Rails 5 provides a new channel generator which creates two new files.
One ruby file and one js file.

This generator is similar to the familiar controller generator. You specify the name of the channel (room) and one or more public methods which can be invoked as Remote Procedures ( we’ll come to it in a while )

Let’s see what we have in each of these files for this particular example..

CLIENT SIDE JS CODE

# app/assets/javascripts/channels/room.coffee
App.room = App.cable.subscriptions.create"RoomChannel",
connected: ->
# Called when the subscription is ready for use on the server
disconnected: ->
# Called when the subscription has been terminated by the server
received: (data) ->
# Called when there's incoming data on the websocket for this channel
speak: ->
@perform 'speak'

Rails created a subscription for the RoomChannel.

Please note that the name is exactly same as the name of the class that we have for the channel.

Then it provides empty implementations for three callbacks: connected, disconnected and received.

Then we have a speak method which basically invokes the perform method with the string speak as its argument. again, that name is important.

We’ll come to it later that why this naming is important. But the good thing is rails did all that for us and we don’t need to worry about it unless we override the defaults.

classMessageBroadcastJob< ApplicationJob
queue_as :defaultdefperform(message)# You may render JSON or HTML itself if you want to reuse your views.ActionCable.server.broadcast 'room_channel', message: render_message(message)
end
private
defrender_message(message)# RAILS5_THING: Controller can render partial without being in scope of the controller.ApplicationController.renderer
.render(partial:'messages/message', locals: { message: message })
endend

Notice how we invoke the broadcast on a given named pubsub queue ( the one we passed as an argument to stream_from) with the hash that we want to broadcast.

CLIENT SIDE CODE

Here’s a JS equivalent of the CoffeeScript that was used in the demo.

(function() {
// Subscribe to a channel (RoomChannel)// And specify event handlers for various events and any custom actions(speak).
App.room = App.cable.subscriptions.create("RoomChannel", {
received: function(data) {
// Do something when some data is published on the channel
$('#messages').append(data.message)
},
speak: function(message) {
// We link the client-side `speak` method to `RoomChannel#speak(data)`.// This is possible because the server-side channel instance will automatically// expose the public methods declared on the class (minus the callbacks),// so that these can be reached as remote procedure calls// via a subscription's `perform` method.returnthis.perform('speak', { message: message });
}
});
$(document).on('keypress', '[data-behavior="room_speaker"]', function(event) {
if (event.keyCode === 13) {
// Respond to some trigger based on which you want to// Invoke the speak method on the subscription created above.
App.room.speak(event.target.value);
event.target.value = ''
event.preventDefault();
}
});
}).call(this);

I think this snippet explains why the exact string ‘speak’ was important.

That’s becauseÂ the server side ruby instance has exposed this method and this can be invoked as a Remote procedural call over the WebSocket connection.

RUNNING THIS DEMO TO EXPLORE LOGS

Here’s the animation showing the working of the demo app.

WHEN A CLIENT CONNECTS

Initial handshake and upgrade of HTTP to WebSocket

The client subscribes to a channel

The server logs also show the initial HTTP upgrade along with the subscription to the channel.

WHEN A CLIENT MAKES AN RPC AND MESSAGE BROADCASTS.

The client invokes the channel’s speak method which in turn results in a broadcast along the channel as seen in the returned frame.

The server logs show the invocation of RoomChannel#speak followed by its persistence in db and broadcast along the channel.

SECURING AGAINST CROSS SITE WEBSOCKET HIJACKING

The websockets support cross domain requests…which means it is also vulnerable to the security threats which result due to this behavior.