Sha256: 99b6bec8e40ffc74a10af56c8c86dab6db5301897342d8bce50c8949d3ff79ad

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 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 = name
        @docstring = 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

3 entries across 3 versions & 2 rubygems

Version Path
prometheus-client-0.5.0 lib/prometheus/client/metric.rb
custom-prometheus-client-0.4.3 lib/prometheus/client/metric.rb
prometheus-client-0.4.2 lib/prometheus/client/metric.rb