Sha256: 0b6af195c8a6178156d7322057f4bb55ed713ba20032832a92a4947afd85f37c

Contents?: true

Size: 1.56 KB

Versions: 5

Compression:

Stored size: 1.56 KB

Contents

# encoding: UTF-8

require 'thread'
require 'prometheus/client/label_set_validator'

module Prometheus
  module Client
    # Metric
    class Metric
      attr_reader :name, :docstring, :base_labels

      def initialize(name, docstring, base_labels = {})
        @mutex = Mutex.new
        @validator = LabelSetValidator.new
        @values = Hash.new { |hash, key| hash[key] = default }

        validate_name(name)
        validate_docstring(docstring)
        @validator.valid?(base_labels)

        @name, @docstring = name, docstring
        @base_labels = base_labels
      end

      # Returns the metric type
      def type
        fail NotImplementedError
      end

      # Returns the value for the given label set
      def get(labels = {})
        @validator.valid?(labels)

        @values[labels]
      end

      # Returns all label sets with their values
      def values
        synchronize do
          @values.each_with_object({}) do |(labels, value), memo|
            memo[labels] = value
          end
        end
      end

      private

      def default
        nil
      end

      def validate_name(name)
        return true if name.is_a?(Symbol)

        fail ArgumentError, 'given name must be a symbol'
      end

      def validate_docstring(docstring)
        return true if docstring.respond_to?(:empty?) && !docstring.empty?

        fail ArgumentError, 'docstring must be given'
      end

      def label_set_for(labels)
        @validator.validate(labels)
      end

      def synchronize(&block)
        @mutex.synchronize(&block)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
prometheus-client-0.4.1 lib/prometheus/client/metric.rb
prometheus-client-0.4.0 lib/prometheus/client/metric.rb
prometheus-client-0.3.1 lib/prometheus/client/metric.rb
prometheus-client-0.3.0 lib/prometheus/client/metric.rb
prometheus-client-0.3.0.pre.rc.1 lib/prometheus/client/metric.rb