streams.rb 4.7 KB
Newer Older
1 2
module ActionCable
  module Channel
3
    # Streams allow channels to route broadcastings to the subscriber. A broadcasting is, as discussed elsewhere, a pub/sub queue where any data
4
    # put into it is automatically sent to the clients that are connected at that time. It's purely an online queue, though. If you're not
5 6 7 8 9 10 11 12 13 14
    # streaming a broadcasting at the very moment it sends out an update, you'll not get that update when connecting later.
    #
    # Most commonly, the streamed broadcast is sent straight to the subscriber on the client-side. The channel just acts as a connector between
    # the two parties (the broadcaster and the channel subscriber). Here's an example of a channel that allows subscribers to get all new
    # comments on a given page:
    #
    #   class CommentsChannel < ApplicationCable::Channel
    #     def follow(data)
    #       stream_from "comments_for_#{data['recording_id']}"
    #     end
15
    #
16 17 18 19 20 21 22 23 24 25
    #     def unfollow
    #       stop_all_streams
    #     end
    #   end
    #
    # So the subscribers of this channel will get whatever data is put into the, let's say, `comments_for_45` broadcasting as soon as it's put there.
    # That looks like so from that side of things:
    #
    #   ActionCable.server.broadcast "comments_for_45", author: 'DHH', content: 'Rails is just swell'
    #
26
    # If you have a stream that is related to a model, then the broadcasting used can be generated from the model and channel.
27
    # The following example would subscribe to a broadcasting like `comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE`
28 29 30 31 32 33 34 35 36 37
    #
    #   class CommentsChannel < ApplicationCable::Channel
    #     def subscribed
    #       post = Post.find(params[:id])
    #       stream_for post
    #     end
    #   end
    #
    # You can then broadcast to this channel using:
    #
38
    #   CommentsChannel.broadcast_to(@post, @comment)
39
    #
40
    # If you don't just want to parlay the broadcast unfiltered to the subscriber, you can supply a callback that lets you alter what goes out.
41 42 43
    # Example below shows how you can use this to provide performance introspection in the process:
    #
    #   class ChatChannel < ApplicationCable::Channel
44 45
    #     def subscribed
    #       @room = Chat::Room[params[:room_number]]
46
    #
47 48
    #       stream_for @room, -> (encoded_message) do
    #         message = ActiveSupport::JSON.decode(encoded_message)
49
    #
50 51
    #         if message['originated_at'].present?
    #           elapsed_time = (Time.now.to_f - message['originated_at']).round(2)
52
    #
53 54 55
    #           ActiveSupport::Notifications.instrument :performance, measurement: 'Chat.message_delay', value: elapsed_time, action: :timing
    #           logger.info "Message took #{elapsed_time}s to arrive"
    #         end
56
    #
57 58 59 60
    #         transmit message
    #       end
    #     end
    #   end
61 62
    #
    # You can stop streaming from all broadcasts by calling #stop_all_streams.
63 64 65 66 67 68 69
    module Streams
      extend ActiveSupport::Concern

      included do
        on_unsubscribe :stop_all_streams
      end

70 71
      # Start streaming from the named <tt>broadcasting</tt> pubsub queue. Optionally, you can pass a <tt>callback</tt> that'll be used
      # instead of the default of just transmitting the updates straight to the subscriber.
72
      def stream_from(broadcasting, callback = nil)
73 74
        # Hold off the confirmation until pubsub#subscribe is successful
        defer_subscription_confirmation!
75

76
        callback ||= default_stream_callback(broadcasting)
77 78
        streams << [ broadcasting, callback ]

79
        Concurrent.global_io_executor.post do
80
          pubsub.subscribe(broadcasting, callback, lambda do
81 82
            transmit_subscription_confirmation
            logger.info "#{self.class.name} is streaming from #{broadcasting}"
83
          end)
84
        end
85 86
      end

87 88 89 90 91 92 93
      # Start streaming the pubsub queue for the <tt>model</tt> in this channel. Optionally, you can pass a
      # <tt>callback</tt> that'll be used instead of the default of just transmitting the updates straight
      # to the subscriber.
      def stream_for(model, callback = nil)
        stream_from(broadcasting_for([ channel_name, model ]), callback)
      end

94
      # Unsubscribes all streams associated with this channel from the pubsub queue.
95 96
      def stop_all_streams
        streams.each do |broadcasting, callback|
J
Jon Moss 已提交
97
          pubsub.unsubscribe broadcasting, callback
98
          logger.info "#{self.class.name} stopped streaming from #{broadcasting}"
99
        end.clear
100 101 102
      end

      private
J
Jon Moss 已提交
103
        delegate :pubsub, to: :connection
104 105 106 107 108 109 110 111 112 113 114 115 116

        def streams
          @_streams ||= []
        end

        def default_stream_callback(broadcasting)
          -> (message) do
            transmit ActiveSupport::JSON.decode(message), via: "streamed from #{broadcasting}"
          end
        end
    end
  end
end