BigW Consortium Gitlab

collection.rb 1.01 KB
Newer Older
1 2
module Gitlab
  module Sherlock
3 4 5 6 7
    # A collection of transactions recorded by Sherlock.
    #
    # Method calls for this class are synchronized using a mutex to allow
    # sharing of a single Collection instance between threads (e.g. when using
    # Puma as a webserver).
8 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 34 35 36 37 38 39 40 41
    class Collection
      include Enumerable

      def initialize
        @transactions = []
        @mutex = Mutex.new
      end

      def add(transaction)
        synchronize { @transactions << transaction }
      end

      alias_method :<<, :add

      def each(&block)
        synchronize { @transactions.each(&block) }
      end

      def clear
        synchronize { @transactions.clear }
      end

      def empty?
        synchronize { @transactions.empty? }
      end

      def find_transaction(id)
        find { |trans| trans.id == id }
      end

      def newest_first
        sort { |a, b| b.finished_at <=> a.finished_at }
      end

42 43
      private

44 45 46 47 48 49
      def synchronize(&block)
        @mutex.synchronize(&block)
      end
    end
  end
end