From 72d94c6eb0ad216a3cf644997fa0367488d85445 Mon Sep 17 00:00:00 2001 From: Rick Carlino Date: Thu, 26 Oct 2017 09:25:13 -0500 Subject: [PATCH] Cache bunny connection --- app/models/application_record.rb | 18 ++++++++++++------ app/models/transport.rb | 15 +++++++++------ 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/app/models/application_record.rb b/app/models/application_record.rb index cdb3992c7..529c3d9c2 100644 --- a/app/models/application_record.rb +++ b/app/models/application_record.rb @@ -1,6 +1,7 @@ class ApplicationRecord < ActiveRecord::Base self.abstract_class = true - after_save :maybe_broadcast, on: [:create, :update, :destroy] + after_save :maybe_broadcast, on: [:create, :update] + after_destroy :maybe_broadcast DONT_BROADCAST = [ "current_sign_in_at", "last_sign_in_at", @@ -8,17 +9,22 @@ class ApplicationRecord < ActiveRecord::Base "updated_at", "created_at" ] - def broadcast? - Device.current && - !self.saved_changes.except(*self.class::DONT_BROADCAST).empty? + # Determine if the changes to the model are worth broadcasting or not. + # Reduces network noise. + def notable_changes? + !self.saved_changes.except(*self.class::DONT_BROADCAST).empty? end - def maybe_broadcast(*args_) + def broadcast? + Device.current && (destroyed? || notable_changes?) + end + + def maybe_broadcast self.broadcast! if broadcast? end def broadcast_payload - { body: self.as_json }.to_json + { body: destroyed? ? "null" : self.as_json }.to_json end def chan_name diff --git a/app/models/transport.rb b/app/models/transport.rb index 2e1ff033e..8c72356b4 100644 --- a/app/models/transport.rb +++ b/app/models/transport.rb @@ -1,12 +1,15 @@ # A wrapper around AMQP to stay DRY. Will make life easier if we ever need to # change protocols module Transport + def self.topic + @topic ||= Bunny + .new(read_timeout: 10, heartbeat: 10) + .start + .create_channel + .topic("amq.topic", auto_delete: true) + end + def self.send(message, id, channel) - Bunny - .new - .start - .create_channel - .topic("amq.topic", auto_delete: true) - .publish(message, routing_key: "bot.device_#{id}.#{channel}") + topic.publish(message, routing_key: "bot.device_#{id}.#{channel}") end end