Sha256: 6c03c8a581bb62ee6cb92f60d383683e52ac80bc34fd12cda22f435d06b452c9

Contents?: true

Size: 1.87 KB

Versions: 2

Compression:

Stored size: 1.87 KB

Contents

# frozen_string_literal: true

require "singleton"
require "json"

module PlainApm
  class Agent
    include Singleton

    def self.collect(event)
      instance.collect(event)
    end

    def self.start
      instance.start
    end

    def self.stop
      instance.stop
    end

    def collect(event)
      return unless @config.enabled

      @events << event
    end

    def start
      # Already running
      return unless @publisher.nil?

      configure

      return unless @config.enabled

      # TODO: sized queue w/ a timeout.
      @events = Thread::Queue.new

      # TODO: Multiple threads
      @publisher = Thread.new { publisher_loop }

      install_hooks

      # TODO: add a cleaner shutdown.
      at_exit { stop }
    end

    def stop
      return if @publisher.nil?

      uninstall_hooks

      @events << nil
      @publisher.join
      @publisher = nil
    end

    private

    def configure
      @config = Config.new
    end

    def install_hooks
      hooks.each(&:install)
    end

    def uninstall_hooks
      hooks.each(&:uninstall)
    end

    def hooks
      @hooks ||= [
        Hooks::ActionMailer,
        Hooks::ActionPack,
        Hooks::ActionView,
        Hooks::ActiveJob,
        Hooks::ActiveRecord,
        Hooks::ActiveSupport,
        Hooks::ErrorReporter,
        Hooks::Manual
      ].map(&:new)
    end

    ##
    # Run a background thread that pops events from the queue and posts them to
    # the target server.
    def publisher_loop
      # Have the thread keep it's own connection.
      transport = Transport.new(
        endpoint: @config.endpoint,
        app_key: @config.app_key
      )

      loop do
        event = @events.pop

        break if event.nil?

        # TODO: event serialization
        _response, _error, _retriable = transport.deliver(JSON.generate(event))

        # TODO: retries / drops
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
plain_apm-0.9.1 lib/plain_apm/agent.rb
plain_apm-0.9.0 lib/plain_apm/agent.rb