Class: Rhales::HydrationDataAggregator

Inherits:
Object
  • Object
show all
Includes:
Utils::LoggingHelpers
Defined in:
lib/rhales/hydration/hydration_data_aggregator.rb

Overview

HydrationDataAggregator traverses the ViewComposition and executes all sections to produce a single, merged JSON structure.

This class implements the server-side data aggregation phase of the two-pass rendering model, handling: - Traversal of the template dependency tree - Direct serialization of props for sections - Merge strategies (deep, shallow, strict) - Collision detection and error reporting

The aggregator replaces the HydrationRegistry by performing all data merging in a single, coordinated pass.

Defined Under Namespace

Classes: JSONSerializationError

Instance Method Summary collapse

Methods included from Utils::LoggingHelpers

#format_value, #log_timed_operation, #log_with_metadata

Methods included from Utils

#now, #now_in_μs, #pretty_path

Constructor Details

#initialize(context) ⇒ HydrationDataAggregator

Returns a new instance of HydrationDataAggregator.



27
28
29
30
31
32
33
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 27

def initialize(context)
  @context = context
  @window_attributes = {}
  @merged_data = {}
  @schema_cache = {}
  @schemas_dir = File.join(Dir.pwd, 'public/schemas')
end

Instance Method Details

#aggregate(composition) ⇒ Object

Aggregate all hydration data from the view composition



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 36

def aggregate(composition)
  log_timed_operation(Rhales.logger, :debug, 'Schema aggregation started',
    template_count: composition.template_names.size
  ) do
    composition.each_document_in_render_order do |template_name, parser|
      process_template(template_name, parser)
    end

    @merged_data
  end
end

#build_template_path_for_schema(parser) ⇒ Object (private)



381
382
383
384
385
386
387
388
389
390
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 381

def build_template_path_for_schema(parser)
  schema_node = parser.section_node('schema')
  line_number = schema_node ? schema_node.location.start_line : 1

  if parser.file_path
    "#{parser.file_path}:#{line_number}"
  else
    "<inline>:#{line_number}"
  end
end

#deep_merge(target, source) ⇒ Object (private)



335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 335

def deep_merge(target, source)
  result = target.dup

  source.each do |key, value|
    result[key] = if result.key?(key) && result[key].is_a?(Hash) && value.is_a?(Hash)
      deep_merge(result[key], value)
    else
      value
                  end
  end

  result
end

#empty_data?(data) ⇒ Boolean (private)

Check if data is considered empty for collision detection

Returns:

  • (Boolean)


393
394
395
396
397
398
399
400
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 393

def empty_data?(data)
  return true if data.nil?
  return true if data == {}
  return true if data == []
  return true if data.respond_to?(:empty?) && data.empty?

  false
end

#extract_expected_keys(template_name, schema_content) ⇒ Object (private)

Extract expected keys using hybrid approach

Tries to load pre-generated JSON schema first (reliable, handles all Zod patterns). Falls back to regex parsing for development (before schemas are generated).

To generate JSON schemas, run: rake rhales:schema:generate



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 408

def extract_expected_keys(template_name, schema_content)
  # Try JSON schema first (reliable, comprehensive)
  keys = extract_keys_from_json_schema(template_name)
  if keys&.any?
    (Rhales.logger, :debug, 'Schema keys extracted from JSON schema',
      template: template_name, key_count: keys.size, method: 'json_schema'
    )
    return keys
  end

  # Fall back to regex (development, before schemas generated)
  keys = extract_keys_from_zod_regex(schema_content)
  if keys.any?
    (Rhales.logger, :debug, 'Schema keys extracted from Zod regex',
      template: template_name, key_count: keys.size, method: 'regex_fallback',
      note: 'Run rake rhales:schema:generate for reliable validation'
    )
  end

  keys
end

#extract_keys_from_json_schema(template_name) ⇒ Object (private)

Extract keys from pre-generated JSON schema (preferred method)



431
432
433
434
435
436
437
438
439
440
441
442
443
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 431

def extract_keys_from_json_schema(template_name)
  schema = load_schema_cached(template_name)
  return nil unless schema

  # Extract all properties from JSON schema
  properties = schema.dig('properties') || {}
  properties.keys
rescue StandardError => ex
  (Rhales.logger, :debug, 'JSON schema loading failed',
    template: template_name, error: ex.message
  )
  nil
end

#extract_keys_from_zod_regex(schema_content) ⇒ Object (private)

Extract keys from Zod schema using regex (fallback method)

NOTE: This is a basic implementation that only matches simple patterns like: fieldName: z.string()

It will miss: - Nested object literals: settings: { theme: z.enum([…]) } - Complex compositions and unions - Multiline definitions

For reliable validation, generate JSON schemas with: rake rhales:schema:generate



471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 471

def extract_keys_from_zod_regex(schema_content)
  return [] unless schema_content

  keys = []
  schema_content.scan(/(\w+):\s*z\./) do |match|
    keys << match[0]
  end
  keys
rescue StandardError => ex
  (Rhales.logger, :debug, 'Regex key extraction failed',
    error: ex.message,
    schema_preview: schema_content[0..100]
  )
  []
end

#format_compact(template_path, window_attr, _expected, _actual, missing, extra, data_size) ⇒ Object (private)

Format: Single line compact (for production)



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 158

def format_compact(template_path, window_attr, _expected, _actual, missing, extra, data_size)
  parts = []
  parts << "#{missing.size} missing" if missing.any?
  parts << "#{extra.size} extra" if extra.any?

  summary = parts.join(', ')
   = {
    template: template_path,
    window_attribute: window_attr,
    missing_keys: missing,
    extra_keys: extra,
    client_data_size: data_size,
  }

  # Use existing metadata formatter
   = .map do |k, v|
    "#{k}=#{(v)}"
  end.join(' ')

  "Schema mismatch (#{summary}): #{}"
end

#format_json(template_path, window_attr, expected, actual, missing, extra, data_size) ⇒ Object (private)

Format: JSON (for structured logging systems)



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 181

def format_json(template_path, window_attr, expected, actual, missing, extra, data_size)
  require 'json'

  authority = Rhales.config.hydration_authority || :schema

  # Check if order changed
  order_changed = (expected.to_set == actual.to_set) && (expected != actual)
  moved_keys = if order_changed
    (expected & actual).select { |k| expected.index(k) != actual.index(k) }
  else
    []
  end

  data = {
    event: 'hydration_schema_mismatch',
    template: template_path,
    window_attribute: window_attr,
    authority: authority,
    schema: {
      expected_keys: expected,
      key_count: expected.size,
    },
    data: {
      actual_keys: actual,
      key_count: data_size,
    },
    diff: {
      missing_keys: missing,
      missing_count: missing.size,
      extra_keys: extra,
      extra_count: extra.size,
      order_changed: order_changed,
      moved_keys: moved_keys,
    },
  }

  JSON.generate(data)
end

#format_metadata_value(value) ⇒ Object (private)

Format values for compact metadata output



221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 221

def (value)
  case value
  when Array
    if value.empty?
      '[]'
    else
      "[#{value.join(', ')}]"
    end
  when String
    value.include?(' ') ? "\"#{value}\"" : value
  else
    value.to_s
  end
end

#format_multiline(template_path, window_attr, expected, actual, missing, extra, data_size) ⇒ Object (private)

Format: Multi-line with visual indicators (balanced)



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 123

def format_multiline(template_path, window_attr, expected, actual, missing, extra, data_size)
  # Check if order changed (same keys, different positions)
  order_changed = (expected.to_set == actual.to_set) && (expected != actual)

  # Find keys that moved position
  moved_keys = if order_changed
    (expected & actual).select do |k|
      expected.index(k) != actual.index(k)
    end
  else
    []
  end

  lines = []
  lines << 'Hydration schema mismatch'
  lines << "  Template: #{template_path}"
  lines << "  Window: #{window_attr}"
  lines << "  Data size: #{data_size}"

  if missing.any?
    lines << "  ✗ Schema expects (#{missing.size}): #{missing.join(', ')}"
  end

  if extra.any?
    lines << "  + Data provides (#{extra.size}): #{extra.join(', ')}"
  end

  if moved_keys.any?
    lines << "  ↔ Order changed (#{moved_keys.size}): #{moved_keys.join(', ')}"
  end

  lines.join("\n")
end

#format_sidebyside(template_path, window_attr, expected, actual, missing, extra, data_size) ⇒ Object (private)

Format: Side-by-side comparison (most visual, for development)



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 71

def format_sidebyside(template_path, window_attr, expected, actual, missing, extra, data_size)
  # Determine authority: schema (default) or data
  authority = Rhales.config.hydration_authority || :schema

  lines = []
  lines << 'Hydration schema mismatch'
  lines << "  Template: #{template_path}"
  lines << "  Window: #{window_attr} (#{data_size} keys)"
  lines << ''

  if authority == :schema
    # Schema is correct, data needs fixing
    lines << '  Schema (correct) │ Data (fix)'
    lines << '  ─────────────────┼────────────'

    # Show all expected keys with their status
    expected.each do |key|
      lines << if actual.include?(key)
        "  #{key.ljust(17)}│ ✓ #{key}"
      else
        "  #{key.ljust(17)}│ ✗ missing  ← add to data source"
               end
    end

    # Show extra keys that shouldn't be in data
    extra.each do |key|
      lines << "  (not in schema)  │ ✗ #{key}  ← remove from data source"
    end
  else
    # Data is correct, schema needs fixing
    lines << '  Schema (fix)     │ Data (correct)'
    lines << '  ─────────────────┼───────────────'

    # Show all actual keys with their status
    actual.each do |key|
      lines << if expected.include?(key)
        "  #{key.ljust(17)}│ ✓ #{key}"
      else
        "  [missing]        │ ✓ #{key}  ← add to schema"
               end
    end

    # Show keys in schema but not in data
    missing.each do |key|
      lines << "  #{key.ljust(17)}│ (not in data)  ← remove from schema"
    end
  end

  lines.join("\n")
end

#load_schema_cached(template_name) ⇒ Object (private)

Load and cache JSON schema from disk



446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 446

def load_schema_cached(template_name)
  @schema_cache[template_name] ||= begin
    schema_path = File.join(@schemas_dir, "#{template_name}.json")
    return nil unless File.exist?(schema_path)

    JSON.parse(File.read(schema_path))
  rescue JSON::ParserError, Errno::ENOENT => ex
    (Rhales.logger, :debug, 'Schema file error',
      template: template_name, path: schema_path, error: ex.class.name
    )
    nil
  end
end

#log_hydration_mismatch(template_path, window_attr, expected, actual, missing, extra, data_size) ⇒ Object (private)

Log hydration schema mismatch using configured format



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 51

def log_hydration_mismatch(template_path, window_attr, expected, actual, missing, extra, data_size)
  format = Rhales.config.hydration_mismatch_format || :compact

  formatter = case format
  when :sidebyside
    format_sidebyside(template_path, window_attr, expected, actual, missing, extra, data_size)
  when :multiline
    format_multiline(template_path, window_attr, expected, actual, missing, extra, data_size)
  when :compact
    format_compact(template_path, window_attr, expected, actual, missing, extra, data_size)
  when :json
    format_json(template_path, window_attr, expected, actual, missing, extra, data_size)
  else
    raise ArgumentError, "Unknown hydration_mismatch_format: #{format}. Valid: :compact, :multiline, :sidebyside, :json"
  end

  Rhales.logger.warn formatter
end

#merge_data(target, source, strategy, window_attr, template_path) ⇒ Object (private)



322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 322

def merge_data(target, source, strategy, window_attr, template_path)
  case strategy
  when 'deep'
    deep_merge(target, source)
  when 'shallow'
    shallow_merge(target, source, window_attr, template_path)
  when 'strict'
    strict_merge(target, source, window_attr, template_path)
  else
    raise ArgumentError, "Unknown merge strategy: #{strategy}"
  end
end

#process_schema_section(template_name, parser) ⇒ Object (private)

Process schema section: Direct JSON serialization



249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 249

def process_schema_section(template_name, parser)
  window_attr = parser.schema_window || 'data'
  merge_strategy = parser.schema_merge_strategy

  # Extract client data for validation
  client_data = @context.client || {}
  schema_content = parser.section('schema')
  expected_keys = extract_expected_keys(template_name, schema_content) if schema_content

  # Build template path for error reporting
  template_path = build_template_path_for_schema(parser)

  # Log schema validation details
  if expected_keys && expected_keys.any?
    actual_keys = client_data.keys.map(&:to_s)
    missing_keys = expected_keys - actual_keys
    extra_keys = actual_keys - expected_keys

    if missing_keys.any? || extra_keys.any?
      log_hydration_mismatch(
        Rhales.pretty_path(template_path),
        window_attr,
        expected_keys,
        actual_keys,
        missing_keys,
        extra_keys,
        client_data.size,
      )
    else
      (Rhales.logger, :debug, 'Schema validation passed',
        template: Rhales.pretty_path(template_path),
        window_attribute: window_attr,
        key_count: expected_keys.size,
        client_data_size: client_data.size
      )
    end
  end

  # Direct serialization of client data (no template interpolation)
  processed_data = @context.client

  # Check for collisions only if the data is not empty
  if @window_attributes.key?(window_attr) && merge_strategy.nil? && !empty_data?(processed_data)
    existing = @window_attributes[window_attr]
    existing_data = @merged_data[window_attr]

    # Only raise collision error if existing data is also not empty
    unless empty_data?(existing_data)
      raise ::Rhales::HydrationCollisionError.new(window_attr, existing[:path], template_path)
    end
  end

  # Merge or set the data
  @merged_data[window_attr] = if @merged_data.key?(window_attr)
    merge_data(
      @merged_data[window_attr],
      processed_data,
      merge_strategy || 'deep',
      window_attr,
      template_path,
    )
  else
    processed_data
                              end

  # Track the window attribute
  @window_attributes[window_attr] = {
    path: template_path,
    merge_strategy: merge_strategy,
    section_type: :schema,
  }
end

#process_template(template_name, parser) ⇒ Object (private)



236
237
238
239
240
241
242
243
244
245
246
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 236

def process_template(template_name, parser)
  # Process schema section
  if parser.schema_lang
    log_timed_operation(Rhales.logger, :debug, 'Schema validation',
      template: template_name,
      schema_lang: parser.schema_lang
    ) do
      process_schema_section(template_name, parser)
    end
  end
end

#shallow_merge(target, source, window_attr, template_path) ⇒ Object (private)



349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 349

def shallow_merge(target, source, window_attr, template_path)
  result = target.dup

  source.each do |key, value|
    if result.key?(key)
      raise ::Rhales::HydrationCollisionError.new(
        "#{window_attr}.#{key}",
        @window_attributes[window_attr][:path],
        template_path,
      )
    end
    result[key] = value
  end

  result
end

#strict_merge(target, source, window_attr, template_path) ⇒ Object (private)



366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/rhales/hydration/hydration_data_aggregator.rb', line 366

def strict_merge(target, source, window_attr, template_path)
  # In strict mode, any collision is an error
  target.each_key do |key|
    next unless source.key?(key)

    raise ::Rhales::HydrationCollisionError.new(
      "#{window_attr}.#{key}",
      @window_attributes[window_attr][:path],
      template_path,
    )
  end

  target.merge(source)
end