Class: MessageBus::Rack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/message_bus/rack/middleware.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, config = {}) ⇒ Middleware

Returns a new instance of Middleware.



35
36
37
38
39
40
# File 'lib/message_bus/rack/middleware.rb', line 35

def initialize(app, config = {})
  @app = app
  @bus = config[:message_bus] || MessageBus
  @connection_manager = MessageBus::ConnectionManager.new(@bus)
  self.start_listener
end

Class Method Details

.backlog_to_json(backlog) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
# File 'lib/message_bus/rack/middleware.rb', line 49

def self.backlog_to_json(backlog)
  m = backlog.map do |msg|
    {
      global_id: msg.global_id,
      message_id: msg.message_id,
      channel: msg.channel,
      data: msg.data
    }
  end.to_a
  JSON.dump(m)
end

Instance Method Details

#add_client_with_timeout(client) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/message_bus/rack/middleware.rb', line 204

def add_client_with_timeout(client)
  @connection_manager.add_client(client)

  client.cleanup_timer = MessageBus.timer.queue(@bus.long_polling_interval.to_f / 1000) {
    begin
      client.cleanup_timer = nil
      client.ensure_closed!
      @connection_manager.remove_client(client)
    rescue
      @bus.logger.warn "Failed to clean up client properly: #{$!} #{$!.backtrace}"
    end
  }
end

#call(env) ⇒ Object



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
# File 'lib/message_bus/rack/middleware.rb', line 61

def call(env)

  return @app.call(env) unless env['PATH_INFO'] =~ /^\/message-bus\//

  # special debug/test route
  if @bus.allow_broadcast? && env['PATH_INFO'] == '/message-bus/broadcast'
    parsed = Rack::Request.new(env)
    @bus.publish parsed["channel"], parsed["data"]
    return [200, { "Content-Type" => "text/html" }, ["sent"]]
  end

  if env['PATH_INFO'].start_with? '/message-bus/_diagnostics'
    diags = MessageBus::Rack::Diagnostics.new(@app, message_bus: @bus)
    return diags.call(env)
  end

  client_id = env['PATH_INFO'].split("/")[2]
  return [404, {}, ["not found"]] unless client_id

  user_id = @bus.user_id_lookup.call(env) if @bus.user_id_lookup
  group_ids = @bus.group_ids_lookup.call(env) if @bus.group_ids_lookup
  site_id = @bus.site_id_lookup.call(env) if @bus.site_id_lookup

  # close db connection as early as possible
  close_db_connection!

  client = MessageBus::Client.new(message_bus: @bus, client_id: client_id,
                                  user_id: user_id, site_id: site_id, group_ids: group_ids)

  if channels = env['message_bus.channels']
    if seq = env['message_bus.seq']
      client.seq = seq.to_i
    end
    channels.each do |k, v|
      client.subscribe(k, v)
    end
  else
    request = Rack::Request.new(env)
    is_json = request.content_type && request.content_type.include?('application/json')
    data = is_json ? JSON.parse(request.body.read) : request.POST
    data.each do |k, v|
      if k == "__seq"
        client.seq = v.to_i
      else
        client.subscribe(k, v)
      end
    end
  end

  headers = {}
  headers["Cache-Control"] = "must-revalidate, private, max-age=0"
  headers["Content-Type"] = "application/json; charset=utf-8"
  headers["Pragma"] = "no-cache"
  headers["Expires"] = "0"

  if @bus.extra_response_headers_lookup
    @bus.extra_response_headers_lookup.call(env).each do |k, v|
      headers[k] = v
    end
  end

  if env["REQUEST_METHOD"] == "OPTIONS"
    return [200, headers, ["OK"]]
  end

  long_polling = @bus.long_polling_enabled? &&
                 env['QUERY_STRING'] !~ /dlp=t/ &&
                 @connection_manager.client_count < @bus.max_active_clients

  allow_chunked = env['HTTP_VERSION'] == 'HTTP/1.1'
  allow_chunked &&= !env['HTTP_DONT_CHUNK']
  allow_chunked &&= @bus.chunked_encoding_enabled?

  client.use_chunked = allow_chunked

  backlog = client.backlog

  if backlog.length > 0 && !allow_chunked
    client.cancel
    @bus.logger.debug "Delivering backlog #{backlog} to client #{client_id} for user #{user_id}"
    [200, headers, [self.class.backlog_to_json(backlog)] ]
  elsif long_polling && env['rack.hijack'] && @bus.rack_hijack_enabled?
    io = env['rack.hijack'].call
    # TODO disable client till deliver backlog is called
    client.io = io
    client.headers = headers
    client.synchronize do
      client.deliver_backlog(backlog)
      add_client_with_timeout(client)
      client.ensure_first_chunk_sent
    end
    [418, {}, ["I'm a teapot, undefined in spec"]]
  elsif long_polling && env['async.callback']
    response = nil
    # load extension if needed
    begin
      response = Thin::AsyncResponse.new(env)
    rescue NameError
      require 'message_bus/rack/thin_ext'
      response = Thin::AsyncResponse.new(env)
    end

    headers.each do |k, v|
      response.headers[k] = v
    end

    if allow_chunked
      response.headers["X-Content-Type-Options"] = "nosniff"
      response.headers["Transfer-Encoding"] = "chunked"
      response.headers["Content-Type"] = "text/plain; charset=utf-8"
    end

    response.status = 200
    client.async_response = response
    client.synchronize do
      add_client_with_timeout(client)
      client.deliver_backlog(backlog)
      client.ensure_first_chunk_sent
    end

    throw :async
  else
    [200, headers, [self.class.backlog_to_json(backlog)]]
  end

rescue => e
  if @bus.on_middleware_error && result = @bus.on_middleware_error.call(env, e)
    result
  else
    raise
  end
end

#close_db_connection!Object



194
195
196
197
198
199
200
201
202
# File 'lib/message_bus/rack/middleware.rb', line 194

def close_db_connection!
  # IMPORTANT
  # ConnectionManagement in Rails puts a BodyProxy around stuff
  #  this means connections are not returned until rack.async is
  #  closed
  if defined? ActiveRecord::Base.clear_active_connections!
    ActiveRecord::Base.clear_active_connections!
  end
end

#start_listenerObject



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
# File 'lib/message_bus/rack/middleware.rb', line 9

def start_listener
  unless @started_listener

    thin = defined?(Thin::Server) && ObjectSpace.each_object(Thin::Server).to_a.first
    thin_running = thin && thin.running?

    @subscription = @bus.subscribe do |msg|
      run = proc do
        begin
          @connection_manager.notify_clients(msg) if @connection_manager
        rescue
          @bus.logger.warn "Failed to notify clients: #{$!} #{$!.backtrace}"
        end
      end

      if thin_running
        EM.next_tick(&run)
      else
        MessageBus.timer.queue(&run)
      end

      @started_listener = true
    end
  end
end

#stop_listenerObject



42
43
44
45
46
47
# File 'lib/message_bus/rack/middleware.rb', line 42

def stop_listener
  if @subscription
    @bus.unsubscribe(&@subscription)
    @started_listener = false
  end
end