Module: Labkit::RateLimit::Config::Parser

Defined in:
lib/labkit/rate_limit/config/parser.rb

Overview

Parser is the parse step: a YAML file into a protobuf message.

YAML types do not follow the schema, so each scalar is converted by the type of the field it fills, the way protoyaml does in Go: a string field keeps the scalar text (off, True and 9970 stay strings), an integer or enum field gets an Integer when the text is one, quoted or not, and the YAML null forms mean the field is absent. Psych keeps the last value of a repeated key, so repeated keys are rejected here, also when one spelling is the snake_case field name and the other its camelCase json_name.

This step checks the shape of a document, not its values. An enum number that no Action defines, such as action: 7, passes in both modes, and in lenient mode protobuf drops an unknown enum name together with the unknown fields, so a rule with a misspelt action reaches the schema step as ACTION_UNSPECIFIED. Schema.check! rejects both.

Constant Summary collapse

INT32 =
(-(2**31))...(2**31)
UINT32 =
0...(2**32)
INT64 =
(-(2**63))...(2**63)
UINT64 =
0...(2**64)
INTEGER_RANGES =
{
  int32: INT32, sint32: INT32, sfixed32: INT32, enum: INT32,
  uint32: UINT32, fixed32: UINT32,
  int64: INT64, sint64: INT64, sfixed64: INT64,
  uint64: UINT64, fixed64: UINT64
}.freeze
INTEGER =
/\A[-+]?\d+\z/
NULLS =
["", "~", "null", "Null", "NULL"].freeze
MAX_DEPTH =

The protobuf JSON decoder stops at 64 levels of objects and arrays. Mappings and lists are counted here so the error names the YAML line and a deeper document cannot exhaust the stack.

64

Class Method Summary collapse

Class Method Details

.parse(path, klass, strict:) ⇒ Google::Protobuf::AbstractMessage

Parameters:

  • path (String) —

    YAML file

  • klass (Class) —

    a Proto message class, AvailableLimiters or RateLimits

  • strict (Boolean) —

    when true an unknown field is an error

Returns:

  • (Google::Protobuf::AbstractMessage)

Raises:

  • (Error) —

    with step :parse



50
51
52
53
54
55
56
57
58
# File 'lib/labkit/rate_limit/config/parser.rb', line 50

def parse(path, klass, strict:)
  tree = tree_for(document_root(path), klass.descriptor, strict: strict, depth: 0)
  klass.decode_json(JSON.generate(tree), ignore_unknown_fields: !strict)
rescue Psych::SyntaxError, SystemCallError => e
  # Both messages already name the file.
  raise Error.new(:parse, e.message)
rescue Google::Protobuf::ParseError, Psych::Exception, JSON::JSONError => e
  raise Error.new(:parse, "#{path}: #{e.message}")
end