Sha256: d79abcb1de8ad672b4a69c6dd3d01bc920ba408d5f55784ab68d6fef697f0d9a

Contents?: true

Size: 1.72 KB

Versions: 7

Compression:

Stored size: 1.72 KB

Contents

# encoding: UTF-8

module Prometheus
  module Client
    # LabelSetValidator ensures that all used label sets comply with the
    # Prometheus specification.
    class LabelSetValidator
      # TODO: we might allow setting :instance in the future
      RESERVED_LABELS = [:job, :instance].freeze

      class LabelSetError < StandardError; end
      class InvalidLabelSetError < LabelSetError; end
      class InvalidLabelError < LabelSetError; end
      class ReservedLabelError < LabelSetError; end

      def initialize
        @validated = {}
      end

      def valid?(labels)
        unless labels.respond_to?(:all?)
          raise InvalidLabelSetError, "#{labels} is not a valid label set"
        end

        labels.all? do |key, _|
          validate_symbol(key)
          validate_name(key)
          validate_reserved_key(key)
        end
      end

      def validate(labels)
        return labels if @validated.key?(labels.hash)

        valid?(labels)

        unless @validated.empty? || match?(labels, @validated.first.last)
          raise InvalidLabelSetError, 'labels must have the same signature'
        end

        @validated[labels.hash] = labels
      end

      private

      def match?(a, b)
        a.keys.sort == b.keys.sort
      end

      def validate_symbol(key)
        return true if key.is_a?(Symbol)

        raise InvalidLabelError, "label #{key} is not a symbol"
      end

      def validate_name(key)
        return true unless key.to_s.start_with?('__')

        raise ReservedLabelError, "label #{key} must not start with __"
      end

      def validate_reserved_key(key)
        return true unless RESERVED_LABELS.include?(key)

        raise ReservedLabelError, "#{key} is reserved"
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 2 rubygems

Version Path
prometheus-client-0.8.0 lib/prometheus/client/label_set_validator.rb
prometheus-client-0.7.1 lib/prometheus/client/label_set_validator.rb
prometheus-client-mmap-0.7.0.beta2 lib/prometheus/client/label_set_validator.rb
prometheus-client-0.7.0 lib/prometheus/client/label_set_validator.rb
prometheus-client-mmap-0.7.0.beta1 lib/prometheus/client/label_set_validator.rb
prometheus-client-0.7.0.pre.rc.1 lib/prometheus/client/label_set_validator.rb
prometheus-client-0.6.0 lib/prometheus/client/label_set_validator.rb