summaryrefslogtreecommitdiff
path: root/lib/bundler/vendor/connection_pool/lib/connection_pool/monotonic_time.rb
blob: 5a9c4a27bb0802399febb74511664d72d339e3a6 (plain)
1
2
3
4
5
6
7
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# Global monotonic clock from Concurrent Ruby 1.0.
# Copyright (c) Jerry D'Antonio -- released under the MIT license.
# Slightly modified; used with permission.
# https://github.com/ruby-concurrency/concurrent-ruby

require 'thread'

class Bundler::ConnectionPool

  class_definition = Class.new do

    if defined?(Process::CLOCK_MONOTONIC)

      # @!visibility private
      def get_time
        Process.clock_gettime(Process::CLOCK_MONOTONIC)
      end

    elsif defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby'

      # @!visibility private
      def get_time
        java.lang.System.nanoTime() / 1_000_000_000.0
      end

    else

      # @!visibility private
      def initialize
        @mutex = Mutex.new
        @last_time = Time.now.to_f
      end

      # @!visibility private
      def get_time
        @mutex.synchronize do
          now = Time.now.to_f
          if @last_time < now
            @last_time = now
          else # clock has moved back in time
            @last_time += 0.000_001
          end
        end
      end
    end
  end

  ##
  # Clock that cannot be set and represents monotonic time since
  # some unspecified starting point.
  #
  # @!visibility private
  GLOBAL_MONOTONIC_CLOCK = class_definition.new
  private_constant :GLOBAL_MONOTONIC_CLOCK

  class << self
    ##
    # Returns the current time a tracked by the application monotonic clock.
    #
    # @return [Float] The current monotonic time when `since` not given else
    #   the elapsed monotonic time between `since` and the current time
    def monotonic_time
      GLOBAL_MONOTONIC_CLOCK.get_time
    end
  end
end