Class: Tnw::MetricSamples::Ingest

Inherits:
Object
  • Object
show all
Defined in:
app/services/tnw/metric_samples/ingest.rb

Constant Summary collapse

ERROR_CODE_PATTERN =
/\A[a-z0-9_.-]+\z/
MAX_ERROR_CODES =
10
MAX_ERROR_CODE_LENGTH =
100

Instance Method Summary collapse

Constructor Details

#initialize(payload:, source_ip:, now: Time.current) ⇒ Ingest

Returns a new instance of Ingest.



10
11
12
13
14
15
# File 'app/services/tnw/metric_samples/ingest.rb', line 10

def initialize(payload:, source_ip:, now: Time.current)
  @payload = payload
  @source_ip = source_ip
  @now = now
  @server = nil
end

Instance Method Details

#callObject



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
44
45
# File 'app/services/tnw/metric_samples/ingest.rb', line 17

def call
  validate_payload_shape!
  @server = find_server!
  sample_attributes = build_sample_attributes

  @server.with_lock do
    Tnw::Metrics::ReplayGuard.verify!(server: @server, sample_uid: sample_attributes[:sample_uid])
    sample = @server.metric_samples.create!(sample_attributes)
    mark_server!(:accepted)
    sample
  end
rescue ActiveRecord::RecordInvalid => error
  ingestion_error = Tnw::Metrics::IngestionError.new(
    :invalid_payload,
    error.record.errors.full_messages.to_sentence
  )
  mark_server!(:rejected, ingestion_error.code) if @server
  raise ingestion_error
rescue ActiveRecord::RecordNotUnique
  ingestion_error = Tnw::Metrics::IngestionError.new(
    :replayed_sample,
    "Metric sample has already been accepted"
  )
  mark_server!(:rejected, ingestion_error.code) if @server
  raise ingestion_error
rescue Tnw::Metrics::IngestionError => error
  mark_server!(:rejected, error.code) if @server
  raise
end