interfacets 0.9.9 → 0.99999

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 (90) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +9 -17
  3. data/lib/interfacets/client/actor.rb +2 -1
  4. data/lib/interfacets/client/assets.rb +77 -63
  5. data/lib/interfacets/client/bus.rb +31 -8
  6. data/lib/interfacets/client/channels/api.rb +141 -35
  7. data/lib/interfacets/client/channels/audio.rb +13 -10
  8. data/lib/interfacets/client/channels/base.rb +2 -2
  9. data/lib/interfacets/client/channels/pubsub.rb +69 -0
  10. data/lib/interfacets/client/channels/react/builder.rb +42 -72
  11. data/lib/interfacets/client/channels/react/channel.rb +7 -5
  12. data/lib/interfacets/client/channels/react/evaluator.rb +6 -4
  13. data/lib/interfacets/client/channels/timer.rb +8 -7
  14. data/lib/interfacets/client/channels/url.rb +39 -6
  15. data/lib/interfacets/client/registry.rb +10 -70
  16. data/lib/interfacets/client/slots.rb +45 -0
  17. data/lib/interfacets/client/system.rb +20 -15
  18. data/lib/interfacets/client/template.rb +90 -0
  19. data/lib/interfacets/client/utils/mruby_patches.rb +8 -4
  20. data/lib/interfacets/client/utils/open_struct.rb +88 -77
  21. data/lib/interfacets/component_registry.rb +120 -0
  22. data/lib/interfacets/component_schema_parser.rb +88 -0
  23. data/lib/interfacets/mruby/build_config.rb +8 -4
  24. data/lib/interfacets/mruby/entrypoint.rb +2 -2
  25. data/lib/interfacets/server/api.rb +44 -27
  26. data/lib/interfacets/server/assets.rb +69 -28
  27. data/lib/interfacets/server/basic_router.rb +38 -23
  28. data/lib/interfacets/server/bus.rb +8 -14
  29. data/lib/interfacets/server/registry.rb +31 -185
  30. data/lib/interfacets/shared/basic_routable.rb +48 -0
  31. data/lib/interfacets/shared/entities/bus.rb +623 -177
  32. data/lib/interfacets/shared/entities/changeset.rb +432 -0
  33. data/lib/interfacets/shared/entities/collection_proxy.rb +132 -72
  34. data/lib/interfacets/shared/entities/specs/handlers.rb +74 -37
  35. data/lib/interfacets/shared/entities/specs.rb +223 -20
  36. data/lib/interfacets/shared/entity.rb +124 -110
  37. data/lib/interfacets/shared/entity_dsl.rb +272 -0
  38. data/lib/interfacets/shared/facet.rb +260 -0
  39. data/lib/interfacets/shared/generated_store.rb +74 -35
  40. data/lib/interfacets/shared/refreshable.rb +85 -0
  41. data/lib/interfacets/shared/utils.rb +36 -32
  42. data/lib/interfacets/shared/validations.rb +749 -25
  43. data/lib/interfacets/shared/view.rb +120 -0
  44. data/lib/interfacets/test/component_registry.rb +82 -0
  45. data/lib/interfacets/test/js/inline_bus.rb +68 -33
  46. data/lib/interfacets/test/js/nodo_bus.rb +37 -9
  47. data/lib/interfacets/test/js/receivers/api.rb +17 -4
  48. data/lib/interfacets/test/js/receivers/audio.rb +61 -0
  49. data/lib/interfacets/test/js/receivers/pubsub.rb +50 -0
  50. data/lib/interfacets/test/js/receivers/react/node/xml_parser.rb +103 -0
  51. data/lib/interfacets/test/js/receivers/react/node.rb +91 -71
  52. data/lib/interfacets/test/js/receivers/react.rb +15 -5
  53. data/lib/interfacets/test/js/receivers/timer.rb +81 -0
  54. data/lib/interfacets/test/js/receivers/url.rb +51 -10
  55. data/lib/interfacets/test/standard_elements.yml +173 -0
  56. data/lib/interfacets/test/ui_simulator.rb +145 -0
  57. data/lib/interfacets/test/validation_engine.rb +184 -0
  58. data/lib/interfacets/test.rb +1 -7
  59. data/lib/interfacets/version.rb +1 -1
  60. data/lib/interfacets.rb +13 -2
  61. metadata +51 -37
  62. data/.rubocop.yml +0 -180
  63. data/LICENSE.txt +0 -21
  64. data/Rakefile +0 -10
  65. data/lib/interfacets/client/channels/page_visibility.rb +0 -21
  66. data/lib/interfacets/client/channels/react/dom.rb +0 -91
  67. data/lib/interfacets/client/channels/speech_to_text.rb +0 -100
  68. data/lib/interfacets/client/config.rb +0 -22
  69. data/lib/interfacets/client/delegator.rb +0 -37
  70. data/lib/interfacets/client/facet.rb +0 -26
  71. data/lib/interfacets/client/facet2.rb +0 -15
  72. data/lib/interfacets/client/facets/attributes/accessor.rb +0 -28
  73. data/lib/interfacets/client/facets/attributes/association.rb +0 -50
  74. data/lib/interfacets/client/facets/attributes/bind.rb +0 -25
  75. data/lib/interfacets/client/facets/attributes/collection.rb +0 -47
  76. data/lib/interfacets/client/facets/attributes/readonly.rb +0 -19
  77. data/lib/interfacets/client/facets/deserializer.rb +0 -30
  78. data/lib/interfacets/client/facets/schema/deserializer.rb +0 -63
  79. data/lib/interfacets/client/facets/schema.rb +0 -63
  80. data/lib/interfacets/client/facets/serializer.rb +0 -18
  81. data/lib/interfacets/client/view.rb +0 -47
  82. data/lib/interfacets/server/assets/facet.rb +0 -61
  83. data/lib/interfacets/server/basic_routable.rb +0 -40
  84. data/lib/interfacets/server/config.rb +0 -87
  85. data/lib/interfacets/server/facet.rb +0 -51
  86. data/lib/interfacets/server/facets/deserializer.rb +0 -25
  87. data/lib/interfacets/server/facets/schema/serializer.rb +0 -54
  88. data/lib/interfacets/server/facets/serializer.rb +0 -50
  89. data/lib/interfacets/shared/entity_collection.rb +0 -88
  90. data/lib/interfacets/test/browser.rb +0 -63
@@ -1,218 +1,664 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Interfacets
4
- module Shared
5
- module Entities
6
- class Bus
7
- InvalidAction = Class.new(StandardError)
8
- InvalidReceiver = Class.new(StandardError)
9
-
10
- # event schema:
11
- # {
12
- # from: (role),
13
- # to: (role),
14
- # action:,
15
- # payload: {
16
-
17
- # }
18
- # }
19
-
20
- attr_reader :manifest, :entity
21
- def initialize(entity:)
22
- @manifest = entity.class.manifest
23
- @entity = entity
24
- end
4
+ module Shared
5
+ module Entities
6
+ class StaleObjectError < StandardError; end
7
+
8
+ class Bus
9
+ StaleObjectError = Interfacets::Shared::Entities::StaleObjectError
10
+ InvalidAction = Class.new(StandardError)
11
+ InvalidReceiver = Class.new(StandardError)
12
+
13
+ # event schema:
14
+ # {
15
+ # from: (role),
16
+ # to: (role),
17
+ # action:,
18
+ # payload: {
19
+ # }
20
+ # }
21
+
22
+ attr_reader(:manifest, :entity)
23
+ def initialize(entity:)
24
+ @manifest = entity.class.manifest
25
+ @entity = entity
26
+ end
25
27
 
26
- def serialize(to:, action:, nesting:)
27
- assert_valid_action(action:, to:, nesting:)
28
-
29
- {
30
- id: SecureRandom.uuid,
31
- from: entity.role,
32
- to: to,
33
- nesting:,
34
- action:,
35
- payload: {
36
- attributes: serialize_attributes(manifest:, entity:, to:)
37
- }
38
- }
39
- end
28
+ # `root_id` identifies the root entity instance on the client. A request carries
29
+ # the client's id and the reply echoes it back; without one the entity's own id is used.
30
+ def serialize(to:, action:, nesting:, in_reply_to: nil, root_id: nil)
31
+ reply = !in_reply_to.nil?
32
+ assert_valid_action(action:, to:, nesting:, reply:)
33
+
34
+ spec = spec_for(action, nesting)
35
+ spec = spec.for_reply if reply && spec
36
+
37
+ # Patch-like events describe the entity at the nesting; everything else
38
+ # describes the whole root.
39
+ target = (spec&.patch? && nesting.is_a?(Array) && entity.entity_at(nesting)) || entity
40
+
41
+ attributes = (
42
+ if spec&.stateless?
43
+ { "internal_entity_id" => entity.internal_entity_id }
44
+ else
45
+ serialize_attributes(
46
+ manifest: manifest_for(target),
47
+ entity: target,
48
+ to:
49
+ )
50
+ end
51
+ )
52
+
53
+ {
54
+ id: SecureRandom.uuid,
55
+ from: entity.entity_role,
56
+ to: to,
57
+ nesting:,
58
+ root_id: root_id || entity.internal_entity_id,
59
+ action:,
60
+ in_reply_to:,
61
+ payload: {
62
+ attributes:
63
+ }
64
+ }.compact
65
+ end
66
+
67
+ # Canonical nesting: ["root"] or ["root", [assoc, id], ...]
68
+ def self.validate_nesting!(nesting)
69
+ valid = nesting.is_a?(Array) &&
70
+ nesting.first == "root" &&
71
+ nesting.drop(1).all? { |seg| seg.is_a?(Array) && seg.size == 2 }
72
+ return nesting if valid
73
+
74
+ raise(
75
+ ArgumentError.new(
76
+ "malformed nesting #{nesting.inspect}: expected [\"root\", [assoc, id], ...]"
77
+ )
78
+ )
79
+ end
80
+
81
+ def handle(event:)
82
+ action = event.fetch("action")
83
+ nesting = self.class.validate_nesting!(event.fetch("nesting"))
84
+
85
+ reply = !event["in_reply_to"].nil?
86
+
87
+ assert_valid_receiver(to: event.fetch("to"))
88
+ assert_valid_action(
89
+ action:,
90
+ to: entity.entity_role,
91
+ nesting:,
92
+ reply:
93
+ )
94
+
95
+ attributes = event.fetch("payload").fetch("attributes", {})
40
96
 
41
- def handle(event:)
42
- assert_valid_receiver(to: event.fetch("to"))
43
- assert_valid_action(
44
- action: event.fetch("action"),
45
- to: entity.role,
46
- nesting: event.fetch("nesting"),
47
- )
97
+ target_entity = entity.entity_at(nesting)
98
+ spec = (target_entity || entity).class.actions[action.to_s]
99
+ spec = spec.for_reply if reply && spec
100
+ patch = spec&.patch?
48
101
 
49
- attributes = event.fetch("payload").fetch("attributes", {})
102
+ merge_target = (patch && target_entity) || entity
103
+ merge(
104
+ entity: merge_target,
105
+ manifest: manifest_for(merge_target),
106
+ attributes:,
107
+ action:,
108
+ spec:,
109
+ )
50
110
 
51
- merge(entity:, manifest:, attributes:)
111
+ if (event["from"] == "server" || entity.entity_role.to_s == "client") && !patch
112
+ entity.checkpoint!
113
+ end
52
114
 
53
- target_entity = entity
54
- event.fetch("nesting")[1..-1].each do |assoc_name, id|
55
- break if target_entity.nil?
115
+ # Merging can create the target (e.g. a new collection item), so resolve it
116
+ # again if we could not before.
117
+ target_entity ||= entity.entity_at(nesting)
118
+ return unless target_entity
56
119
 
57
- spec = entity.association(assoc_name)
120
+ spec ||= target_entity.class.actions[action.to_s]&.then { reply ? _1.for_reply : _1 }
121
+ spec&.dispatch(target_entity)
58
122
 
59
- target_entity =(
60
- if spec.type == :reference
61
- target_entity = spec.get
62
- else
63
- spec.get.find { _1.internal_entity_id == id }
123
+ spec&.invalidates&.each do |target|
124
+ case target
125
+ when :parent
126
+ target_entity.parent&.invalidate!
127
+ when :root
128
+ target_entity.root&.invalidate!
129
+ end
130
+ end
64
131
  end
65
- )
66
- end
67
132
 
68
- raise "No EntityError" if target_entity.nil?
133
+ def spec_for(action, nesting)
134
+ target = (nesting.is_a?(Array) && entity.entity_at(nesting)) || entity
135
+ target.class.actions[action.to_s]
136
+ end
69
137
 
70
- target_entity
71
- .class
72
- .actions
73
- .fetch(event.fetch("action"))
74
- .dispatch(target_entity)
75
- end
138
+ def manifest_for(target)
139
+ if target.class.respond_to?(:manifest) && target.class.manifest
140
+ target.class.manifest
141
+ elsif target.class.respond_to?(:accessors)
142
+ target.class
143
+ else
144
+ manifest
145
+ end
146
+ end
76
147
 
77
- private
148
+ def serialize_attributes(manifest:, entity:, to:)
149
+ return if entity.nil?
78
150
 
79
- def serialize_attributes(manifest:, entity:, to:)
80
- return if entity.nil?
151
+ data = {}
81
152
 
82
- data = {}
153
+ if entity.respond_to?(:errors)
154
+ data[:errors] = (
155
+ if entity.errors.respond_to?(:to_h)
156
+ entity.errors.to_h
157
+ else
158
+ entity.errors.to_hash
159
+ end
160
+ )
161
+ end
83
162
 
84
- manifest
85
- .accessors
86
- .each do |name, spec|
87
- data[name] = entity.send(name)
88
- end
163
+ manifest
164
+ .accessors
165
+ .each do |name, spec|
166
+ data[name] = entity.send(name)
167
+ end
168
+
169
+ manifest
170
+ .associations
171
+ .each do |name, spec|
172
+ if spec.type == :reference
173
+ child = entity.send(name)
174
+ child_manifest = (
175
+ child && spec.respond_to?(:klass_for) && child.respond_to?(:store) &&
176
+ spec.klass_for(child.store)
177
+ ) || spec.klass
178
+ data[name] = serialize_attributes(
179
+ manifest: child_manifest,
180
+ entity: child,
181
+ to:
182
+ )
183
+ else
184
+ data[name] = (entity.send(name) || []).map { |child|
185
+ child_manifest = (
186
+ child && spec.respond_to?(:klass_for) && child.respond_to?(:store) &&
187
+ spec.klass_for(child.store)
188
+ ) || spec.klass
189
+ serialize_attributes(
190
+ manifest: child_manifest,
191
+ entity: child,
192
+ to:
193
+ )
194
+ }
195
+ end
196
+ end
89
197
 
90
- manifest
91
- .associations
92
- .each do |name, spec|
93
- if spec.type == :reference
94
- data[name] = serialize_attributes(
95
- manifest: spec.klass,
96
- entity: entity.send(name),
97
- to:
198
+ data
199
+ end
200
+
201
+ def merge(manifest:, entity:, attributes:, action:, spec:)
202
+ merge_errors(entity:, attributes:)
203
+ merge_accessors(
204
+ manifest:,
205
+ entity:,
206
+ attributes:,
207
+ action:,
208
+ spec:
209
+ )
210
+ merge_references(
211
+ manifest:,
212
+ entity:,
213
+ attributes:,
214
+ action:,
215
+ spec:
216
+ )
217
+ merge_collections(
218
+ manifest:,
219
+ entity:,
220
+ attributes:,
221
+ action:,
222
+ spec:
98
223
  )
99
- else
100
- data[name] = (entity.send(name) || []).map {
101
- serialize_attributes(
102
- manifest: spec.klass,
103
- entity: _1,
104
- to:
224
+ end
225
+
226
+ def merge_errors(entity:, attributes:)
227
+ errs = attributes[:errors] || attributes["errors"]
228
+ return unless errs
229
+
230
+ entity.errors.clear if entity.errors.respond_to?(:clear)
231
+ origin = entity.entity_role.to_s == "client" ? :server : :client
232
+ errs.each do |k, vs|
233
+ attr_sym = k.to_sym
234
+ val = (
235
+ if attributes.key?(k)
236
+ attributes[k]
237
+ elsif attributes.key?(attr_sym)
238
+ attributes[attr_sym]
239
+ elsif entity.respond_to?(attr_sym)
240
+ entity.send(attr_sym)
241
+ end
105
242
  )
106
- }
243
+ Array(vs).each {
244
+ entity.errors.add(
245
+ attr_sym,
246
+ _1,
247
+ origin:,
248
+ value: val
249
+ )
250
+ }
251
+ end
107
252
  end
108
- end
109
253
 
110
- data
111
- end
254
+ def merge_accessors(manifest:, entity:, attributes:, action:, spec:)
255
+ patch = spec&.patch?
256
+ events = spec ? spec.merge_events : [action.to_s, action.to_s.to_sym]
257
+
258
+ manifest
259
+ .accessors
260
+ .values
261
+ .select { _1.accepted_by?(entity.entity_role) }
262
+ .each do |attribute|
263
+ attr_key = key_in(attributes, attribute.name)
264
+ next unless attr_key
265
+
266
+ attr_val = attributes[attr_key]
267
+ attr_mergers = entity.class.mergers[attribute.name]
268
+ merger = (
269
+ events
270
+ .map { attr_mergers[_1] }
271
+ .compact
272
+ .first || attr_mergers[:default] || attr_mergers["default"]
273
+ )
274
+
275
+ merger.call(entity, attr_val)
276
+
277
+ if patch && entity.respond_to?(:changeset)
278
+ current_val = entity.respond_to?(attribute.name) ? entity.send(attribute.name) : nil
279
+ if current_val == attr_val && entity.changeset.respond_to?(:checkpoint_accessor!)
280
+ entity.changeset.checkpoint_accessor!(attribute.name, current_val)
281
+ end
282
+ end
283
+ end
284
+ end
112
285
 
113
- def merge(manifest:, entity:, attributes:)
114
- manifest
115
- .accessors
116
- .values
117
- .select { _1.accepted_by?(entity.role) }
118
- .each do |attribute|
119
- next unless attributes.key?(attribute.name)
286
+ def merge_references(manifest:, entity:, attributes:, action:, spec:)
287
+ manifest
288
+ .associations
289
+ .values
290
+ .select { _1.type == :reference }
291
+ .select { _1.accepted_by?(entity.entity_role) }
292
+ .each do |association|
293
+ assoc_key = key_in(attributes, association.name)
294
+ next unless assoc_key
295
+
296
+ value = attributes.fetch(assoc_key)
297
+
298
+ if value.nil?
299
+ entity.association(association.name).set(nil)
300
+ next
301
+ end
302
+
303
+ handler = entity.association(association.name)
304
+ identifier = association.identifier
305
+ incoming_id_key = [identifier, identifier.to_sym].find { value.key?(_1) }
306
+
307
+ handler
308
+ .get
309
+ .then { |existing|
310
+ # A different incoming id means a different record: build a
311
+ # replacement instead of overwriting the id of the existing one.
312
+ replace = existing && incoming_id_key &&
313
+ association
314
+ .klass
315
+ .accessors
316
+ .key?(identifier) &&
317
+ existing.send(identifier).to_s != value[incoming_id_key].to_s
318
+ replace ? handler.build : (existing || handler.build)
319
+ }
320
+ .tap { |nested_entity|
321
+ merge(
322
+ entity: nested_entity,
323
+ manifest: association.klass,
324
+ attributes: value,
325
+ action:,
326
+ spec:
327
+ )
328
+ }
329
+ .then { entity.association(association.name).set(_1) }
330
+ end
331
+ end
120
332
 
121
- entity.send("#{attribute.name}=", attributes[attribute.name])
122
- end
333
+ def merge_collections(manifest:, entity:, attributes:, action:, spec:)
334
+ patch = spec&.patch?
123
335
 
124
- manifest
125
- .associations
126
- .values
127
- .select { _1.type == :reference }
128
- .select { _1.accepted_by?(entity.role) }
129
- .each do |association|
130
- next unless attributes.key?(association.name)
131
-
132
- value = attributes.fetch(association.name)
133
-
134
- if value.nil?
135
- entity.association(association.name).set(nil)
136
- next
137
- end
138
-
139
- entity
140
- .association(association.name)
141
- .get
142
- .then { _1 || entity.association(association.name).build }
143
- .tap {
144
- merge(
145
- entity: _1,
146
- manifest: association.klass,
147
- attributes: value
148
- )
149
- }
150
- .then { entity.association(association.name).set(_1) }
151
- end
336
+ manifest
337
+ .associations
338
+ .values
339
+ .select { _1.type == :collection }
340
+ .select { _1.accepted_by?(entity.entity_role) }
341
+ .each do |collection|
342
+ coll_key = key_in(attributes, collection.name)
343
+ next unless coll_key
152
344
 
153
- manifest
154
- .associations
155
- .values
156
- .select { _1.type == :collection }
157
- .select { _1.accepted_by?(entity.role) }
158
- .each do |collection|
159
- next unless attributes.key?(collection.name)
345
+ identifier = collection.identifier
160
346
 
161
- identifier = collection.identifier
347
+ incoming_coll = attributes.fetch(coll_key) || []
348
+ existing_coll = (entity.send(collection.name) || []).to_a
349
+ is_client = entity.entity_role.to_s == "client"
162
350
 
163
- incoming_coll = attributes.fetch(collection.name) || []
164
- existing_coll = entity.send(collection.name) || []
351
+ persisted_existing, unpersisted_existing = existing_coll.partition { |item|
352
+ id_val = item.send(identifier) if item.respond_to?(identifier)
353
+ !id_val.nil? && !id_val.to_s.empty?
354
+ }
165
355
 
166
- items = (
167
- incoming_coll.map do |val|
168
- found_item = (
169
- val.fetch(identifier) &&
170
- existing_coll.find { _1.send(identifier) == val.fetch(identifier) }
171
- )
356
+ incoming_coll.each do |val|
357
+ next if val.is_a?(Hash)
358
+
359
+ raise(
360
+ InvalidAction.new(
361
+ "invalid item in collection '#{collection.name}': " \
362
+ "expected a Hash, got #{val.class}"
363
+ )
364
+ )
365
+ end
366
+
367
+ if !is_client && !patch
368
+ reject_stale_items!(
369
+ collection:,
370
+ incoming_coll:,
371
+ persisted_existing:,
372
+ identifier:
373
+ )
374
+ end
375
+
376
+ items = incoming_coll.map {
377
+ merge_collection_item(
378
+ collection:,
379
+ val: _1,
380
+ entity:,
381
+ action:,
382
+ spec:,
383
+ persisted_existing:,
384
+ is_client:,
385
+ patch:
386
+ )
387
+ }
388
+
389
+ if patch && unpersisted_existing.any?
390
+ result_items = reinsert_unpersisted(
391
+ items.compact,
392
+ existing_coll,
393
+
394
+ unpersisted_existing
395
+ )
396
+ entity.association(collection.name).set(result_items)
397
+ else
398
+ entity.association(collection.name).set(items.compact)
399
+ end
400
+ end
401
+ end
402
+
403
+ def merge_collection_item(collection:, val:, entity:, action:, spec:, persisted_existing:,
404
+ is_client:, patch:)
405
+ identifier = collection.identifier
406
+ id_val = val[identifier] || val[identifier.to_s] || val[identifier.to_sym]
407
+ id_present = !id_val.nil? && !id_val.to_s.empty?
408
+ found_item = (
409
+ id_present &&
410
+ persisted_existing.find { _1.send(identifier).to_s == id_val.to_s }
411
+ )
172
412
 
173
- if found_item
174
- found_item.tap { |r|
175
- merge(
176
- entity: r,
177
- manifest: collection.klass,
178
- attributes: val
413
+ if found_item
414
+ found_item.tap {
415
+ merge_item(
416
+ collection:,
417
+ item: _1,
418
+ val:,
419
+ action:,
420
+ spec:
421
+ )
422
+ }
423
+ elsif !is_client && id_present && !patch
424
+ handle_missing_item(
425
+ collection:,
426
+ id_val:,
427
+ val:,
428
+ entity:,
429
+ action:,
430
+ spec:
431
+ )
432
+ else
433
+ child_manifest = (
434
+ collection.respond_to?(:klass_for) && collection.klass_for(val)
435
+ ) || collection.klass
436
+ assoc_keys = (
437
+ if child_manifest.respond_to?(:associations)
438
+ child_manifest
439
+ .associations
440
+ .keys
441
+ .flat_map { [_1.to_sym, _1.to_s] }
442
+ else
443
+ []
444
+ end
445
+ )
446
+ attrs = val.except(*assoc_keys).transform_keys(&:to_sym)
447
+ entity
448
+ .association(collection.name)
449
+ .build(**attrs)
450
+ .tap {
451
+ merge_item(
452
+ collection:,
453
+ item: _1,
454
+ val:,
455
+ action:,
456
+ spec:
179
457
  )
180
458
  }
459
+ end
460
+ end
461
+
462
+ def merge_item(collection:, item:, val:, action:, spec:)
463
+ item_manifest = (
464
+ item.respond_to?(:store) && collection.respond_to?(:klass_for) &&
465
+ collection.klass_for(item.store)
466
+ ) || collection.klass
467
+ merge(
468
+ entity: item,
469
+ manifest: item_manifest,
470
+ attributes: val,
471
+ action:,
472
+ spec:
473
+ )
474
+ end
475
+
476
+ # Keeps unsaved local items where the user left them, next to the
477
+ # nearest neighbour that survived the patch.
478
+ def reinsert_unpersisted(reconciled_items, existing_coll, unpersisted_existing)
479
+ result_items = reconciled_items.dup
480
+ surviving = ->(e) { result_items.any? { _1.internal_entity_id == e.internal_entity_id } }
481
+
482
+ unpersisted_existing.each do |unpersisted_item|
483
+ orig_idx = existing_coll.index(unpersisted_item)
484
+
485
+ prev_item = (
486
+ existing_coll
487
+ .slice(0, orig_idx)
488
+ .reverse
489
+ .find(&surviving)
490
+ )
491
+ next_item = existing_coll.slice(
492
+ orig_idx + 1,
493
+ existing_coll.size
494
+ ).find(&surviving)
495
+
496
+ if prev_item
497
+ prev_idx = result_items.index {
498
+ _1.internal_entity_id == prev_item.internal_entity_id
499
+ }
500
+ result_items.insert(prev_idx + 1, unpersisted_item)
501
+ elsif next_item
502
+ next_idx = result_items.index {
503
+ _1.internal_entity_id == next_item.internal_entity_id
504
+ }
505
+ result_items.insert(next_idx, unpersisted_item)
181
506
  else
182
- entity
183
- .association(collection.name)
184
- .build
185
- .tap { |r|
186
- merge(
187
- entity: r,
188
- manifest: collection.klass,
189
- attributes: val
190
- )
191
- }
507
+ result_items << unpersisted_item
192
508
  end
193
509
  end
194
- )
195
- entity.association(collection.name).set(items)
196
- end
197
- end
198
510
 
199
- def assert_valid_action(action:, to:, nesting:)
200
- nested_manifest = manifest
201
- nesting[1..-1].each do |assoc_name, _id|
202
- nested_manifest = manifest.associations.fetch(assoc_name).klass
203
- end
511
+ result_items
512
+ end
204
513
 
205
- unless nested_manifest.actions[action]&.accepted_by?(to.to_s)
206
- raise InvalidAction.new("invalid action: #{action}")
207
- end
208
- end
514
+ def key_in(attributes, name)
515
+ if attributes.key?(name)
516
+ name
517
+ elsif attributes.key?(name.to_sym)
518
+ name.to_sym
519
+ end
520
+ end
521
+
522
+ # Raises for a stale item before any item of the collection is merged, so a
523
+ # failed save leaves the collection's records untouched. Only the built-in
524
+ # raising policy can be decided up front; callables still run per item.
525
+ def reject_stale_items!(collection:, incoming_coll:, persisted_existing:, identifier:)
526
+ return unless raises_on_missing?(collection)
527
+
528
+ existing_ids = persisted_existing.map { _1.send(identifier).to_s }
529
+ incoming_coll.each do |val|
530
+ next unless val.is_a?(Hash)
209
531
 
210
- def assert_valid_receiver(to:)
211
- if to != entity.role
212
- raise InvalidReceiver.new("invalid receiver role: to: #{to}, entity: #{entity.role.inspect}")
532
+ id_val = val[identifier] || val[identifier.to_s] || val[identifier.to_sym]
533
+ next if id_val.nil? || id_val.to_s.empty? || existing_ids.include?(id_val.to_s)
534
+
535
+ raise_stale!(collection, id_val)
536
+ end
537
+ end
538
+
539
+ def raises_on_missing?(collection)
540
+ handler = collection.respond_to?(:on_missing) ? collection.on_missing : :raise
541
+ handler.nil? || handler == :raise || !(%i[drop ignore omit
542
+ prune].include?(handler) || handler.respond_to?(:call))
543
+ end
544
+
545
+ def raise_stale!(collection, id_val)
546
+ raise(
547
+ StaleObjectError.new(
548
+ "Stale object in collection '#{collection.name}' with id '#{id_val}' " \
549
+ "not found on server"
550
+ )
551
+ )
552
+ end
553
+
554
+ def handle_missing_item(collection:, id_val:, val:, entity:, action:, spec:)
555
+ handler = collection.respond_to?(:on_missing) ? collection.on_missing : :raise
556
+ handler = :raise if handler.nil?
557
+
558
+ case handler
559
+ when :raise
560
+ raise_stale!(collection, id_val)
561
+ when :drop, :ignore, :omit, :prune
562
+ nil
563
+ else
564
+ if handler.respond_to?(:call)
565
+ result = (
566
+ if handler.arity >= 0
567
+ args = [id_val, val, collection, entity].take(handler.arity)
568
+ handler.call(*args)
569
+ else
570
+ handler.call(
571
+ id_val,
572
+ val,
573
+ collection,
574
+ entity
575
+ )
576
+ end
577
+ )
578
+
579
+ # The handler returns a record (or the result of `association.build`).
580
+ # The framework wraps it, so user code never has to construct entities.
581
+ return nil if result.nil? || result == :drop
582
+
583
+ item = entity.association(collection.name).wrap(result)
584
+ item_manifest = (
585
+ collection.respond_to?(:klass_for) && collection.klass_for(item.store)
586
+ ) || collection.klass
587
+ merge(
588
+ entity: item,
589
+ manifest: item_manifest,
590
+ attributes: val,
591
+ action:,
592
+ spec:
593
+ )
594
+ item
595
+ else
596
+ raise_stale!(collection, id_val)
597
+ end
598
+ end
599
+ end
600
+
601
+ def assert_valid_action(action:, to:, nesting:, reply: false)
602
+ target_entity = nesting.is_a?(Array) ? entity.entity_at(nesting) : entity
603
+ return if target_entity && accepts_action?(
604
+ target_entity.class.actions[action.to_s],
605
+ to,
606
+
607
+ reply
608
+ )
609
+
610
+ current_manifests = [manifest]
611
+
612
+ nesting_chain = Array(nesting)[1..-1] || []
613
+ nesting_chain.each do |assoc_name, _id|
614
+ next_manifests = []
615
+ current_manifests.each do |m|
616
+ assoc = m.associations[assoc_name]
617
+ next unless assoc
618
+
619
+ if assoc.respond_to?(:klasses) && assoc.klasses
620
+ next_manifests.concat(assoc.klasses.values)
621
+ elsif assoc.klass
622
+ next_manifests << assoc.klass
623
+ end
624
+ end
625
+ current_manifests = next_manifests
626
+ break if current_manifests.empty?
627
+ end
628
+
629
+ valid = current_manifests.any? {
630
+ accepts_action?(
631
+ _1.actions[action.to_s],
632
+ to,
633
+ reply
634
+ )
635
+ }
636
+
637
+ raise(
638
+ InvalidAction.new("invalid action: #{action}")
639
+ ) unless valid
640
+ end
641
+
642
+ def accepts_action?(spec, to, reply)
643
+ return false unless spec
644
+
645
+ if reply
646
+ spec.replies? && spec.for_reply.accepted_by?(to.to_s)
647
+ else
648
+ spec.accepted_by?(to.to_s)
649
+ end
650
+ end
651
+
652
+ def assert_valid_receiver(to:)
653
+ if to.to_s != entity.entity_role.to_s
654
+ raise(
655
+ InvalidReceiver.new(
656
+ "invalid receiver role: to: #{to}, entity: #{entity.entity_role.inspect}"
657
+ )
658
+ )
659
+ end
660
+ end
661
+ end
213
662
  end
214
663
  end
215
664
  end
216
- end
217
- end
218
- end