Class: Sentiero::Rails::Store

Inherits:
Store
  • Object
show all
Defined in:
lib/sentiero/rails/store.rb

Instance Method Summary collapse

Constructor Details

#initialize(limits: nil) ⇒ Store

Returns a new instance of Store.



13
14
15
# File 'lib/sentiero/rails/store.rb', line 13

def initialize(limits: nil)
  @limits = limits
end

Instance Method Details

#count_occurrences(problem_id, after: nil) ⇒ Object

COUNT in SQL instead of materializing every row.



303
304
305
306
307
308
# File 'lib/sentiero/rails/store.rb', line 303

def count_occurrences(problem_id, after: nil)
  validate_id!(problem_id)
  scope = Occurrence.where(fingerprint: problem_id)
  scope = scope.where("timestamp > ?", after.to_f) if after
  scope.count
end

#delete_session(session_id) ⇒ Object



160
161
162
163
164
165
166
# File 'lib/sentiero/rails/store.rb', line 160

def delete_session(session_id)
  validate_id!(session_id)
  Session.transaction do
    destroy_session_data(session_id)
  end
  nil
end

#delete_window(ref) ⇒ Object



168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/sentiero/rails/store.rb', line 168

def delete_window(ref)
  validate_window_ref!(ref)
  session_id, window_id = ref.session_id, ref.window_id
  Session.transaction do
    Event.where(session_id: session_id, window_id: window_id).delete_all

    remaining = Event.where(session_id: session_id).exists?
    unless remaining
      Session.where(session_id: session_id).delete_all
    end
  end
  nil
end

#each_session_events(limit: nil, since: nil, until_time: nil, types: nil) ⇒ Object

Batched scan: one events query for the whole session page instead of the base's get_session + get_events per window.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sentiero/rails/store.rb', line 47

def each_session_events(limit: nil, since: nil, until_time: nil, types: nil)
  unless block_given?
    return enum_for(:each_session_events, limit: limit, since: since, until_time: until_time, types: types)
  end

  cap = limit || limits.analytics_max_scan_sessions
  summaries = list_sessions(limit: cap, since: since, until_time: until_time)
  return if summaries.empty?

  events = events_by_session_window(summaries.map { |summary| summary[:session_id] })
  summaries.each do |summary|
    windows = events[summary[:session_id]] || {}
    summary = summary.merge(
      window_starts: windows.transform_values { |window_events| window_events.first&.fetch("timestamp", nil) }
    )
    windows.each do |window_id, window_events|
      window_events = window_events.select { |event| types.include?(event["type"]) } if types
      yield summary, window_id, window_events
    end
  end
end

#get_events(ref, after: nil, limit: nil) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
# File 'lib/sentiero/rails/store.rb', line 129

def get_events(ref, after: nil, limit: nil)
  validate_window_ref!(ref)
  session_id, window_id = ref.session_id, ref.window_id
  scope = Event.where(session_id: session_id, window_id: window_id)
    .order(timestamp: :asc)

  scope = scope.where("timestamp > ?", after.to_f) if after
  scope = scope.limit(limit) if limit

  scope.map(&:data)
end

#get_occurrences(problem_id, after: nil, limit: nil) ⇒ Object



294
295
296
297
298
299
300
# File 'lib/sentiero/rails/store.rb', line 294

def get_occurrences(problem_id, after: nil, limit: nil)
  validate_id!(problem_id)
  scope = Occurrence.where(fingerprint: problem_id).order(timestamp: :asc)
  scope = scope.where("timestamp > ?", after.to_f) if after
  scope = scope.limit(limit) if limit
  scope.map(&:data)
end

#get_problem(problem_id) ⇒ Object



288
289
290
291
292
# File 'lib/sentiero/rails/store.rb', line 288

def get_problem(problem_id)
  validate_id!(problem_id)
  problem = Problem.find_by(fingerprint: problem_id)
  problem ? problem_to_hash(problem) : nil
end

#get_server_event(event_id) ⇒ Object



337
338
339
340
# File 'lib/sentiero/rails/store.rb', line 337

def get_server_event(event_id)
  validate_id!(event_id)
  ServerEvent.find_by(event_id: event_id)&.data
end

#get_session(session_id) ⇒ Object



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
121
122
123
124
125
126
127
# File 'lib/sentiero/rails/store.rb', line 96

def get_session(session_id)
  validate_id!(session_id)
  session = Session.find_by(session_id: session_id)
  return nil unless session

  window_stats = Event.where(session_id: session_id)
    .group(:window_id)
    .pluck(:window_id, Arel.sql("COUNT(*)"), Arel.sql("MIN(timestamp)"), Arel.sql("MAX(timestamp)"))

  window_data = window_stats.map { |wid, count, first_ts, last_ts|
    entry = {window_id: wid, event_count: count}
    entry[:first_event_at] = first_ts.to_f if first_ts
    entry[:last_event_at] = last_ts.to_f if last_ts
    entry
  }

  timestamps = Event.where(session_id: session_id)
    .pick(Arel.sql("MIN(timestamp)"), Arel.sql("MAX(timestamp)"))

  result = {
    session_id: session.session_id,
    windows: window_data,
    created_at: session.created_at.to_f,
    updated_at: session.updated_at.to_f,
    first_event_at: timestamps&.first&.to_f,
    last_event_at: timestamps&.last&.to_f
  }
  if  && session..present?
    result[:metadata] = session.
  end
  result
end

#list_problems(project:, limit:, offset: 0, status: nil, sort_by: nil, search: nil, since: nil, until_time: nil) ⇒ Object



270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/sentiero/rails/store.rb', line 270

def list_problems(project:, limit:, offset: 0, status: nil, sort_by: nil, search: nil, since: nil, until_time: nil)
  scope = Problem.all
  scope = scope.where(project: project) unless project.nil?
  scope = scope.where(status: status) if status
  scope = scope.where("last_seen >= ?", since.to_f) if since
  scope = scope.where("last_seen <= ?", until_time.to_f) if until_time
  if search && !search.empty?
    pattern = "%#{search}%"
    scope = scope.where("title LIKE ? OR exception_class LIKE ?", pattern, pattern)
  end
  scope = case sort_by
  when "first_seen" then scope.order(first_seen: :desc)
  when "count" then scope.order(count: :desc)
  else scope.order(last_seen: :desc)
  end
  scope.offset(offset).limit(limit).map { |p| problem_to_hash(p) }
end

#list_server_events(project:, limit:, name: nil, level: nil, session_id: nil, after: nil) ⇒ Object



342
343
344
345
346
347
348
349
350
351
# File 'lib/sentiero/rails/store.rb', line 342

def list_server_events(project:, limit:, name: nil, level: nil, session_id: nil, after: nil)
  scope = ServerEvent.all
  scope = scope.where(project: project) unless project.nil?
  scope = scope.order(timestamp: :asc)
  scope = scope.where(name: name) if name
  scope = scope.where(level: level) if level
  scope = scope.where(session_id: session_id) if session_id
  scope = scope.where("timestamp > ?", after.to_f) if after
  scope.limit(limit).map(&:data)
end

#list_sessions(limit:, offset: 0, since: nil, until_time: nil, sort_by: nil, search: nil, min_duration_ms: nil, min_events: nil) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/sentiero/rails/store.rb', line 69

def list_sessions(limit:, offset: 0, since: nil, until_time: nil, sort_by: nil, search: nil,
  min_duration_ms: nil, min_events: nil)
  scope = filtered_session_scope(since:, until_time:, search:)
  if sort_by == "event_count" || min_duration_ms || min_events
    scope = with_event_aggregates(scope)
  end
  if min_events
    scope = scope.having("COUNT(#{Event.table_name}.id) >= ?", min_events)
  end
  if min_duration_ms
    scope = scope.having("MAX(#{Event.table_name}.timestamp) - MIN(#{Event.table_name}.timestamp) >= ?", min_duration_ms)
  end
  scope = ordered_session_scope(scope, sort_by)

  sessions = scope.offset(offset).limit(limit).to_a
  return [] if sessions.empty?

  sids = sessions.map(&:session_id)
  window_ids_by_session = window_ids_for(sids)
  counts_by_session = event_counts_for(sids)
  timestamp_ranges = timestamp_ranges_for(sids)

  sessions.map { |session|
    session_summary(session, window_ids_by_session, counts_by_session, timestamp_ranges)
  }
end

#occurrences_for_session(session_id, limit: nil) ⇒ Object



353
354
355
356
357
358
# File 'lib/sentiero/rails/store.rb', line 353

def occurrences_for_session(session_id, limit: nil)
  validate_id!(session_id)
  scope = Occurrence.where(session_id: session_id).order(timestamp: :asc)
  scope = scope.limit(limit) if limit
  scope.map(&:data)
end

#purge_older_than(seconds) ⇒ Object

Subquery-based DELETEs avoid loading stale ids into Ruby and large IN (...) lists.



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/sentiero/rails/store.rb', line 183

def purge_older_than(seconds)
  cutoff = Time.at(Time.now.to_f - seconds)
  cutoff_f = cutoff.to_f
  session_count = nil

  Session.transaction do
    stale = Session.where("updated_at < ?", cutoff)
    Event.where(session_id: stale.select(:session_id)).delete_all
    session_count = stale.delete_all

    ServerEvent.where("timestamp < ?", cutoff_f).delete_all
    Occurrence.where("timestamp < ?", cutoff_f).delete_all
    stale_fps = Problem.where("last_seen < ?", cutoff_f).pluck(:fingerprint)
    unless stale_fps.empty?
      Occurrence.where(fingerprint: stale_fps).delete_all
      Problem.where(fingerprint: stale_fps).delete_all
    end
  end

  session_count
end

#save_events(ref, events) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/sentiero/rails/store.rb', line 17

def save_events(ref, events)
  return if events.nil? || events.empty?
  session_id, window_id = ref.session_id, ref.window_id

  now = Time.now

  Session.transaction do
    session = find_or_create_session!(session_id, now)
    session.update_column(:updated_at, now) unless session.previously_new_record?

    rows = events.map { |event|
      {
        session_id: session_id,
        window_id: window_id,
        timestamp: event["timestamp"]&.to_f,
        data: event,
        created_at: now
      }
    }
    Event.insert_all(rows)

    enforce_max_events_per_session(session_id)
    enforce_max_sessions(session_id)
  end

  nil
end

#save_metadata(session_id, metadata) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/sentiero/rails/store.rb', line 141

def (session_id, )
  return unless .is_a?(Hash) && !.empty?
  return unless 
  validate_metadata!()

  session = Session.find_by(session_id: session_id)
  return unless session

  # Locked reload-merge-save, mirroring save_occurrence's Problem.lock:
  # an unlocked read-modify-write here drops keys from a concurrent
  # merge (e.g. this same method called for "has_errors" from
  # save_occurrence racing a client-supplied metadata update).
  session.with_lock do
    existing = session. || {}
    session.update_column(:metadata, existing.merge(.transform_keys(&:to_s)))
  end
  nil
end

#save_occurrence(occurrence) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/sentiero/rails/store.rb', line 205

def save_occurrence(occurrence)
  validate_occurrence!(occurrence)
  fp = occurrence["fingerprint"]
  ts = occurrence["timestamp"].to_f
  occ_id = SecureRandom.uuid
  stored = occurrence.merge("id" => occ_id)

  # On a concurrent insert of a new fingerprint one writer's save! raises
  # (RecordInvalid from the uniqueness validator, or RecordNotUnique from the
  # DB index); retry so the loser re-runs and takes the "existing" branch.
  attempts = 0
  begin
    Problem.transaction do
      # SELECT ... FOR UPDATE so the count+1 / last_seen read-modify-write is
      # serialized; an unlocked find lost concurrent updates under READ COMMITTED.
      problem = Problem.lock.find_by(fingerprint: fp)
      if problem
        reopening = problem.status == "resolved"
        problem.count += 1
        problem.first_seen = [problem.first_seen, ts].min
        problem.last_seen = [problem.last_seen, ts].max
        problem.message = occurrence["message"]
        if reopening
          problem.status = "open"
          problem.resolved_at = nil
        end
      else
        problem = Problem.new(fingerprint: fp)
        problem.project = occurrence["project"]
        problem.exception_class = occurrence["exception_class"]
        problem.title = build_problem_title(occurrence)
        problem.message = occurrence["message"]
        problem.count = 1
        problem.status = "open"
        problem.first_seen = ts
        problem.last_seen = ts
        problem.resolved_at = nil
      end
      problem.save!

      Occurrence.create!(
        occurrence_id: occ_id,
        fingerprint: fp,
        session_id: occurrence["session_id"],
        timestamp: ts,
        data: stored
      )

      enforce_max_problems
    end
  rescue ::ActiveRecord::RecordNotUnique
    attempts += 1
    retry if attempts < 2
    raise
  rescue ::ActiveRecord::RecordInvalid => e
    raise unless e.record.errors[:fingerprint].any?
    attempts += 1
    retry if attempts < 2
    raise
  end

  (occurrence["session_id"], {"has_errors" => true}) if occurrence["session_id"]
  fp
end

#save_server_event(event) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/sentiero/rails/store.rb', line 318

def save_server_event(event)
  validate_server_event!(event)
  ev_id = SecureRandom.uuid
  stored = event.merge("id" => ev_id)
  ServerEvent.transaction do
    ServerEvent.create!(
      event_id: ev_id,
      project: event["project"],
      name: event["name"],
      level: event["level"],
      session_id: event["session_id"],
      timestamp: event["timestamp"].to_f,
      data: stored
    )
    enforce_max_server_events
  end
  nil
end

#server_events_for_session(session_id, limit: nil) ⇒ Object



360
361
362
363
364
365
# File 'lib/sentiero/rails/store.rb', line 360

def server_events_for_session(session_id, limit: nil)
  validate_id!(session_id)
  scope = ServerEvent.where(session_id: session_id).order(timestamp: :asc)
  scope = scope.limit(limit) if limit
  scope.map(&:data)
end

#session_ids_for_problem(problem_id, limit: nil) ⇒ Object



367
368
369
370
371
372
373
374
375
# File 'lib/sentiero/rails/store.rb', line 367

def session_ids_for_problem(problem_id, limit: nil)
  validate_id!(problem_id)
  scope = Occurrence.where(fingerprint: problem_id)
    .where.not(session_id: nil)
    .group(:session_id)
    .order(Arel.sql("MAX(timestamp) DESC"))
    .pluck(:session_id)
  limit ? scope.first(limit) : scope
end

#update_problem_status(problem_id, status) ⇒ Object



310
311
312
313
314
315
316
# File 'lib/sentiero/rails/store.rb', line 310

def update_problem_status(problem_id, status)
  validate_id!(problem_id)
  validate_status!(status)
  resolved_at = (status == "resolved") ? Time.now.to_f : nil
  Problem.where(fingerprint: problem_id).update_all(status: status, resolved_at: resolved_at)
  nil
end