mongoid 9.1.1 → 9.1.3

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 (85) hide show
  1. checksums.yaml +4 -4
  2. data/lib/config/locales/en.yml +44 -11
  3. data/lib/mongoid/association/accessors.rb +21 -4
  4. data/lib/mongoid/association/eager_load/discriminated_inclusion.rb +10 -10
  5. data/lib/mongoid/association/eager_load/embedded_distributor.rb +6 -6
  6. data/lib/mongoid/association/eager_load/lookup_pipeline.rb +1 -1
  7. data/lib/mongoid/association/eager_loadable.rb +8 -1
  8. data/lib/mongoid/association/embedded/batchable.rb +17 -1
  9. data/lib/mongoid/association/nested/many.rb +1 -1
  10. data/lib/mongoid/association/referenced/belongs_to/buildable.rb +19 -15
  11. data/lib/mongoid/association/referenced/belongs_to.rb +11 -3
  12. data/lib/mongoid/association/referenced/has_and_belongs_to_many/buildable.rb +25 -5
  13. data/lib/mongoid/association/referenced/has_and_belongs_to_many.rb +12 -0
  14. data/lib/mongoid/association/referenced/has_many/buildable.rb +17 -7
  15. data/lib/mongoid/association/referenced/has_many/proxy.rb +4 -2
  16. data/lib/mongoid/association/referenced/has_one/buildable.rb +20 -6
  17. data/lib/mongoid/association/relatable.rb +18 -0
  18. data/lib/mongoid/association.rb +23 -0
  19. data/lib/mongoid/atomic/modifiers.rb +100 -16
  20. data/lib/mongoid/attributes/readonly.rb +19 -1
  21. data/lib/mongoid/changeable.rb +19 -1
  22. data/lib/mongoid/clients/factory.rb +2 -0
  23. data/lib/mongoid/config/encryption.rb +152 -19
  24. data/lib/mongoid/contextual/none.rb +51 -0
  25. data/lib/mongoid/criteria/scopable.rb +5 -0
  26. data/lib/mongoid/criteria.rb +45 -1
  27. data/lib/mongoid/document.rb +13 -0
  28. data/lib/mongoid/encryptable.rb +43 -16
  29. data/lib/mongoid/errors/invalid_encrypted_association.rb +28 -0
  30. data/lib/mongoid/errors/invalid_encryption_schema.rb +27 -0
  31. data/lib/mongoid/errors/no_encryption_schema.rb +5 -3
  32. data/lib/mongoid/errors.rb +2 -0
  33. data/lib/mongoid/factory.rb +1 -1
  34. data/lib/mongoid/fields/encrypted.rb +14 -3
  35. data/lib/mongoid/fields/foreign_key.rb +9 -0
  36. data/lib/mongoid/fields/standard.rb +10 -0
  37. data/lib/mongoid/fields/validators/macro.rb +29 -0
  38. data/lib/mongoid/fields.rb +49 -2
  39. data/lib/mongoid/persistable/creatable.rb +120 -14
  40. data/lib/mongoid/persistable.rb +15 -15
  41. data/lib/mongoid/persistence_context.rb +46 -4
  42. data/lib/mongoid/reloadable.rb +1 -0
  43. data/lib/mongoid/search_indexable.rb +5 -1
  44. data/lib/mongoid/tasks/database.rb +10 -7
  45. data/lib/mongoid/touchable.rb +28 -1
  46. data/lib/mongoid/version.rb +1 -1
  47. data/lib/mongoid/warnings.rb +4 -0
  48. data/spec/integration/associations/embedded_delayed_atomic_sets_spec.rb +216 -0
  49. data/spec/integration/associations/has_and_belongs_to_many_spec.rb +14 -0
  50. data/spec/integration/atomic/modifiers_spec.rb +283 -0
  51. data/spec/integration/encryption_spec.rb +418 -0
  52. data/spec/mongoid/association/accessors_spec.rb +35 -0
  53. data/spec/mongoid/association/referenced/belongs_to/buildable_spec.rb +35 -6
  54. data/spec/mongoid/association/referenced/encrypted_foreign_key_spec.rb +142 -0
  55. data/spec/mongoid/association/referenced/has_and_belongs_to_many/buildable_spec.rb +36 -5
  56. data/spec/mongoid/association/referenced/has_and_belongs_to_many/proxy_spec.rb +48 -0
  57. data/spec/mongoid/association/referenced/has_many/buildable_spec.rb +24 -6
  58. data/spec/mongoid/association/referenced/has_many/proxy_spec.rb +81 -0
  59. data/spec/mongoid/association/referenced/has_one/buildable_spec.rb +18 -3
  60. data/spec/mongoid/atomic/modifiers_spec.rb +347 -0
  61. data/spec/mongoid/attributes/nested_spec.rb +29 -0
  62. data/spec/mongoid/attributes/readonly_dotted_spec.rb +334 -0
  63. data/spec/mongoid/attributes/readonly_spec.rb +389 -0
  64. data/spec/mongoid/changeable_spec.rb +18 -0
  65. data/spec/mongoid/clients/factory_spec.rb +36 -0
  66. data/spec/mongoid/config/encryption_spec.rb +450 -0
  67. data/spec/mongoid/contextual/none_spec.rb +18 -0
  68. data/spec/mongoid/criteria/includable_spec.rb +346 -0
  69. data/spec/mongoid/criteria_spec.rb +17 -0
  70. data/spec/mongoid/encryptable_spec.rb +54 -0
  71. data/spec/mongoid/factory_spec.rb +8 -0
  72. data/spec/mongoid/fields_spec.rb +37 -0
  73. data/spec/mongoid/findable_spec.rb +14 -0
  74. data/spec/mongoid/scopable_spec.rb +102 -0
  75. data/spec/mongoid/search_indexable_spec.rb +26 -0
  76. data/spec/mongoid/tasks/database_spec.rb +13 -0
  77. data/spec/mongoid/touchable_spec.rb +217 -0
  78. data/spec/mongoid/touchable_spec_models.rb +37 -0
  79. data/spec/support/crypt/models.rb +138 -0
  80. data/spec/support/models/delete_all_account.rb +10 -0
  81. data/spec/support/models/delete_all_item.rb +9 -0
  82. data/spec/support/models/delete_all_scoped_item.rb +11 -0
  83. data/spec/support/models/delete_all_tag.rb +7 -0
  84. data/spec/support/models/modifier_models.rb +65 -0
  85. metadata +2045 -2008
@@ -166,6 +166,12 @@ module Mongoid
166
166
  def internal_state=(state)
167
167
  self._id = state[:id]
168
168
  @changed_attributes = state[:changed_attributes]
169
+ # The document was constructed as new in #becomes, collecting
170
+ # pre-create change markers. Drop them when the copied state is that
171
+ # of a persisted document: its pending changes were all tracked after
172
+ # the document was persisted, and stale markers would let in-place
173
+ # changes to readonly attributes bypass the dirty filter.
174
+ @pre_create_changed_attributes = nil unless state[:new_record]
169
175
  @errors = ActiveModel::Errors.new(self).tap { |e| e.copy!(state[:errors]) }
170
176
  @new_record = state[:new_record]
171
177
  @destroyed = state[:destroyed]
@@ -337,6 +343,10 @@ module Mongoid
337
343
  relation = __send__(name)
338
344
  Array.wrap(relation).each do |r|
339
345
  r.instance_variable_set(:@new_record, new_record)
346
+ # The embedded documents were also constructed as new; drop
347
+ # their pre-create change markers when they are marked as
348
+ # persisted, as #internal_state= does for the parent document.
349
+ r.instance_variable_set(:@pre_create_changed_attributes, nil) unless new_record
340
350
  end
341
351
  end
342
352
  end
@@ -410,6 +420,8 @@ module Mongoid
410
420
  def instantiate_document(attrs = nil, selected_fields = nil, options = {}, &block)
411
421
  execute_callbacks = options.fetch(:execute_callbacks, Threaded.execute_callbacks?)
412
422
  attributes = attrs.to_h
423
+ preloaded_fields = attributes.keys.select { |key| key.start_with?(Association::PRELOADED_PREFIX) }
424
+ preloaded = attributes.extract!(*preloaded_fields)
413
425
 
414
426
  doc = allocate
415
427
  doc.__selected_fields = selected_fields
@@ -417,6 +429,7 @@ module Mongoid
417
429
  doc.instance_variable_set(:@attributes_before_type_cast, attributes.dup)
418
430
 
419
431
  doc._handle_callbacks_after_instantiation(execute_callbacks, &block)
432
+ doc.load_preloaded_associations(preloaded)
420
433
 
421
434
  doc.remember_storage_options!
422
435
  doc
@@ -33,7 +33,7 @@ module Mongoid
33
33
  #
34
34
  # @return [ true | false ] Whether the model is encrypted.
35
35
  def encrypted?
36
- !encrypt_metadata.empty? || fields.any? { |_, field| field.is_a?(Mongoid::Fields::Encrypted) }
36
+ !encrypt_metadata.empty? || fields.any? { |_, field| field.encrypted? }
37
37
  end
38
38
 
39
39
  # Whether an encryption schema has to be generated for this model.
@@ -43,21 +43,29 @@ module Mongoid
43
43
  # group has no encrypted field of its own, but its collection still needs
44
44
  # a schema, otherwise the embedded fields are written in plaintext.
45
45
  #
46
- # The answer is memoized, since this runs on the persistence path.
47
- # Declaring encryption on a model after it has already been persisted is
48
- # not supported.
46
+ # This runs on the persistence path, so the answer is memoized. A true
47
+ # answer is always memoized. A false answer is memoized only when every
48
+ # embeds_one target in the walk resolved to a class; if one could not be
49
+ # resolved yet, the answer is recomputed next time, so a class loaded
50
+ # later is still detected. Declaring encryption on a model after it has
51
+ # already been persisted is not supported.
49
52
  #
50
53
  # @return [ true | false ] Whether the model needs an encryption schema.
51
54
  #
52
55
  # @api private
53
56
  def requires_encryption_schema?
54
57
  return @requires_encryption_schema if defined?(@requires_encryption_schema)
58
+ return @requires_encryption_schema = true if encrypted?
55
59
 
56
- @requires_encryption_schema = encrypted? || embeds_encrypted?([ self ])
60
+ found, complete = embedded_encryption_scan([ self ])
61
+ @requires_encryption_schema = found if found || complete
62
+ found
57
63
  end
58
64
 
59
- # Whether any model reachable through this model's embeds_one relations
60
- # declares encryption.
65
+ # Walks the models reachable through this model's embeds_one relations,
66
+ # looking for one that declares encryption. Subclasses of an
67
+ # association target are included: any of them can be assigned to the
68
+ # association.
61
69
  #
62
70
  # embeds_many is not considered: libmongocrypt cannot express per-field
63
71
  # encryption under array items, so those fields are never mapped.
@@ -65,21 +73,40 @@ module Mongoid
65
73
  # @param [ Array<Class> ] path The models the walk is already inside of.
66
74
  # A model embedding itself terminates here.
67
75
  #
68
- # @return [ true | false ] Whether an embedded model is encrypted.
76
+ # @return [ Array<true | false> ] A pair: whether an embedded model is
77
+ # encrypted, and whether every embeds_one target the walk needed
78
+ # resolved to a class. The second value is only meaningful when the
79
+ # first is false.
69
80
  #
70
81
  # @api private
71
- def embeds_encrypted?(path)
72
- relations.each_value.any? do |relation|
73
- next false unless relation.is_a?(Association::Embedded::EmbedsOne)
82
+ def embedded_encryption_scan(path)
83
+ complete = true
84
+
85
+ relations.each_value do |relation|
86
+ next unless relation.is_a?(Association::Embedded::EmbedsOne)
74
87
 
75
88
  klass = relation.try_relation_class
76
- # An association target does not have to be a Mongoid document, and
77
- # the class it names does not have to exist.
78
- next false unless klass.respond_to?(:encrypted?)
79
- next false if path.include?(klass)
89
+ # The class an association names does not have to exist yet.
90
+ if klass.nil?
91
+ complete = false
92
+ next
93
+ end
94
+
95
+ # An association target does not have to be a Mongoid document.
96
+ next unless klass.respond_to?(:encrypted?)
97
+
98
+ ([ klass ] + klass.descendants).uniq.each do |candidate|
99
+ next if path.include?(candidate)
100
+ return [ true, true ] if candidate.encrypted?
80
101
 
81
- klass.encrypted? || klass.embeds_encrypted?(path + [ klass ])
102
+ found, nested_complete = candidate.embedded_encryption_scan(path + [ candidate ])
103
+ return [ true, true ] if found
104
+
105
+ complete &&= nested_complete
106
+ end
82
107
  end
108
+
109
+ [ false, complete ]
83
110
  end
84
111
 
85
112
  # Override the key_id for the model.
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mongoid
4
+ module Errors
5
+ # This error is raised when an encrypted field is used as the foreign key
6
+ # of a has_and_belongs_to_many association. Encryption protects an array
7
+ # only as a whole, while the association queries and atomically updates
8
+ # individual elements of it, so the association cannot manage the key.
9
+ class InvalidEncryptedAssociation < MongoidError
10
+ # Create the new error.
11
+ #
12
+ # @example Create the error.
13
+ # InvalidEncryptedAssociation.new(Person, :preferences, 'preference_ids')
14
+ #
15
+ # @param [ Class ] klass The model declaring the association.
16
+ # @param [ Symbol | String ] association The association name.
17
+ # @param [ String ] field The encrypted foreign key field.
18
+ def initialize(klass, association, field)
19
+ super(
20
+ compose_message(
21
+ 'invalid_encrypted_association',
22
+ { klass: klass.name, association: association, field: field }
23
+ )
24
+ )
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mongoid
4
+ module Errors
5
+ # This error is raised when two models writing to the same namespace
6
+ # describe a field, or the collection metadata, differently. The schema map
7
+ # has one entry per namespace, so the two descriptions cannot both be
8
+ # honored.
9
+ class InvalidEncryptionSchema < MongoidError
10
+ # Create the new error.
11
+ #
12
+ # @example Create the error.
13
+ # InvalidEncryptionSchema.new('music.bands', 'properties.code')
14
+ #
15
+ # @param [ String | nil ] namespace The namespace being described.
16
+ # @param [ String ] path The conflicting path in the schema.
17
+ def initialize(namespace, path)
18
+ super(
19
+ compose_message(
20
+ 'invalid_encryption_schema',
21
+ { namespace: namespace || 'the collection', path: path }
22
+ )
23
+ )
24
+ end
25
+ end
26
+ end
27
+ end
@@ -15,11 +15,13 @@ module Mongoid
15
15
  # @param [ Class ] klass The model class.
16
16
  # @param [ String ] namespace The namespace the model resolved to.
17
17
  # @param [ String | Symbol ] client The name of the client in use.
18
- def initialize(klass, namespace, client)
18
+ # @param [ String | nil ] field The encrypted field missing from the
19
+ # schema entry, if the namespace itself is covered.
20
+ def initialize(klass, namespace, client, field = nil)
19
21
  super(
20
22
  compose_message(
21
- 'no_encryption_schema',
22
- { klass: klass, namespace: namespace, client: client }
23
+ field ? 'no_encryption_schema_field' : 'no_encryption_schema',
24
+ { klass: klass, namespace: namespace, client: client, field: field }
23
25
  )
24
26
  )
25
27
  end
@@ -20,6 +20,8 @@ require 'mongoid/errors/invalid_collection'
20
20
  require 'mongoid/errors/invalid_config_file'
21
21
  require 'mongoid/errors/invalid_config_option'
22
22
  require 'mongoid/errors/invalid_dependent_strategy'
23
+ require 'mongoid/errors/invalid_encrypted_association'
24
+ require 'mongoid/errors/invalid_encryption_schema'
23
25
  require 'mongoid/errors/invalid_field'
24
26
  require 'mongoid/errors/invalid_field_option'
25
27
  require 'mongoid/errors/invalid_field_type'
@@ -109,7 +109,7 @@ module Mongoid
109
109
  constantized = klass.get_discriminator_mapping(type) || constantize(type)
110
110
 
111
111
  # Check if the class is a Document class
112
- raise Errors::UnknownModel.new(camelized, type) unless constantized.respond_to?(:instantiate)
112
+ raise Errors::UnknownModel.new(type.camelize, type) unless constantized.respond_to?(:instantiate)
113
113
 
114
114
  constantized
115
115
  end
@@ -2,8 +2,8 @@
2
2
 
3
3
  module Mongoid
4
4
  module Fields
5
- # Represents a field that should be encrypted.
6
- class Encrypted < Standard
5
+ # Behavior shared by the field types whose value is encrypted.
6
+ module EncryptionOptions
7
7
  def initialize(name, options = {})
8
8
  @encryption_options = if options[:encrypt].is_a?(Hash)
9
9
  options[:encrypt]
@@ -13,6 +13,11 @@ module Mongoid
13
13
  super
14
14
  end
15
15
 
16
+ # @return [ true ] Always true: this field is encrypted.
17
+ def encrypted?
18
+ true
19
+ end
20
+
16
21
  # @return [ true | false | nil ] Whether the field should be encrypted using a
17
22
  # deterministic encryption algorithm; if not specified, nil is returned.
18
23
  def deterministic?
@@ -26,7 +31,8 @@ module Mongoid
26
31
  end
27
32
 
28
33
  # @return [ String | nil ] The name of the field that contains the
29
- # key alt name to use for encryption; if not specified, nil is returned.
34
+ # key alt name to use for encryption; if not specified, nil is
35
+ # returned.
30
36
  def key_name_field
31
37
  @encryption_options[:key_name_field]
32
38
  end
@@ -43,5 +49,10 @@ module Mongoid
43
49
  @encryption_options[:key_id] = key_id
44
50
  end
45
51
  end
52
+
53
+ # Represents a field that should be encrypted.
54
+ class Encrypted < Standard
55
+ include EncryptionOptions
56
+ end
46
57
  end
47
58
  end
@@ -187,5 +187,14 @@ module Mongoid
187
187
  object
188
188
  end
189
189
  end
190
+
191
+ # Represents a foreign key field whose value is encrypted.
192
+ #
193
+ # A belongs_to association stores its key in a single value, so it can be
194
+ # encrypted like any other field. The encryption options of the field
195
+ # declared before the association are preserved here.
196
+ class EncryptedForeignKey < ForeignKey
197
+ include EncryptionOptions
198
+ end
190
199
  end
191
200
  end
@@ -56,6 +56,16 @@ module Mongoid
56
56
  false
57
57
  end
58
58
 
59
+ # Is this field encrypted?
60
+ #
61
+ # @example Is the field encrypted?
62
+ # field.encrypted?
63
+ #
64
+ # @return [ true | false ] If the field is encrypted.
65
+ def encrypted?
66
+ false
67
+ end
68
+
59
69
  # Create the new field with a name and optional additional options.
60
70
  #
61
71
  # @example Create the new field.
@@ -34,6 +34,7 @@ module Mongoid
34
34
  validate_field_name(klass, name)
35
35
  validate_name_uniqueness(klass, name, options)
36
36
  validate_options(klass, name, options)
37
+ validate_encrypted_association(klass, name, options)
37
38
  end
38
39
 
39
40
  # Validate the association definition.
@@ -109,6 +110,34 @@ module Mongoid
109
110
  Mongoid::Warnings.warn_symbol_type_deprecated if option == :type && options[option] == Symbol
110
111
  end
111
112
  end
113
+
114
+ # Determine if an encrypted field is the foreign key of a
115
+ # has_and_belongs_to_many association. Defining the field after the
116
+ # association has to be rejected, and so does defining it on a parent
117
+ # of the class that declares the association: the field is propagated
118
+ # to the descendants and would replace their association key.
119
+ #
120
+ # @api private
121
+ #
122
+ # @param [ Class ] klass The model class.
123
+ # @param [ Symbol | String ] name The field name.
124
+ # @param [ Hash ] options The provided options.
125
+ #
126
+ # @raise [ Errors::InvalidEncryptedAssociation ] If the field is the
127
+ # foreign key of a has_and_belongs_to_many association.
128
+ def validate_encrypted_association(klass, name, options)
129
+ return unless options[:encrypt]
130
+
131
+ ([ klass ] + klass.descendants).each do |candidate|
132
+ field = candidate.fields[name.to_s]
133
+ next unless field&.foreign_key?
134
+
135
+ association = field.association
136
+ next unless association.is_a?(Association::Referenced::HasAndBelongsToMany)
137
+
138
+ raise Errors::InvalidEncryptedAssociation.new(candidate, association.name, name)
139
+ end
140
+ end
112
141
  end
113
142
  end
114
143
  end
@@ -412,6 +412,13 @@ module Mongoid
412
412
  return '' unless name.present?
413
413
 
414
414
  key = name.to_s
415
+
416
+ # A key without a "." refers to an immediate field, so it resolves to
417
+ # its alias (or itself) with no splitting. Short-circuiting here avoids
418
+ # the split and dup on every read, which is a hot path. This mirrors the
419
+ # same optimization already applied to the matcher.
420
+ return aliased_fields[key]&.dup || key unless key.include?('.')
421
+
415
422
  segment, remaining = key.split('.', 2)
416
423
 
417
424
  # Don't get the alias for the field when a belongs_to association
@@ -579,7 +586,7 @@ module Mongoid
579
586
  Validators::Macro.validate(self, name, options)
580
587
  added = add_field(named, options)
581
588
  descendants.each do |subclass|
582
- subclass.add_field(named, options)
589
+ subclass.add_field(named, descendant_field_options(subclass, named, options))
583
590
  end
584
591
  added
585
592
  end
@@ -674,6 +681,41 @@ module Mongoid
674
681
  field
675
682
  end
676
683
 
684
+ # Build the options to apply to a descendant when a belongs_to
685
+ # association declared on an ancestor generates its foreign key. A
686
+ # descendant may declare the field as encrypted before the association
687
+ # is declared on the parent. The encryption options and the declared
688
+ # type belong to the descendant and must survive the propagation, as
689
+ # must the foreign key behavior.
690
+ #
691
+ # When the descendant's encryption options differ from the ancestor's,
692
+ # the difference is preserved: the schema generation reports it instead
693
+ # of one declaration silently overriding the other.
694
+ #
695
+ # A field declared without an association is not covered: the ancestor's
696
+ # declaration keeps replacing the descendant's field as before.
697
+ #
698
+ # @api private
699
+ #
700
+ # @param [ Class ] subclass The descendant the field is propagated to.
701
+ # @param [ String ] name The field name.
702
+ # @param [ Hash ] options The options of the ancestor's declaration.
703
+ #
704
+ # @return [ Hash ] The options to apply to the descendant.
705
+ def descendant_field_options(subclass, name, options)
706
+ return options unless options[:identity]
707
+ return options unless options[:association].is_a?(Association::Referenced::BelongsTo)
708
+
709
+ existing = subclass.fields[name]
710
+ return options unless existing&.encrypted?
711
+
712
+ preserved = options.merge(type: existing.type, encrypt: existing.options[:encrypt])
713
+ if existing.foreign_key? && existing.association
714
+ preserved[:association] = existing.association
715
+ end
716
+ preserved
717
+ end
718
+
677
719
  # Run through all custom options stored in Mongoid::Fields.options and
678
720
  # execute the handler if the option is provided.
679
721
  #
@@ -894,7 +936,12 @@ module Mongoid
894
936
  opts = options.merge(klass: self)
895
937
  opts[:type] = retrieve_and_validate_type(name, options[:type])
896
938
  return Fields::Localized.new(name, opts) if options[:localize]
897
- return Fields::ForeignKey.new(name, opts) if options[:identity]
939
+
940
+ if options[:identity]
941
+ return Fields::EncryptedForeignKey.new(name, opts) if options[:encrypt]
942
+
943
+ return Fields::ForeignKey.new(name, opts)
944
+ end
898
945
  return Fields::Encrypted.new(name, opts) if options[:encrypt]
899
946
 
900
947
  Fields::Standard.new(name, opts)
@@ -39,13 +39,79 @@ module Mongoid
39
39
  { atomic_insert_modifier => { atomic_position => as_attributes } }
40
40
  end
41
41
 
42
+ # Determine whether merging the touch updates into the insert
43
+ # operations would produce an update whose operators target both a
44
+ # path and one of its ancestors or descendants. MongoDB rejects such
45
+ # an update with error 40. This can happen for embeds_many inserts,
46
+ # where the operations target the array (via $push) but the touches
47
+ # include a path inside that array (e.g. items.0.updated_at) when a
48
+ # sibling has a pending touch.
49
+ #
50
+ # @api private
51
+ #
52
+ # @param [ Hash ] operations The atomic insert operations.
53
+ # @param [ Hash ] touches The touch updates to merge.
54
+ #
55
+ # @return [ true | false ] Whether any touch path conflicts with a
56
+ # path the insert operations target.
57
+ def conflicting_touch_paths?(operations, touches)
58
+ targeted = operations.each_value.flat_map do |doc|
59
+ doc.respond_to?(:keys) ? doc.keys.map(&:to_s) : []
60
+ end
61
+
62
+ touches.each_key.any? do |touch_path|
63
+ path = touch_path.to_s
64
+ targeted.any? do |target|
65
+ path == target || path.start_with?("#{target}.") ||
66
+ target.start_with?("#{path}.")
67
+ end
68
+ end
69
+ end
70
+
71
+ # Rewrite the indices in the touch updates to the positional operator,
72
+ # as the final update will do to the merged operations. The touches of
73
+ # the parent chain target the inserted element, so rewriting them is
74
+ # safe, and merging the rewritten keys into the operations lets the
75
+ # final update reuse them as-is. A pending touch on a different element
76
+ # of the same array, however, would be rewritten to the same positional
77
+ # path and silently touch the wrong document; in that case this method
78
+ # returns nil and the caller persists the touch updates in their own
79
+ # round-trip after the insert instead of merging them.
80
+ #
81
+ # @api private
82
+ #
83
+ # @param [ Hash ] selector The update selector.
84
+ # @param [ Document ] parent The parent document being touched.
85
+ # @param [ Symbol, String, nil ] field The parent's custom touch field.
86
+ # @param [ Hash ] touches The touch updates to rewrite.
87
+ #
88
+ # @return [ Hash | nil ] The rewritten touch updates, or nil if any
89
+ # touch would be misdirected by the rewriting.
90
+ def rewritten_touch_updates(selector, parent, field, touches)
91
+ rewritten = positionally(selector, { '$set' => touches })['$set']
92
+
93
+ chain_paths = parent._touchable_chain_paths(field)
94
+ touches.each_key do |key|
95
+ path = key.to_s
96
+ next if rewritten.key?(path)
97
+
98
+ return nil unless chain_paths.include?(path)
99
+ end
100
+ rewritten
101
+ end
102
+
42
103
  # Insert the embedded document.
43
104
  #
44
105
  # When the parent association is touchable (which is the default for
45
- # +embedded_in+), the touch timestamp updates are merged into the
46
- # same +update_one+ call that performs the insert. This avoids a
47
- # second round-trip that the +after_save+ touch callback would
48
- # otherwise issue.
106
+ # +embedded_in+), the touch updates are merged into the same
107
+ # +update_one+ call that performs the insert. This avoids a second
108
+ # round-trip that the +after_save+ touch callback would otherwise
109
+ # issue. The merge is skipped when a touch path would conflict with a
110
+ # path the insert targets (see +conflicting_touch_paths?+) or when
111
+ # rewriting the touch indices to the positional operator would
112
+ # misdirect a touch (see +rewritten_touch_updates+); such touches are
113
+ # persisted in their own round-trip right after the insert, so their
114
+ # persistence does not depend on the callback chain running.
49
115
  #
50
116
  # @api private
51
117
  #
@@ -62,19 +128,59 @@ module Mongoid
62
128
  selector = _parent.atomic_selector
63
129
  operations = atomic_inserts
64
130
 
65
- if _touchable_parent?
66
- touches = _parent._gather_touch_updates(Time.current)
67
- if touches.present?
68
- operations['$set'] = (operations['$set'] || {}).merge(touches)
69
- Threaded.begin_touch_merged(self)
70
- end
131
+ deferred_touches = merge_touch_updates(selector, operations)
132
+
133
+ begin
134
+ _root.collection.find(selector).update_one(
135
+ positionally(selector, operations),
136
+ session: _session
137
+ )
138
+ _root.persist_atomic_operations('$set' => deferred_touches) if deferred_touches
139
+ rescue StandardError
140
+ # If the insert failed, the after_save callback will not run to
141
+ # consume and clear the merged-touch flag, so clear it here.
142
+ Threaded.exit_touch_merged(self)
143
+ raise
71
144
  end
145
+ end
146
+ end
147
+
148
+ # Merge the parent chain's pending touch updates into the insert
149
+ # operations when doing so would not produce a conflicting update
150
+ # (see +conflicting_touch_paths?+ and +rewritten_touch_updates+).
151
+ # Either way, marks the touch as merged so the after_save callback
152
+ # does not persist the updates a second time. Returns the touch
153
+ # updates that could not be merged; they are persisted in their own
154
+ # round-trip right after the insert, rather than relying on the
155
+ # after_save callback, so that an aborted callback chain cannot
156
+ # silently drop them.
157
+ #
158
+ # @api private
159
+ #
160
+ # @param [ Hash ] selector The update selector.
161
+ # @param [ Hash ] operations The atomic insert operations, modified
162
+ # in place when the touches are merged.
163
+ #
164
+ # @return [ Hash | nil ] The deferred touch updates, if any.
165
+ def merge_touch_updates(selector, operations)
166
+ return nil unless _touchable_parent?
72
167
 
73
- _root.collection.find(selector).update_one(
74
- positionally(selector, operations),
75
- session: _session
76
- )
168
+ field = _association&.inverse_association&.touch_field
169
+ touches = _parent._gather_touch_updates(Time.current, field)
170
+ return nil if touches.blank?
171
+
172
+ if conflicting_touch_paths?(operations, touches)
173
+ deferred_touches = touches
174
+ else
175
+ rewritten = rewritten_touch_updates(selector, _parent, field, touches)
176
+ if rewritten
177
+ operations['$set'] = (operations['$set'] || {}).merge(rewritten)
178
+ else
179
+ deferred_touches = touches
180
+ end
77
181
  end
182
+ Threaded.begin_touch_merged(self)
183
+ deferred_touches
78
184
  end
79
185
 
80
186
  # Insert the root document.
@@ -142,6 +142,21 @@ module Mongoid
142
142
  raise Errors::Callback.new(self.class, method)
143
143
  end
144
144
 
145
+ # Persist the atomic operations.
146
+ #
147
+ # @api private
148
+ #
149
+ # @example Persist the atomic operations.
150
+ # persist_atomic_operations(ops)
151
+ #
152
+ # @param [ Hash ] operations The atomic operations.
153
+ def persist_atomic_operations(operations)
154
+ return unless persisted? && operations && !operations.empty?
155
+
156
+ selector = atomic_selector
157
+ _root.collection.find(selector).update_one(positionally(selector, operations), session: _session)
158
+ end
159
+
145
160
  private
146
161
 
147
162
  # Are we executing an atomically block on the current document?
@@ -300,20 +315,5 @@ module Mongoid
300
315
  persist_atomic_operations(operation)
301
316
  end
302
317
  end
303
-
304
- # Persist the atomic operations.
305
- #
306
- # @api private
307
- #
308
- # @example Persist the atomic operations.
309
- # persist_atomic_operations(ops)
310
- #
311
- # @param [ Hash ] operations The atomic operations.
312
- def persist_atomic_operations(operations)
313
- return unless persisted? && operations && !operations.empty?
314
-
315
- selector = atomic_selector
316
- _root.collection.find(selector).update_one(positionally(selector, operations), session: _session)
317
- end
318
318
  end
319
319
  end