serega 0.51.0 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +48 -21
  3. data/VERSION +1 -1
  4. data/docs/README.md +41 -0
  5. data/docs/attributes.md +248 -0
  6. data/docs/batch-loading.md +207 -0
  7. data/docs/camel-case.md +86 -0
  8. data/docs/conditional-attributes.md +165 -0
  9. data/docs/configuration.md +47 -0
  10. data/docs/context.md +34 -0
  11. data/docs/errors.md +38 -0
  12. data/docs/formatters.md +231 -0
  13. data/docs/hash-records.md +93 -0
  14. data/docs/migrating-from-root-and-metadata.md +50 -0
  15. data/docs/preloads.md +125 -0
  16. data/docs/prepare-initial-objects.md +72 -0
  17. data/docs/presenter.md +87 -0
  18. data/docs/presets.md +174 -0
  19. data/docs/ractors.md +54 -0
  20. data/docs/relations.md +233 -0
  21. data/docs/responses.md +548 -0
  22. data/docs/root-and-metadata.md +110 -0
  23. data/docs/selecting-fields.md +157 -0
  24. data/docs/serializing.md +113 -0
  25. data/docs/testing.md +230 -0
  26. data/lib/serega/attribute_normalizer.rb +26 -8
  27. data/lib/serega/attribute_normalizers/block.rb +3 -3
  28. data/lib/serega/config.rb +28 -13
  29. data/lib/serega/errors.rb +5 -4
  30. data/lib/serega/plan/cache.rb +13 -29
  31. data/lib/serega/plan/depth_limit.rb +27 -8
  32. data/lib/serega/plan/per_ractor_cache.rb +2 -2
  33. data/lib/serega/plan/point.rb +13 -2
  34. data/lib/serega/plan/selection.rb +10 -0
  35. data/lib/serega/plan.rb +7 -3
  36. data/lib/serega/plugins/context_metadata/context_metadata.rb +1 -1
  37. data/lib/serega/plugins/root/root.rb +10 -10
  38. data/lib/serega/plugins.rb +13 -0
  39. data/lib/serega/result_code/relation_point_code.rb +3 -2
  40. data/lib/serega/source_group.rb +2 -2
  41. data/lib/serega/validations/attribute/check_block.rb +4 -7
  42. data/lib/serega/validations/attribute/check_opt_hash_access.rb +2 -3
  43. data/lib/serega/validations/check_batch_loader_params.rb +2 -1
  44. data/lib/serega.rb +54 -46
  45. data/sig/serega.rbs +10 -8
  46. metadata +30 -6
data/lib/serega/errors.rb CHANGED
@@ -36,7 +36,7 @@ class Serega
36
36
  # # => Serega::PresetNotExist: Preset :admin is not defined in UserSerializer
37
37
  # ```
38
38
  #
39
- # See [Presets](https://github.com/andreyruby/serega/blob/master/docs/selecting-fields.md#presets).
39
+ # See [Presets](https://github.com/andreyruby/serega/blob/master/docs/presets.md).
40
40
  class PresetNotExist < SeregaError
41
41
  # Serializer that has no such preset
42
42
  attr_reader :serializer
@@ -52,16 +52,17 @@ class Serega
52
52
  end
53
53
 
54
54
  # Raised when fields nest deeper than `config.depth_limit` of the
55
- # serializer that starts the serialization
55
+ # serializer that starts the serialization, or, without a limit, when
56
+ # relations nest in a cycle
56
57
  #
57
58
  # ```ruby
58
59
  # UserSerializer.to_h(user, with: {friends: :friends})
59
60
  # # => Serega::DepthLimitError: Depth limit was exceeded
60
61
  # ```
61
62
  #
62
- # See [Depth limit](https://github.com/andreyruby/serega/blob/master/docs/configuration.md#depth-limit).
63
+ # See [Limiting nesting depth](https://github.com/andreyruby/serega/blob/master/docs/relations.md#limiting-nesting-depth).
63
64
  class DepthLimitError < SeregaError
64
- # Path that exceeds the limit, and on the next line a hint to increase the limit:
65
+ # Path that exceeds the limit or closes the cycle, and on the next line a hint:
65
66
  #
66
67
  # UserSerializer (depth limit: 2) -> friends -> friends
67
68
  # (hint: if the nesting is not a cycle, increase config.depth_limit of UserSerializer)
@@ -9,21 +9,12 @@ class Serega
9
9
  # the plans.
10
10
  #
11
11
  class Cache # :nodoc:
12
- # Cached plan, whether its parameters were validated, and the
13
- # parameters as provided
14
- CACHED_PLAN = Struct.new(:plan, :validated, :param1, :param2, :param3, :param4) do
12
+ # Cached plan and the parameters as provided
13
+ CACHED_PLAN = Struct.new(:plan, :param1, :param2, :param3, :param4) do
15
14
  # Whether the given parameters equal the cached ones
16
15
  def same_params?(param1, param2, param3, param4)
17
16
  param1.eql?(self.param1) && param2.eql?(self.param2) && param3.eql?(self.param3) && param4.eql?(self.param4)
18
17
  end
19
-
20
- # Validates the cached parameters with the planner, once
21
- def validate(planner, serializer_class)
22
- return if validated
23
-
24
- planner.validate(serializer_class, planner.parse(serializer_class, param1, param2, param3, param4))
25
- self.validated = true
26
- end
27
18
  end
28
19
  private_constant :CACHED_PLAN
29
20
 
@@ -46,18 +37,14 @@ class Serega
46
37
  # The plan without parameters is always cached; plans with parameters
47
38
  # are cached by parameters as provided when
48
39
  # `max_cached_plans_per_serializer_count` is positive. Parameters are
49
- # parsed when a plan is built, and validated when
50
- # `check_selection` is true, or nil with
51
- # `config.check_selection` on.
52
- def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil, check_selection: nil)
40
+ # parsed and validated when a plan is built.
41
+ def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil)
53
42
  return default_plan if param1.nil? && param2.nil? && param3.nil? && param4.nil?
54
43
 
55
- config = @serializer_class.config
56
- check_selection = config.check_selection if check_selection.nil?
57
- max_size = config.max_cached_plans_per_serializer_count
58
- return build(param1, param2, param3, param4, check_selection) if max_size.zero?
44
+ max_size = @serializer_class.config.max_cached_plans_per_serializer_count
45
+ return build(param1, param2, param3, param4) if max_size.zero?
59
46
 
60
- cached_plan(param1, param2, param3, param4, max_size, check_selection)
47
+ cached_plan(param1, param2, param3, param4, max_size)
61
48
  end
62
49
 
63
50
  private
@@ -70,16 +57,13 @@ class Serega
70
57
  # Keeps plans by the key of the parameters, and compares each
71
58
  # parameter with the cached one. Parameters with the key of other
72
59
  # cached parameters replace them.
73
- def cached_plan(param1, param2, param3, param4, max_size, check_selection)
60
+ def cached_plan(param1, param2, param3, param4, max_size)
74
61
  key = cache_key(param1, param2, param3, param4)
75
62
  cached = @plans[key]
76
- if cached&.same_params?(param1, param2, param3, param4)
77
- cached.validate(@planner, @serializer_class) if check_selection
78
- return cached.plan
79
- end
63
+ return cached.plan if cached&.same_params?(param1, param2, param3, param4)
80
64
 
81
- plan = build(param1, param2, param3, param4, check_selection)
82
- @plans[key] = CACHED_PLAN.new(plan, check_selection, *frozen_copy([param1, param2, param3, param4]))
65
+ plan = build(param1, param2, param3, param4)
66
+ @plans[key] = CACHED_PLAN.new(plan, *frozen_copy([param1, param2, param3, param4]))
83
67
  @plans.shift if @plans.length > max_size
84
68
  plan
85
69
  end
@@ -103,11 +87,11 @@ class Serega
103
87
  # rubocop:enable Security/CompoundHash
104
88
  end
105
89
 
106
- def build(param1, param2, param3, param4, check_selection)
90
+ def build(param1, param2, param3, param4)
107
91
  params = @planner.parse(@serializer_class, param1, param2, param3, param4)
108
92
  return default_plan if @planner.empty?(params)
109
93
 
110
- @planner.validate(@serializer_class, params) if check_selection
94
+ @planner.validate(@serializer_class, params)
111
95
  @planner.plan(@serializer_class, params)
112
96
  end
113
97
 
@@ -4,19 +4,21 @@ class Serega
4
4
  class SeregaPlan # :nodoc:
5
5
  #
6
6
  # Depth limit of plans: the levels of child plans that `config.depth_limit`
7
- # of the root serializer allows below a plan.
7
+ # of the root serializer allows below a plan. Without a limit, it stops a
8
+ # cycle of relations.
8
9
  #
9
10
  module DepthLimit # :nodoc:
10
11
  class << self
11
- # Depth left below a plan: the depth limit of the serializer for a
12
- # root plan, one level less than the parent plan's for a child plan,
13
- # `nil` without a limit. Raises DepthLimitError when the parent plan
14
- # has no level left.
15
- def depth_left(serializer_class, parent_plan_point)
16
- return serializer_class.config.depth_limit unless parent_plan_point
12
+ # Depth left below the plan of a selection: the depth limit of the
13
+ # serializer for a root plan, one level less than the parent plan's
14
+ # for a child plan, `nil` without a limit. Raises DepthLimitError when
15
+ # the parent plan has no level left, or, without a limit, when a
16
+ # parent plan has the same selection and would repeat without end.
17
+ def depth_left(selection, parent_plan_point)
18
+ return selection.serializer_class.config.depth_limit unless parent_plan_point
17
19
 
18
20
  parent_depth_left = parent_plan_point.plan.depth_left
19
- return unless parent_depth_left
21
+ return check_cycle(selection, parent_plan_point) unless parent_depth_left
20
22
  return parent_depth_left - 1 if parent_depth_left > 1
21
23
 
22
24
  raise_depth_limit_error(parent_plan_point)
@@ -24,12 +26,29 @@ class Serega
24
26
 
25
27
  private
26
28
 
29
+ def check_cycle(selection, parent_plan_point)
30
+ point = parent_plan_point
31
+
32
+ while point
33
+ plan = point.plan
34
+ raise_cycle_error(parent_plan_point) if plan.selection == selection
35
+
36
+ point = plan.parent_plan_point
37
+ end
38
+ end
39
+
27
40
  def raise_depth_limit_error(parent_plan_point)
28
41
  root_serializer = parent_plan_point.plan.root_plan.serializer_class
29
42
  limit = root_serializer.config.depth_limit
30
43
  path = parent_plan_point.path.join(" -> ")
31
44
  raise DepthLimitError.new("Depth limit was exceeded", "#{root_serializer} (depth limit: #{limit}) -> #{path}\n(hint: if the nesting is not a cycle, increase config.depth_limit of #{root_serializer})")
32
45
  end
46
+
47
+ def raise_cycle_error(parent_plan_point)
48
+ root_serializer = parent_plan_point.plan.root_plan.serializer_class
49
+ path = parent_plan_point.path.join(" -> ")
50
+ raise DepthLimitError.new("Relations nest in a cycle", "#{root_serializer} -> #{path}\n(hint: hide a relation of the cycle or set config.depth_limit)")
51
+ end
33
52
  end
34
53
  end
35
54
  end
@@ -19,9 +19,9 @@ class Serega
19
19
  # Returns serialization plan from the plans cache of the current Ractor.
20
20
  # Takes the parameters one by one like Cache#fetch: a splat allocates
21
21
  # an Array on every `Serega.new`.
22
- def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil, check_selection: nil)
22
+ def fetch(param1 = nil, param2 = nil, param3 = nil, param4 = nil)
23
23
  plan_cache = SeregaUtils::RactorLocal.fetch(@key) { SeregaPlan::Cache.new(@serializer_class, @planner) }
24
- plan_cache.fetch(param1, param2, param3, param4, check_selection: check_selection)
24
+ plan_cache.fetch(param1, param2, param3, param4)
25
25
  end
26
26
  end
27
27
  end
@@ -48,9 +48,20 @@ class Serega
48
48
  names
49
49
  end
50
50
 
51
- # Attribute `many` option
51
+ # Attribute `many` option, or `config.many` of the relation serializer
52
+ # when the attribute has no `many` option
52
53
  def many
53
- attribute.many
54
+ many = attribute.many
55
+ return many unless many.nil? && @child_plan
56
+
57
+ @child_plan.serializer_class.config.many
58
+ end
59
+
60
+ # Whether a nil relation value serializes as `[]`: `config.many` of
61
+ # the relation serializer is true, and the attribute has neither the
62
+ # `:many` nor the `:default` option
63
+ def nil_as_empty_list?
64
+ attribute.many.nil? && many == true && !attribute.initials[:opts].key?(:default)
54
65
  end
55
66
 
56
67
  # Attribute `batch_loaders`
@@ -13,6 +13,9 @@ class Serega
13
13
  # Serializer of the selected attributes
14
14
  attr_reader :serializer_class
15
15
 
16
+ # Parsed `only`, `with` and `except` options
17
+ attr_reader :only, :with, :except
18
+
16
19
  # Selects the attributes of the serializer with the parsed selection,
17
20
  # Hashes of attribute names
18
21
  def initialize(serializer_class, selection)
@@ -46,6 +49,13 @@ class Serega
46
49
  Selection.new(attribute.serializer, child_selection(attribute))
47
50
  end
48
51
 
52
+ # Whether the other selection selects the same attributes and child
53
+ # selections of the same serializer
54
+ def ==(other)
55
+ other.class == self.class && other.serializer_class == serializer_class &&
56
+ other.only == @only && other.with == @with && other.except == @except
57
+ end
58
+
49
59
  # Returns the result builder class of the plan: SeregaResultBuilder
50
60
  def builder_class
51
61
  SeregaResultBuilder
data/lib/serega/plan.rb CHANGED
@@ -9,6 +9,9 @@ class Serega
9
9
  # Serializer of the plan
10
10
  attr_reader :serializer_class
11
11
 
12
+ # Selection of the attributes of the plan
13
+ attr_reader :selection
14
+
12
15
  # Parent plan point
13
16
  attr_reader :parent_plan_point
14
17
 
@@ -33,13 +36,14 @@ class Serega
33
36
  # selection's serializer, with the result builder class of the
34
37
  # selection. A child plan gets the point of its parent plan. Raises
35
38
  # DepthLimitError when the plan nests deeper than the depth limit of the
36
- # root serializer.
39
+ # root serializer, or repeats a parent plan without a depth limit.
37
40
  def initialize(selection, parent_plan_point = nil)
38
41
  serializer_class = selection.serializer_class
39
42
  serializer_class.lock
40
43
  @serializer_class = serializer_class
44
+ @selection = selection
41
45
  @parent_plan_point = parent_plan_point
42
- @depth_left = DepthLimit.depth_left(serializer_class, parent_plan_point)
46
+ @depth_left = DepthLimit.depth_left(selection, parent_plan_point)
43
47
  @builder_class = selection.builder_class
44
48
  @points = selected_points(selection)
45
49
  @presenter = points_presenter(serializer_class)
@@ -55,7 +59,7 @@ class Serega
55
59
  rescue *RACTOR_ISOLATION_ERRORS
56
60
  raise if serializer_class.shareable?
57
61
 
58
- raise SeregaError, "#{serializer_class} can not serialize in other Ractors. Call `make_shareable!` at the end of its definition"
62
+ raise SeregaError, "#{serializer_class} can not serialize in other Ractors\n(hint: call `make_shareable!` at the end of its definition)"
59
63
  # :nocov:
60
64
  end
61
65
 
@@ -10,7 +10,7 @@ class Serega
10
10
  # plugin :context_metadata
11
11
  #
12
12
  # UserSerializer.to_h(user, meta: {version: "1.0.1"})
13
- # # => {data: {username: "batman"}, version: "1.0.1"}
13
+ # # => {data: {username: "gru"}, version: "1.0.1"}
14
14
  # ```
15
15
  #
16
16
  # See [Metadata per serialization](https://github.com/andreyruby/serega/blob/master/docs/root-and-metadata.md#metadata-per-serialization).
@@ -9,8 +9,8 @@ class Serega
9
9
  # plugin :root, root: :users # one key for objects and lists
10
10
  # plugin :root, root_one: :user, root_many: :users # separate keys
11
11
  #
12
- # UserSerializer.to_h(user, root: :user) # => {user: {username: "batman"}}
13
- # UserSerializer.to_h(user, root: nil) # => {username: "batman"}
12
+ # UserSerializer.to_h(user, root: :user) # => {user: {username: "gru"}}
13
+ # UserSerializer.to_h(user, root: nil) # => {username: "gru"}
14
14
  # ```
15
15
  #
16
16
  # See [Root key](https://github.com/andreyruby/serega/blob/master/docs/root-and-metadata.md#root-key).
@@ -38,23 +38,23 @@ class Serega
38
38
 
39
39
  # Class methods the plugin adds to serializers
40
40
  module ClassMethods
41
- def call(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil, **opts) # :nodoc:
42
- new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
41
+ def call(object, only: nil, with: nil, except: nil, preset: nil, context: nil, many: nil, **opts) # :nodoc:
42
+ new(only: only, with: with, except: except, preset: preset)
43
43
  .to_h(object, context: context, many: many, **opts)
44
44
  end
45
45
 
46
- def to_data(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil, **opts) # :nodoc:
47
- new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
46
+ def to_data(object, only: nil, with: nil, except: nil, preset: nil, context: nil, many: nil, **opts) # :nodoc:
47
+ new(only: only, with: with, except: except, preset: preset)
48
48
  .to_data(object, context: context, many: many, **opts)
49
49
  end
50
50
 
51
- def to_struct(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil, **opts) # :nodoc:
52
- new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
51
+ def to_struct(object, only: nil, with: nil, except: nil, preset: nil, context: nil, many: nil, **opts) # :nodoc:
52
+ new(only: only, with: with, except: except, preset: preset)
53
53
  .to_struct(object, context: context, many: many, **opts)
54
54
  end
55
55
 
56
- def to_json(object, only: nil, with: nil, except: nil, preset: nil, check_selection: nil, context: nil, many: nil, **opts) # :nodoc:
57
- new(only: only, with: with, except: except, preset: preset, check_selection: check_selection)
56
+ def to_json(object, only: nil, with: nil, except: nil, preset: nil, context: nil, many: nil, **opts) # :nodoc:
57
+ new(only: only, with: with, except: except, preset: preset)
58
58
  .to_json(object, context: context, many: many, **opts)
59
59
  end
60
60
 
@@ -13,6 +13,9 @@ class Serega
13
13
  activerecord_preloads: :ActiverecordPreloads
14
14
  }.freeze
15
15
 
16
+ # Names of deprecated plugins, replaced by response serializers
17
+ DEPRECATED = %i[root metadata context_metadata].freeze # :nodoc:
18
+
16
19
  class << self
17
20
  # Loads the code of the plugin and returns its module. Raises
18
21
  # SeregaError when the plugin does not exist.
@@ -21,6 +24,16 @@ class Serega
21
24
  require_relative "plugins/#{name}/#{name}"
22
25
  const_get(module_name)
23
26
  end
27
+
28
+ # Warning text for a deprecated plugin, `nil` for the others
29
+ def deprecation_warning(serializer_class, name) # :nodoc:
30
+ return unless DEPRECATED.include?(name)
31
+
32
+ "#{serializer_class}: plugin #{name.inspect} is deprecated. Migrate to a response serializer with data and " \
33
+ "meta attributes: " \
34
+ "https://github.com/andreyruby/serega/blob/master/docs/migrating-from-root-and-metadata.md. " \
35
+ "Set config.deprecation_warnings = false to hide this warning."
36
+ end
24
37
  end
25
38
  end
26
39
  end
@@ -74,12 +74,13 @@ class Serega
74
74
  private
75
75
 
76
76
  # Code that appends the sources of `value_N` to `child_sources_N` and
77
- # gives its pull, as SeregaEngine::Pulls.append does
77
+ # gives its pull, as SeregaEngine::Pulls.append does. A nil value gives
78
+ # the pull 0, an empty list, when the point serializes nil as `[]`.
78
79
  def pull_code
79
80
  index = @index
80
81
  <<~RUBY.chomp
81
82
  #{skip_branch}if value_#{index}.nil?
82
- nil
83
+ #{@point.nil_as_empty_list? ? "0" : "nil"}
83
84
  #{collection_branch}else
84
85
  child_sources_#{index} << value_#{index}
85
86
  #{@point.many ? "1" : "Serega::SeregaEngine::Pulls::SINGLE_SOURCE"}
@@ -103,12 +103,12 @@ class Serega
103
103
  return if points.empty?
104
104
 
105
105
  serializer_class = plan.serializer_class
106
- handler = serializer_class.preload_with
106
+ handler = serializer_class.preload_with_handler
107
107
  sources = plan.presenter ? @sources.map(&:__getobj__) : @sources
108
108
 
109
109
  points.each do |point|
110
110
  unless handler
111
- raise SeregaError, "The :preload option requires a preload handler. Register one with `preload_with` (the :activerecord_preloads plugin does this for you)."
111
+ raise SeregaError, "The :preload option requires a preload handler\n(hint: register one with `preload_with`, or load the :activerecord_preloads plugin)"
112
112
  end
113
113
 
114
114
  handler.call(sources, point.preloads)
@@ -10,14 +10,11 @@ class Serega
10
10
  # Attribute `block` parameter validator
11
11
  #
12
12
  class CheckBlock # :nodoc:
13
- # Explains the changed attribute block behavior. Shown when the block
14
- # looks like an old-style value block — it accepts parameters or
15
- # defines no attributes.
13
+ # Error of a block that looks like a value block: it accepts
14
+ # parameters or defines no attributes.
16
15
  ERROR_MESSAGE =
17
- "Attribute block now defines a nested serializer:" \
18
- " it is executed in the context of a new serializer class and must define its attributes." \
19
- " Defining the attribute value with a block is not supported anymore," \
20
- " use the `value: <callable>` option instead."
16
+ "Attribute block defines a nested serializer and must define its attributes\n" \
17
+ "(hint: to compute the attribute value, use the `value: <callable>` option)"
21
18
 
22
19
  class << self
23
20
  # Checks block parameter provided with attribute.
@@ -22,9 +22,8 @@ class Serega
22
22
  return unless opts.key?(:delegate)
23
23
 
24
24
  raise SeregaError,
25
- "Option :hash_access can not be used together with option :delegate." \
26
- " Use the delegate :to_hash_access (intermediate step) and" \
27
- " :hash_access (final step) sub-options instead"
25
+ "Option :hash_access can not be used together with option :delegate\n" \
26
+ "(hint: use the :to_hash_access and :hash_access sub-options of :delegate)"
28
27
  end
29
28
  end
30
29
  end
@@ -56,7 +56,8 @@ class Serega
56
56
  <<~ERR.strip
57
57
  Batch loader arguments should have one of this signatures:
58
58
  - (objects) # one argument
59
- - (objects, :ctx) # one argument and one :ctx keyword argument
59
+ - (objects, ctx) # two arguments, the second is the context
60
+ - (objects, ctx:) # one argument and the :ctx keyword argument
60
61
  ERR
61
62
  end
62
63
  end