Class: Apptrail::ApptrailEventsClient

Inherits:
Object
  • Object
show all
Defined in:
lib/apptrail-application-events-sdk.rb

Overview

You can use the Apptrail Application Events Client to send audit log events from your Ruby applications.

See [Sending events](apptrail.com/docs/applications/guide/working-with-events/overview).

Instance Method Summary collapse

Constructor Details

#initialize(region:, api_key:) ⇒ ApptrailEventsClient

Returns a new instance of ApptrailEventsClient.



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/apptrail-application-events-sdk.rb', line 69

def initialize(region:, api_key:)
  @_region = region
  begin
    parsed_key = Base64.urlsafe_decode64(api_key)
    application_id, = parsed_key.split(',', 3)
    @_application_id = application_id
  rescue StandardError
    raise ArgumentError, 'Invalid API Key.'
  end

  @_base_api_url = "https://events.#{region}.apptrail.com/applications/session"
  @_api_key = api_key
  @_session_client = HTTP.persistent @_base_api_url

  @_form_data = nil
  @_upload_url = nil
  @_upload_client = nil

  @_finalize_id = SecureRandom.uuid
  ObjectSpace.define_finalizer(@_finalize_id, proc { close })
end

Instance Method Details

#closeObject



158
159
160
161
162
163
# File 'lib/apptrail-application-events-sdk.rb', line 158

def close
  # https://github.com/appsignal/rdkafka-ruby/pull/160/files
  ObjectSpace.undefine_finalizer(@_finalize_id)
  @_session_client.close if @_session_client
  @_upload_client.close if @_upload_client
end

#inspectObject



61
62
63
# File 'lib/apptrail-application-events-sdk.rb', line 61

def inspect
  "#<ApptrailEventsClient:#{object_id}>"
end

#put_event(event) ⇒ Object

Send a single audit event to log to Apptrail.

Parameters:



94
95
96
# File 'lib/apptrail-application-events-sdk.rb', line 94

def put_event(event)
  put_events([event])
end

#put_events(events) ⇒ Object

Send a list of up to 1000 audit events to log to Apptrail.

Parameters:

Raises:

  • (TypeError)


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
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
156
# File 'lib/apptrail-application-events-sdk.rb', line 101

def put_events(events)
  raise TypeError, 'Must pass in array of events.' unless events.is_a?(Array)
  raise ArgumentError, 'Can not send more than 1000 events in a single PutEvents call.' unless events.length <= 1000

  begin
    JSON::Validator.validate!(SCHEMA, events, list: true, parse_data: false)
  rescue JSON::Schema::ValidationError => e
    raise Apptrail::ApptrailError, e.message
  end

  _refresh_post_policy() if @_upload_url.nil? || @_form_data.nil? || @_upload_client.nil?

  content = StringIO.new
  events.each do |evt|
    content << JSON.fast_generate(evt)
    content << "\n"
  end

  filename = "#{SecureRandom.uuid}.jsonl"
  s3_key = File.join(@_application_id, filename)

  form_file = HTTP::FormData::File.new(StringIO.new(content.string), filename: filename)

  new_form_opts = {
    **@_form_data,
    key: s3_key,
    file: form_file
  }

  resp = nil
  begin
    Retriable.with_context(:s3) do
      resp = @_upload_client.post(@_upload_url, form: new_form_opts)
      unless resp.status.success?
        if resp.status.server_error?
          raise ApptrailRetryableError, 'Server Error while putting events.'
        elsif resp.status.client_error?
          if resp.status.code == 403 && resp.body.to_s.include?('Policy expired')
            _refresh_post_policy
            raise ApptrailRetryableError, 'Session expired.'
          else
            raise ApptrailError, 'Error while putting events.'
          end
        else
          raise ApptrailError, 'Error while putting events.'
        end
      end
    end
  rescue StandardError
    raise ApptrailError, "Failed to put #{events.length} events. Encountered error."
  else
    Apptrail.logger.info("Successfully wrote #{events.length} events.")
  ensure
    resp.flush if resp
  end
end

#to_sObject



65
66
67
# File 'lib/apptrail-application-events-sdk.rb', line 65

def to_s
  'ApptrailEventsClient{}'
end