Sha256: 8eb3f44dd3d015cabd53589d5333a480b80c5ef57a9b17703fb621a3848b6d73

Contents?: true

Size: 1.58 KB

Versions: 2

Compression:

Stored size: 1.58 KB

Contents

# encoding: UTF-8

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

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(key) }

        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].get
      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(labels)
        ValueClass.new(type, @name, @name, labels)
      end

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

        raise ArgumentError, 'given name must be a symbol'
      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(&block)
        @mutex.synchronize(&block)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
prometheus-client-mmap-0.7.0.beta2 lib/prometheus/client/metric.rb
prometheus-client-mmap-0.7.0.beta1 lib/prometheus/client/metric.rb