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.



27
28
29
30
31
32
# File 'lib/message_bus/rack/middleware.rb', line 27

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



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/message_bus/rack/middleware.rb', line 41

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



167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/message_bus/rack/middleware.rb', line 167

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

  client.cleanup_timer = ::EM::Timer.new( @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



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

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'.freeze
      parsed = Rack::Request.new(env)
      @bus.publish parsed["channel".freeze], parsed["data".freeze]
      return [200,{"Content-Type".freeze => "text/html".freeze},["sent"]]
  end

  if env['PATH_INFO'].start_with? '/message-bus/_diagnostics'.freeze
    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)

  request = Rack::Request.new(env)
  request.POST.each do |k,v|
    client.subscribe(k, v)
  end

  backlog = client.backlog
  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

  ensure_reactor

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

  if backlog.length > 0
    [200, headers, [self.class.backlog_to_json(backlog)] ]
  elsif long_polling && env['rack.hijack'] && @bus.rack_hijack_enabled?
    io = env['rack.hijack'].call
    client.io = io
    client.headers = headers

    add_client_with_timeout(client)
    [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
    response.status = 200

    client.async_response = response

    add_client_with_timeout(client)

    throw :async
  else
    [200, headers, ["[]"]]
  end
end

#close_db_connection!Object



145
146
147
148
149
150
151
152
153
# File 'lib/message_bus/rack/middleware.rb', line 145

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

#ensure_reactorObject



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/message_bus/rack/middleware.rb', line 155

def ensure_reactor
  # ensure reactor is running
  if EM.reactor_pid != Process.pid
    Thread.new { EM.run }
    i = 100
    while !EM.reactor_running? && i > 0
      sleep 0.001
      i -= 1
    end
  end
end

#start_listenerObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/message_bus/rack/middleware.rb', line 6

def start_listener
  unless @started_listener

    require 'eventmachine'
    require 'message_bus/em_ext'

    @subscription = @bus.subscribe do |msg|
      if EM.reactor_running?
        EM.next_tick do
          begin
            @connection_manager.notify_clients(msg) if @connection_manager
          rescue
            @bus.logger.warn "Failed to notify clients: #{$!} #{$!.backtrace}"
          end
        end
      end
    end
    @started_listener = true
  end
end

#stop_listenerObject



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

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