File: client.rb

package info (click to toggle)
ruby-faye 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 1,792 kB
  • sloc: javascript: 14,833; ruby: 5,068; makefile: 30
file content (346 lines) | stat: -rw-r--r-- 12,062 bytes parent folder | download
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
module Faye
  class Client

    include Deferrable
    include Publisher
    include Logging
    include Extensible

    UNCONNECTED  = 1
    CONNECTING   = 2
    CONNECTED    = 3
    DISCONNECTED = 4

    HANDSHAKE = 'handshake'
    RETRY     = 'retry'
    NONE      = 'none'

    CONNECTION_TIMEOUT = 60.0

    extend Forwardable
    def_delegators :@dispatcher, :add_websocket_extension, :disable, :set_header

    def initialize(endpoint = nil, options = {})
      ::WebSocket::Driver.validate_options(options, [:interval, :timeout, :endpoints, :proxy, :retry, :scheduler, :websocket_extensions, :tls])
      super()
      info('New client created for ?', endpoint)

      @channels   = Channel::Set.new
      @dispatcher = Dispatcher.new(self, endpoint || RackAdapter::DEFAULT_ENDPOINT, options)

      @message_id = 0
      @state      = UNCONNECTED

      @response_callbacks = {}

      @advice = {
        'reconnect' => RETRY,
        'interval'  => 1000.0 * (options[:interval] || Engine::INTERVAL),
        'timeout'   => 1000.0 * (options[:timeout]  || CONNECTION_TIMEOUT)
      }
      @dispatcher.timeout = @advice['timeout'] / 1000.0

      @dispatcher.bind(:message, &method(:receive_message))
    end

    # Request
    # MUST include:  * channel
    #                * version
    #                * supportedConnectionTypes
    # MAY include:   * minimumVersion
    #                * ext
    #                * id
    #
    # Success Response                             Failed Response
    # MUST include:  * channel                     MUST include:  * channel
    #                * version                                    * successful
    #                * supportedConnectionTypes                   * error
    #                * clientId                    MAY include:   * supportedConnectionTypes
    #                * successful                                 * advice
    # MAY include:   * minimumVersion                             * version
    #                * advice                                     * minimumVersion
    #                * ext                                        * ext
    #                * id                                         * id
    #                * authSuccessful
    def handshake(&block)
      return if @advice['reconnect'] == NONE
      return if @state != UNCONNECTED

      @state = CONNECTING

      info('Initiating handshake with ?', @dispatcher.endpoint.to_s)
      @dispatcher.select_transport(MANDATORY_CONNECTION_TYPES)

      send_message({
        'channel'                  => Channel::HANDSHAKE,
        'version'                  => BAYEUX_VERSION,
        'supportedConnectionTypes' => @dispatcher.connection_types

      }, {}) do |response|

        if response['successful']
          @state = CONNECTED
          @dispatcher.client_id = response['clientId']

          @dispatcher.select_transport(response['supportedConnectionTypes'])

          info('Handshake successful: ?', @dispatcher.client_id)

          subscribe(@channels.keys, true)
          block.call if block_given?

        else
          info('Handshake unsuccessful')
          EventMachine.add_timer(@dispatcher.retry) { handshake(&block) }
          @state = UNCONNECTED
        end
      end
    end

    # Request                              Response
    # MUST include:  * channel             MUST include:  * channel
    #                * clientId                           * successful
    #                * connectionType                     * clientId
    # MAY include:   * ext                 MAY include:   * error
    #                * id                                 * advice
    #                                                     * ext
    #                                                     * id
    #                                                     * timestamp
    def connect(&block)
      return if @advice['reconnect'] == NONE or
                @state == DISCONNECTED

      return handshake { connect(&block) } if @state == UNCONNECTED

      callback(&block)
      return unless @state == CONNECTED

      info('Calling deferred actions for ?', @dispatcher.client_id)
      set_deferred_status(:succeeded)
      set_deferred_status(:unknown)

      return unless @connect_request.nil?
      @connect_request = true

      info('Initiating connection for ?', @dispatcher.client_id)

      send_message({
        'channel'        => Channel::CONNECT,
        'clientId'       => @dispatcher.client_id,
        'connectionType' => @dispatcher.connection_type

      }, {}) do
        cycle_connection
      end
    end

    # Request                              Response
    # MUST include:  * channel             MUST include:  * channel
    #                * clientId                           * successful
    # MAY include:   * ext                                * clientId
    #                * id                  MAY include:   * error
    #                                                     * ext
    #                                                     * id
    def disconnect
      return unless @state == CONNECTED
      @state = DISCONNECTED

      info('Disconnecting ?', @dispatcher.client_id)
      promise = Publication.new

      send_message({
        'channel'  => Channel::DISCONNECT,
        'clientId' => @dispatcher.client_id

      }, {}) do |response|
        if response['successful']
          @dispatcher.close
          promise.set_deferred_status(:succeeded)
        else
          promise.set_deferred_status(:failed, Error.parse(response['error']))
        end
      end

      info('Clearing channel listeners for ?', @dispatcher.client_id)
      @channels = Channel::Set.new

      promise
    end

    # Request                              Response
    # MUST include:  * channel             MUST include:  * channel
    #                * clientId                           * successful
    #                * subscription                       * clientId
    # MAY include:   * ext                                * subscription
    #                * id                  MAY include:   * error
    #                                                     * advice
    #                                                     * ext
    #                                                     * id
    #                                                     * timestamp
    def subscribe(channel, force = false, &block)
      if Array === channel
        return channel.map { |c| subscribe(c, force, &block) }
      end

      subscription  = Subscription.new(self, channel, block)
      has_subscribe = @channels.has_subscription?(channel)

      if has_subscribe and not force
        @channels.subscribe([channel], subscription)
        subscription.set_deferred_status(:succeeded)
        return subscription
      end

      connect {
        info('Client ? attempting to subscribe to ?', @dispatcher.client_id, channel)
        @channels.subscribe([channel], subscription) unless force

        send_message({
          'channel'      => Channel::SUBSCRIBE,
          'clientId'     => @dispatcher.client_id,
          'subscription' => channel

        }, {}) do |response|
          unless response['successful']
            subscription.set_deferred_status(:failed, Error.parse(response['error']))
            next @channels.unsubscribe(channel, subscription)
          end

          channels = [response['subscription']].flatten
          info('Subscription acknowledged for ? to ?', @dispatcher.client_id, channels)
          subscription.set_deferred_status(:succeeded)
        end
      }
      subscription
    end

    # Request                              Response
    # MUST include:  * channel             MUST include:  * channel
    #                * clientId                           * successful
    #                * subscription                       * clientId
    # MAY include:   * ext                                * subscription
    #                * id                  MAY include:   * error
    #                                                     * advice
    #                                                     * ext
    #                                                     * id
    #                                                     * timestamp
    def unsubscribe(channel, subscription = nil, &block)
      subscription ||= block

      if Array === channel
        return channel.map { |c| unsubscribe(c, subscription) }
      end

      dead = @channels.unsubscribe(channel, subscription)
      return unless dead

      connect {
        info('Client ? attempting to unsubscribe from ?', @dispatcher.client_id, channel)

        send_message({
          'channel'      => Channel::UNSUBSCRIBE,
          'clientId'     => @dispatcher.client_id,
          'subscription' => channel

        }, {}) do |response|
          next unless response['successful']

          channels = [response['subscription']].flatten
          info('Unsubscription acknowledged for ? from ?', @dispatcher.client_id, channels)
        end
      }
    end

    # Request                              Response
    # MUST include:  * channel             MUST include:  * channel
    #                * data                               * successful
    # MAY include:   * clientId            MAY include:   * id
    #                * id                                 * error
    #                * ext                                * ext
    def publish(channel, data, options = {})
      ::WebSocket::Driver.validate_options(options, [:attempts, :deadline])

      publication = Publication.new
      connect {
        info('Client ? queueing published message to ?: ?', @dispatcher.client_id, channel, data)

        send_message({
          'channel'  => channel,
          'data'     => data,
          'clientId' => @dispatcher.client_id

        }, options) do |response|
          if response['successful']
            publication.set_deferred_status(:succeeded)
          else
            publication.set_deferred_status(:failed, Error.parse(response['error']))
          end
        end
      }
      publication
    end

  private

    def send_message(message, options, &callback)
      message['id'] = generate_message_id

      timeout = [nil, 0].include?(@advice['timeout']) ?
                1.2 * @dispatcher.retry :
                1.2 * @advice['timeout'] / 1000.0

      pipe_through_extensions(:outgoing, message, nil) do |message|
        next unless message
        @response_callbacks[message['id']] = callback if callback
        @dispatcher.send_message(message, timeout, options)
      end
    end

    def generate_message_id
      @message_id += 1
      @message_id = 0 if @message_id >= 2**32
      @message_id.to_s(36)
    end

    def receive_message(message)
      id = message['id']

      if message.has_key?('successful')
        callback = @response_callbacks.delete(id)
      end

      pipe_through_extensions(:incoming, message, nil) do |message|
        next unless message
        handle_advice(message['advice']) if message['advice']
        deliver_message(message)
        callback.call(message) if callback
      end
    end

    def handle_advice(advice)
      @advice.update(advice)
      @dispatcher.timeout = @advice['timeout'] / 1000.0

      if @advice['reconnect'] == HANDSHAKE and @state != DISCONNECTED
        @state = UNCONNECTED
        @dispatcher.client_id = nil
        cycle_connection
      end
    end

    def deliver_message(message)
      return unless message.has_key?('channel') and message.has_key?('data')
      info('Client ? calling listeners for ? with ?', @dispatcher.client_id, message['channel'], message['data'])
      @channels.distribute_message(message)
    end

    def cycle_connection
      if @connect_request
        @connect_request = nil
        info('Closed connection for ?', @dispatcher.client_id)
      end
      EventMachine.add_timer(@advice['interval'] / 1000.0) { connect }
    end

  end
end