aboutsummaryrefslogtreecommitdiffstats
path: root/lib/action_cable/connection/subscriptions.rb
blob: 24ab1bdfbfd48214fb75334d9a163238698ecb1f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
module ActionCable
  module Connection
    class Subscriptions
      def initialize(connection)
        @connection = connection
        @subscriptions = {}
      end

      def execute_command(data)
        case data['command']
        when 'subscribe'   then add data
        when 'unsubscribe' then remove data
        when 'message'     then perform_action data
        else
          logger.error "Received unrecognized command in #{data.inspect}"
        end
      rescue Exception => e
        logger.error "Could not execute command from #{data.inspect}) [#{e.class} - #{e.message}]: #{e.backtrace.first(5).join(" | ")}"
      end

      def add(data)
        id_key = data['identifier']
        id_options = ActiveSupport::JSON.decode(id_key).with_indifferent_access

        subscription_klass = connection.server.registered_channels.detect do |channel_klass|
          channel_klass == id_options[:channel].safe_constantize
        end

        if subscription_klass
          subscriptions[id_key] ||= subscription_klass.new(connection, id_key, id_options)
        else
          logger.error "Subscription class not found (#{data.inspect})"
        end
      end

      def remove(data)
        logger.info "Unsubscribing from channel: #{data['identifier']}"
        subscriptions[data['identifier']].perform_disconnection
        subscriptions.delete(data['identifier'])
      end

      def perform_action(data)
        find(data).perform_action ActiveSupport::JSON.decode(data['data'])
      end


      def identifiers
        subscriptions.keys
      end

      def cleanup
        subscriptions.each { |id, channel| channel.perform_disconnection }
      end


      private
        attr_reader :connection, :subscriptions
        delegate :logger, to: :connection

        def find(data)
          if subscription = subscriptions[data['identifier']]
            subscription
          else
            raise "Unable to find subscription with identifier: #{data['identifier']}"
          end
        end
    end
  end
end