Class: RightSupport::Stats::Activity

Inherits:
Object
  • Object
show all
Defined in:
lib/right_support/stats/activity.rb

Overview

Track statistics for a given kind of activity

Constant Summary collapse

RECENT_SIZE =

Number of samples included when calculating average recent activity with the smoothing formula A = ((A * (RECENT_SIZE - 1)) + V) / RECENT_SIZE, where A is the current recent average and V is the new activity value As a rough guide, it takes approximately 2 * RECENT_SIZE activity values at value V for average A to reach 90% of the original difference between A and V For example, for A = 0, V = 1, RECENT_SIZE = 3 the progression for A is 0, 0.3, 0.5, 0.7, 0.8, 0.86, 0.91, 0.94, 0.96, 0.97, 0.98, 0.99, …

3.0
MAX_TYPE_SIZE =

Maximum string length for activity type

60

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(measure_rate = true) ⇒ Activity

Initialize activity data

Parameters:

  • measure_rate (Boolean) (defaults to: true)

    Whether to measure activity rate



48
49
50
51
# File 'lib/right_support/stats/activity.rb', line 48

def initialize(measure_rate = true)
  @measure_rate = measure_rate
  reset
end

Instance Attribute Details

#count_per_typeObject (readonly)

(Hash) Count of activity per type



43
44
45
# File 'lib/right_support/stats/activity.rb', line 43

def count_per_type
  @count_per_type
end

#totalObject (readonly)

(Integer) Total activity count



40
41
42
# File 'lib/right_support/stats/activity.rb', line 40

def total
  @total
end

Class Method Details

.all(stats) ⇒ Hash, NilClass

Aggregate the stats from multiple ‘all’ calls

Parameters:

  • stats (Array)

    Hashes that are to be aggregated

Returns:

  • (Hash, NilClass)

    Summed information about activity, or nil if the total is 0 “total” [Integer] Total activity count “percent” [Hash] Percentage for each type of activity if tracking type, otherwise omitted “last” [Hash] Information about last activity

    "elapsed" [Integer] Seconds since last activity started
    "type" [String] Type of activity if tracking type, otherwise omitted
    "active" [Boolean] Whether activity still active if tracking whether active, otherwise omitted
    

    “rate” [Float] Recent average rate if measuring rate, otherwise omitted “latency” [Float] Recent average latency if measuring latency, otherwise omitted



228
229
230
231
232
233
234
235
236
237
238
# File 'lib/right_support/stats/activity.rb', line 228

def self.all(stats)
  if (total = stats.inject(0) { |t, s| t += s["total"] if s && s["total"]; t }) > 0
    all = percentage(stats, total)
    all["last"] = last(stats.map { |s| s["last"] if s })
    rate = avg_rate(stats.map { |s| {"rate" => s["rate"], "total" => s["total"]} if s }, total)
    all["rate"] = rate if rate
    latency = avg_latency(stats.map { |s| {"latency" => s["latency"], "total" => s["total"]} if s }, total)
    all["latency"] = latency if latency
    all
  end
end

.avg_latency(stats, total) ⇒ Fixnum, NilClass

Compute average latency from multiple average latency

Parameters:

  • stats (Array)

    List of stats containing hash of “latency” and “total”

  • total (Integer)

    Overall total

Returns:

  • (Fixnum, NilClass)

    Average latency or nil if no average latency data



284
285
286
287
# File 'lib/right_support/stats/activity.rb', line 284

def self.avg_latency(stats, total)
  sum = stats.inject(nil) { |sum, stat| sum = (sum || 0.0) + (stat["latency"] * stat["total"]) if stat && stat["latency"]; sum }
  sum / total if sum
end

.avg_rate(stats, total) ⇒ Fixnum, NilClass

Compute average rate from multiple average rates

Parameters:

  • stats (Array)

    List of stats containing hash of “rate” and “total”

  • total (Integer)

    Overall total

Returns:

  • (Fixnum, NilClass)

    Average rate or nil if no average rate data



273
274
275
276
# File 'lib/right_support/stats/activity.rb', line 273

def self.avg_rate(stats, total)
  sum = stats.inject(nil) { |sum, stat| sum = (sum || 0.0) + (stat["rate"] * stat["total"]) if stat && stat["rate"]; sum }
  sum / total if sum
end

.last(stats) ⇒ Hash, NilClass

Determine last activity from multiple last activity stats

Parameters:

  • stats (Array)

    Multiple last activity stats

Returns:

  • (Hash, NilClass)

    Last activity, or nil if no last activity data



294
295
296
# File 'lib/right_support/stats/activity.rb', line 294

def self.last(stats)
  stats.inject(nil) { |l, s| l = s if s && (l.nil? || (l["elapsed"] > s["elapsed"] && (s["type"] || s["active"]))); l }
end

.percentage(stats, total) ⇒ Hash

Aggregate multiple percentage stats

Parameters:

  • stats (Array)

    List of stats containing “percent” hash and “total” value

  • total (Integer)

    Overall total

Returns:

  • (Hash)

    Converted counts “total” [Integer] Total activity count “percent” [Hash] Percentage for each type of activity if tracking type, omitted if no data



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/right_support/stats/activity.rb', line 248

def self.percentage(stats, total)
  count_per_type = {}
  stats.each do |s|
    if s
      t = s["total"]
      s["percent"].each do |k, v|
        count_per_type[k] = (count_per_type[k] || 0) + ((v / 100.0) * t).round
      end if s["percent"]
    end
  end
  if count_per_type.empty?
    {"total" => total}
  else
    percent = {}
    count_per_type.each { |k, v| percent[k] = (v / total.to_f) * 100.0 }
    {"percent" => percent, "total" => total}
  end
end

Instance Method Details

#allHash, NilClass

Get stat summary including all aspects of activity that were measured except latency

Returns:

  • (Hash, NilClass)

    Information about activity, or nil if the total is 0 “total” [Integer] Total activity count “percent” [Hash] Percentage for each type of activity if tracking type, otherwise omitted “last” [Hash] Information about last activity

    "elapsed" [Integer] Seconds since last activity started
    "type" [String] Type of activity if tracking type, otherwise omitted
    "active" [Boolean] Whether activity still active if tracking whether active, otherwise omitted
    

    “rate” [Float] Recent average rate if measuring rate, otherwise omitted “latency” [Float] Recent average latency if measuring latency, otherwise omitted



187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/right_support/stats/activity.rb', line 187

def all
  if @total > 0
    result = if @count_per_type.empty?
      {"total" => @total}
    else
      percentage
    end
    result.merge!("last" => last)
    result.merge!("rate" => avg_rate) if @measure_rate
    result.merge!("latency" => avg_latency) if @avg_latency
    result
  end
end

#avg_durationFloat, NilClass

Get average latency for performing an activity avg_duration is deprecated but still supported

Returns:

  • (Float, NilClass)

    Average latency in seconds of activity weighted toward past activity, or nil if total is 0



146
147
148
# File 'lib/right_support/stats/activity.rb', line 146

def avg_latency
  @avg_latency
end

#avg_latencyFloat, NilClass

Get average latency for performing an activity

Returns:

  • (Float, NilClass)

    Average latency in seconds of activity weighted toward past activity, or nil if total is 0



141
142
143
# File 'lib/right_support/stats/activity.rb', line 141

def avg_latency
  @avg_latency
end

#avg_rateFloat, NilClass

Convert average interval to average rate Adjust interval before computing average to take into account when last activity occurred

Returns:

  • (Float, NilClass)

    Recent average rate, or nil if total is 0



130
131
132
133
134
135
# File 'lib/right_support/stats/activity.rb', line 130

def avg_rate
  if @measure_rate && @total > 0
    interval = average(@interval, Time.now - @last_start_time)
    interval == 0.0 ? 0.0 : 1.0 / interval
  end
end

#finish(start_time = nil, id = nil) ⇒ Float

Mark the finish of an activity and update the average latency

Parameters:

  • start_time (Time) (defaults to: nil)

    Time when activity started, defaults to last time update was called

  • id (String) (defaults to: nil)

    Unique identifier associated with this activity

Returns:

  • (Float)

    Activity latency in seconds



98
99
100
101
102
103
104
105
# File 'lib/right_support/stats/activity.rb', line 98

def finish(start_time = nil, id = nil)
  now = Time.now
  start_time ||= @last_start_time
  latency = now - start_time
  @avg_latency = average(@avg_latency || 0.0, latency)
  @last_id = 0 if id && id == @last_id
  latency
end

#lastHash, NilClass

Get stats about last activity

Returns:

  • (Hash, NilClass)

    Information about last activity, or nil if the total is 0 “elapsed” [Integer] Seconds since last activity started “type” [String] Type of activity if specified, otherwise omitted “active” [Boolean] Whether activity still active



154
155
156
157
158
159
160
161
# File 'lib/right_support/stats/activity.rb', line 154

def last
  if @total > 0
    result = {"elapsed" => (Time.now - @last_start_time).to_i}
    result["type"] = @last_type if @last_type
    result["active"] = @last_id != 0 if !@last_id.nil?
    result
  end
end

#measure(type, id) { ... } ⇒ Object

Update activity and measure its latency

Parameters:

  • type (String, Symbol)

    Type of activity, with anything that is not a symbol, true, or false automatically converted to a String and truncated to MAX_TYPE_SIZE characters; defaults to nil

  • id (String)

    Unique identifier associated with this activity

Yields:

  • required block being measured

Returns:

  • (Object)

    Result from yield

Raises:

  • (ArgumentError)

    block missing



118
119
120
121
122
123
124
# File 'lib/right_support/stats/activity.rb', line 118

def measure(type, id)
  raise ArgumentError, "block missing" unless block_given?
  start_time = update(type, id)
  result = yield
  finish(start_time, id)
  result
end

#percentageHash, NilClass

Convert count per type into percentage by type

Returns:

  • (Hash, NilClass)

    Converted counts, or nil if total is 0 “total” [Integer] Total activity count “percent” [Hash] Percentage for each type of activity if tracking type, otherwise omitted



168
169
170
171
172
173
174
# File 'lib/right_support/stats/activity.rb', line 168

def percentage
  if @total > 0
    percent = {}
    @count_per_type.each { |k, v| percent[k] = (v / @total.to_f) * 100.0 }
    {"percent" => percent, "total" => @total}
  end
end

#resetTrueClass

Reset statistics

Returns:

  • (TrueClass)

    Always return true



56
57
58
59
60
61
62
63
64
65
# File 'lib/right_support/stats/activity.rb', line 56

def reset
  @interval = 0.0
  @last_start_time = Time.now
  @avg_latency = nil
  @total = 0
  @count_per_type = {}
  @last_type = nil
  @last_id = nil
  true
end

#update(type = nil, id = nil) ⇒ Time

Mark the start of an activity and update counts and average rate with weighting toward past activity

Parameters:

  • type (String, Symbol) (defaults to: nil)

    Type of activity, with anything that is not a symbol, true, or false automatically converted to a String and truncated to MAX_TYPE_SIZE characters; defaults to nil

  • id (String) (defaults to: nil)

    Unique identifier associated with this activity

Returns:

  • (Time)

    Update time



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/right_support/stats/activity.rb', line 75

def update(type = nil, id = nil)
  now = Time.now
  @interval = average(@interval, now - @last_start_time) if @measure_rate
  @last_start_time = now
  @total += 1
  unless type.nil?
    unless [Symbol, TrueClass, FalseClass].include?(type.class)
      type = type.inspect unless type.is_a?(String)
      type = type[0, MAX_TYPE_SIZE - 3] + "..." if type.size > (MAX_TYPE_SIZE - 3)
    end
    @count_per_type[type] = (@count_per_type[type] || 0) + 1
  end
  @last_type = type
  @last_id = id
  now
end