Sha256: 7d894f55ecb5acaa6fe5f560174fac6de78ed816e7b76706d0453dc015779092

Contents?: true

Size: 1.65 KB

Versions: 4

Compression:

Stored size: 1.65 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 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)
        unless name.is_a?(Symbol)
          raise ArgumentError, 'metric name must be a symbol'
        end
        unless name.to_s =~ /\A[a-zA-Z_:][a-zA-Z0-9_:]*\Z/
          msg = 'metric name must match /[a-zA-Z_:][a-zA-Z0-9_:]*/'
          raise ArgumentError, msg
        end
      end

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

        raise ArgumentError, 'docstring must be given'
      end

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

      def synchronize
        @mutex.synchronize { yield }
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
prometheus-client-0.9.0 lib/prometheus/client/metric.rb
prometheus-client-0.8.0 lib/prometheus/client/metric.rb
prometheus-client-0.7.1 lib/prometheus/client/metric.rb
prometheus-client-0.7.0 lib/prometheus/client/metric.rb