Sha256: d43f2c251a7e36d758283a8618a32ab5fd37b9faab6f2ffab185ef45a4bee620

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

module Tobox
  module Plugins
    module PgNotify
      class Notifier
        def initialize(config)
          @config = config
          @running = false
          @notifier_mutex = Thread::Mutex.new
          @notifier_semaphore = Thread::ConditionVariable.new
        end

        def start
          return if @running

          config = @config

          @db = Sequel.connect(config.database.opts.merge(max_connections: 1))

          raise Error, "this plugin only works with postgresql" unless @db.database_type == :postgres

          @db.loggers = config.database.loggers
          Array(config.lifecycle_events[:database_connect]).each { |cb| cb.call(@db) }

          channel = config[:notifier_channel]

          @th = Thread.start do
            Thread.current.name = "outbox-notifier"

            @db.listen(channel, loop: true) do
              signal
            end
          end

          @running = true
        end

        def stop
          return unless @running

          @th.terminate

          @db.disconnect

          @running = false
        end

        def wait
          @notifier_mutex.synchronize do
            @notifier_semaphore.wait(@notifier_mutex)
          end
        end

        def signal
          @notifier_mutex.synchronize do
            @notifier_semaphore.signal
          end
        end
      end

      module WorkerMethods
        attr_writer :notifier

        def wait_for_work
          @notifier.wait
        end
      end

      class << self
        def configure(config)
          config.config[:notifier_channel] = :outbox_notifications

          notifier = Notifier.new(config)

          config.on_start_worker { |wk| wk.notifier = notifier }

          config.on_start(&notifier.method(:start))
          config.on_stop(&notifier.method(:stop))
        end
      end
    end
    register_plugin :pg_notify, PgNotify
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tobox-0.7.0 lib/tobox/plugins/pg_notify.rb