interfacets 0.9.99 → 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 (74) 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 -64
  5. data/lib/interfacets/client/bus.rb +28 -9
  6. data/lib/interfacets/client/channels/api.rb +138 -39
  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 +3 -2
  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 +7 -3
  20. data/lib/interfacets/client/utils/open_struct.rb +2 -4
  21. data/lib/interfacets/component_registry.rb +34 -29
  22. data/lib/interfacets/component_schema_parser.rb +8 -4
  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 -7
  26. data/lib/interfacets/server/assets.rb +58 -23
  27. data/lib/interfacets/server/basic_router.rb +29 -19
  28. data/lib/interfacets/server/bus.rb +5 -6
  29. data/lib/interfacets/server/registry.rb +17 -10
  30. data/lib/interfacets/shared/basic_routable.rb +7 -4
  31. data/lib/interfacets/shared/entities/bus.rb +619 -185
  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 +58 -37
  35. data/lib/interfacets/shared/entities/specs.rb +184 -18
  36. data/lib/interfacets/shared/entity.rb +113 -23
  37. data/lib/interfacets/shared/entity_dsl.rb +138 -20
  38. data/lib/interfacets/shared/facet.rb +128 -68
  39. data/lib/interfacets/shared/generated_store.rb +69 -34
  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 +746 -26
  43. data/lib/interfacets/shared/view.rb +74 -28
  44. data/lib/interfacets/test/component_registry.rb +31 -12
  45. data/lib/interfacets/test/js/inline_bus.rb +51 -25
  46. data/lib/interfacets/test/js/nodo_bus.rb +21 -10
  47. data/lib/interfacets/test/js/receivers/api.rb +14 -12
  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 +33 -5
  51. data/lib/interfacets/test/js/receivers/react/node.rb +69 -15
  52. data/lib/interfacets/test/js/receivers/react.rb +13 -4
  53. data/lib/interfacets/test/js/receivers/timer.rb +12 -8
  54. data/lib/interfacets/test/js/receivers/url.rb +47 -11
  55. data/lib/interfacets/test/ui_simulator.rb +88 -18
  56. data/lib/interfacets/test/validation_engine.rb +82 -49
  57. data/lib/interfacets/test.rb +1 -3
  58. data/lib/interfacets/version.rb +1 -1
  59. data/lib/interfacets.rb +11 -3
  60. metadata +31 -28
  61. data/.rubocop.yml +0 -180
  62. data/.tmp +0 -5
  63. data/LICENSE.txt +0 -21
  64. data/Rakefile +0 -14
  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/server/assets/facet.rb +0 -63
  71. data/lib/interfacets/server/config.rb +0 -87
  72. data/lib/interfacets/server/facets/deserializer.rb +0 -25
  73. data/lib/interfacets/server/facets/schema/serializer.rb +0 -54
  74. data/lib/interfacets/server/facets/serializer.rb +0 -50
@@ -1,230 +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
+ )
40
52
 
41
- def handle(event:)
42
- action = event.fetch("action")
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
43
80
 
44
- assert_valid_receiver(to: event.fetch("to"))
45
- assert_valid_action(
46
- action:,
47
- to: entity.role,
48
- nesting: event.fetch("nesting"),
49
- )
81
+ def handle(event:)
82
+ action = event.fetch("action")
83
+ nesting = self.class.validate_nesting!(event.fetch("nesting"))
50
84
 
51
- attributes = event.fetch("payload").fetch("attributes", {})
85
+ reply = !event["in_reply_to"].nil?
52
86
 
53
- merge(entity:, manifest:, attributes:, action:)
87
+ assert_valid_receiver(to: event.fetch("to"))
88
+ assert_valid_action(
89
+ action:,
90
+ to: entity.entity_role,
91
+ nesting:,
92
+ reply:
93
+ )
54
94
 
55
- target_entity = entity.entity_at(event.fetch("nesting"))
95
+ attributes = event.fetch("payload").fetch("attributes", {})
56
96
 
57
- target_entity
58
- &.class
59
- &.actions
60
- &.fetch(event.fetch("action"))
61
- &.dispatch(target_entity)
62
- end
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?
63
101
 
64
- private
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
+ )
65
110
 
66
- def serialize_attributes(manifest:, entity:, to:)
67
- return if entity.nil?
111
+ if (event["from"] == "server" || entity.entity_role.to_s == "client") && !patch
112
+ entity.checkpoint!
113
+ end
68
114
 
69
- data = {}
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
70
119
 
71
- data[:errors] = entity.errors.to_h if entity.respond_to?(:errors)
120
+ spec ||= target_entity.class.actions[action.to_s]&.then { reply ? _1.for_reply : _1 }
121
+ spec&.dispatch(target_entity)
72
122
 
73
- manifest
74
- .accessors
75
- .each do |name, spec|
76
- data[name] = entity.send(name)
77
- end
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
131
+ end
132
+
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
137
+
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
147
+
148
+ def serialize_attributes(manifest:, entity:, to:)
149
+ return if entity.nil?
150
+
151
+ data = {}
152
+
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
162
+
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
197
+
198
+ data
199
+ end
78
200
 
79
- manifest
80
- .associations
81
- .each do |name, spec|
82
- if spec.type == :reference
83
- data[name] = serialize_attributes(
84
- manifest: spec.klass,
85
- entity: entity.send(name),
86
- to:
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:
87
209
  )
88
- else
89
- data[name] = (entity.send(name) || []).map {
90
- serialize_attributes(
91
- manifest: spec.klass,
92
- entity: _1,
93
- to:
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:
223
+ )
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
94
242
  )
95
- }
243
+ Array(vs).each {
244
+ entity.errors.add(
245
+ attr_sym,
246
+ _1,
247
+ origin:,
248
+ value: val
249
+ )
250
+ }
251
+ end
96
252
  end
97
- end
98
253
 
99
- data
100
- 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
101
285
 
102
- def merge(manifest:, entity:, attributes:, action:)
103
- if (errs = attributes[:errors] || attributes["errors"])
104
- entity.errors.clear if entity.errors.respond_to?(:clear)
105
- errs.each do |k, vs|
106
- Array(vs).each { |v| entity.errors.add(k.to_sym, v) }
107
- end
108
- end
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
332
+
333
+ def merge_collections(manifest:, entity:, attributes:, action:, spec:)
334
+ patch = spec&.patch?
335
+
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
344
+
345
+ identifier = collection.identifier
346
+
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"
350
+
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
+ }
109
355
 
110
- manifest
111
- .accessors
112
- .values
113
- .select { _1.accepted_by?(entity.role) }
114
- .each do |attribute|
115
- next unless attributes.key?(attribute.name)
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
116
402
 
117
- attr_mergers = (
118
- entity.class.mergers[attribute.name]
119
- )
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
+ )
120
412
 
121
- merger = (
122
- if attr_mergers.key?(action)
123
- attr_mergers.fetch(action)
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
+ )
124
432
  else
125
- attr_mergers.fetch(:default)
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:
457
+ )
458
+ }
126
459
  end
127
- )
460
+ end
128
461
 
129
- merger.call(entity, attributes[attribute.name])
130
- end
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 } }
131
481
 
132
- manifest
133
- .associations
134
- .values
135
- .select { _1.type == :reference }
136
- .select { _1.accepted_by?(entity.role) }
137
- .each do |association|
138
- next unless attributes.key?(association.name)
139
-
140
- value = attributes.fetch(association.name)
141
-
142
- if value.nil?
143
- entity.association(association.name).set(nil)
144
- next
145
- end
146
-
147
- entity
148
- .association(association.name)
149
- .get
150
- .then { _1 || entity.association(association.name).build }
151
- .tap { |nested_entity|
152
- merge(
153
- entity: nested_entity,
154
- manifest: association.klass,
155
- attributes: value,
156
- action:
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)
157
490
  )
158
- }
159
- .then { entity.association(association.name).set(_1) }
160
- end
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)
506
+ else
507
+ result_items << unpersisted_item
508
+ end
509
+ end
510
+
511
+ result_items
512
+ end
513
+
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)
161
527
 
162
- manifest
163
- .associations
164
- .values
165
- .select { _1.type == :collection }
166
- .select { _1.accepted_by?(entity.role) }
167
- .each do |collection|
168
- next unless attributes.key?(collection.name)
528
+ existing_ids = persisted_existing.map { _1.send(identifier).to_s }
529
+ incoming_coll.each do |val|
530
+ next unless val.is_a?(Hash)
169
531
 
170
- identifier = collection.identifier
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
171
538
 
172
- incoming_coll = attributes.fetch(collection.name) || []
173
- existing_coll = entity.send(collection.name) || []
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
174
544
 
175
- items = (
176
- incoming_coll.map do |val|
177
- found_item = (
178
- val.fetch(identifier) &&
179
- existing_coll.find { _1.send(identifier) == val.fetch(identifier) }
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"
180
550
  )
551
+ )
552
+ end
181
553
 
182
- if found_item
183
- found_item.tap { |r|
184
- merge(
185
- entity: r,
186
- manifest: collection.klass,
187
- attributes: val,
188
- action:
189
- )
190
- }
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
191
595
  else
192
- entity
193
- .association(collection.name)
194
- .build
195
- .tap { |r|
196
- merge(
197
- entity: r,
198
- manifest: collection.klass,
199
- attributes: val,
200
- action:
201
- )
202
- }
596
+ raise_stale!(collection, id_val)
203
597
  end
204
598
  end
205
- )
206
- entity.association(collection.name).set(items)
207
- end
208
- end
599
+ end
209
600
 
210
- def assert_valid_action(action:, to:, nesting:)
211
- nested_manifest = manifest
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,
212
606
 
213
- nesting[1..-1].each do |assoc_name, _id|
214
- nested_manifest = manifest.associations.fetch(assoc_name).klass
215
- end
607
+ reply
608
+ )
216
609
 
217
- unless nested_manifest.actions[action]&.accepted_by?(to.to_s)
218
- raise InvalidAction.new("invalid action: #{action}")
219
- end
220
- end
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
221
651
 
222
- def assert_valid_receiver(to:)
223
- if to != entity.role
224
- raise InvalidReceiver.new("invalid receiver role: to: #{to}, entity: #{entity.role.inspect}")
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
225
662
  end
226
663
  end
227
664
  end
228
- end
229
- end
230
- end