[ActionCable] Possibility from server side to terminate subscription by specifying WebSocket close code and reason

WebSocket.close() method accept two optional parameters:

  1. code - A numeric value indicating the status code explaining why the connection is being closed.
  2. reason - A human-readable string explaining why the connection is closing.

More info: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/close

Real live example where and how my proposed changes would work in Rails

For example by terminating subscription from server if User session expired

    ActionCable.server
               .remote_connections
               .where(current_user: warden_proxy.user)
               .disconnect(4001, "Unauthorized")

``

On JavaScript side possibility to receive WebSocket close code and reason. For example if WebSocket closed because User session expired then we redirect to root path

  disconnected: (data) ->
    # Called when the subscription has been terminated by the server

    # If Unauthorized (Session Terminated or Expired)
    if data.statusCode == 4001
      window.location = "/"  

``

In Rails ActionCable there is needed only couple changes to support WebSocket close code and reason.

Please check my implementation in my Fork: https://github.com/aboltart/rails/commit/be168f16118f5848d0d3a9165afeafb6717a71f8

See also https://github.com/rails/rails/pull/29390 about using proper close codes for WebSockets.

Yes, I saw your mentioned Merge Request.

In my example I am using 4000+ WebSocket close code what according CloseEvent - Web APIs | MDN description should be used for application specific purpose.

In my implementation I am not performing status code checking, because at then end status code validation will be performed https://github.com/rails/rails/blob/5-2-1/actioncable/lib/action_cable/connection/client_socket.rb#L90