Optimise responses to CORS preflight requests

Optimise responses to CORS preflight requests

Respond prior to authentication and subscription setup. Our response doesn’t depend on these, so there’s no point executing them, especially since they may be heavy routines which perform I/O.

diff --git a/lib/message_bus/rack/middleware.rb b/lib/message_bus/rack/middleware.rb
index 809bfc1..216a8bb 100644
--- a/lib/message_bus/rack/middleware.rb
+++ b/lib/message_bus/rack/middleware.rb
@@ -81,6 +81,22 @@ class MessageBus::Rack::Middleware
     client_id = env['PATH_INFO'][@base_route_length..-1].split("/")[0]
     return [404, {}, ["not found"]] unless client_id
 
+    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
+
     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
@@ -111,22 +127,6 @@ class MessageBus::Rack::Middleware
       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

GitHub sha: 570e542b

This commit appears in #244 which was approved by SamSaffron. It was merged by SamSaffron.