Class: Synthra::Behaviors::Latency

Inherits:
Base
  • Object
show all
Defined in:
lib/synthra/behaviors/latency.rb

Overview

Latency behavior - adds configurable delay to data generation

Simulates network latency by sleeping for a specified duration. The delay can be fixed or randomized within a range.

Examples:

Fixed delay

latency = Latency.new(500, rng)
latency.apply(result)  # Sleeps for 500ms

Random delay

latency = Latency.new(100..500, rng)
latency.apply(result)  # Sleeps for random 100-500ms

Instance Method Summary collapse

Constructor Details

This class inherits a constructor from Synthra::Behaviors::Base

Instance Method Details

#apply(result, context = nil) ⇒ Object

Apply latency to the result

Calculates the delay and sleeps for that duration. Validates against configured maximum latency limit.

Examples:

latency = Latency.new(500, rng)
result = latency.apply({ "id" => "123" })
# Sleeps for 500ms, then returns result

Parameters:

  • result (Object)

    the generated data (passed through unchanged)

  • context (Generator::Context, nil) (defaults to: nil)

    generation context (not used)

Returns:

  • (Object)

    the result unchanged

Raises:



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/synthra/behaviors/latency.rb', line 55

def apply(result, context = nil)
  return result unless should_apply?

  delay = calculate_delay

  # Validate against configured limits
  Synthra.configuration.limits.validate_latency!(delay)

  # Sleep for delay (convert ms to seconds)
  sleep(delay / 1000.0)
  result
end

#calculate_delayInteger (private)

Calculate the delay in milliseconds

Supports multiple value formats:

  • Range: random value within range
  • Hash: { min: X, max: Y } for range
  • Integer: fixed delay

Returns:

  • (Integer)

    delay in milliseconds



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/synthra/behaviors/latency.rb', line 81

def calculate_delay
  case value
  when Range

    # Random delay within range
    rng ? rng.rand(value) : rand(value)
  when Hash

    # Named min/max arguments
    min = value[:min] || 0
    max = value[:max] || min
    rng ? rng.int(min, max) : rand(min..max)
  when Integer

    # Fixed delay
    value
  else
    0
  end
end