hyperdx-ruby 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 4933bb0e69a1ad181315c58d286df867e1c657f3571fae7b1deeda5d731ca630
4
+ data.tar.gz: 97bbb1208f0052283abee07c27a04a0005590e3dd06097e62644f04d86857014
5
+ SHA512:
6
+ metadata.gz: b8fab542413e3d0ff9fd02f58356e0ae238bf37fe2e235052b02b735b64d5332dd415777571228dcf24ae5de2755ec9c0f2fbc991984bba780d62f07ee12eb27
7
+ data.tar.gz: 357382ef8d18d2dbdf412c7595d85cfc48d5e287d719a5b34210bc9989f2a56672cc54f7f951bf2e071503c8d1b23558f778cf2963380915a03d752572c2383f
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Hyperdx::Ruby
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/hyperdx/ruby`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/hyperdx-ruby. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/hyperdx-ruby/blob/main/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the Hyperdx::Ruby project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/hyperdx-ruby/blob/main/CODE_OF_CONDUCT.md).
@@ -0,0 +1,208 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "etc"
4
+ require "net/http"
5
+ require "socket"
6
+ require "json"
7
+ require "concurrent"
8
+ require "date"
9
+ require "securerandom"
10
+
11
+ module Hyperdx
12
+ Message = Struct.new(:source, :running_size)
13
+
14
+ class Client
15
+ def initialize(request, uri, opts)
16
+ @uri = uri
17
+
18
+ # NOTE: buffer is in memory
19
+ @buffer = []
20
+
21
+ @lock = Mutex.new
22
+
23
+ @flush_interval = opts[:flush_interval] || Resources::FLUSH_INTERVAL
24
+ @flush_size = opts[:flush_size] || Resources::FLUSH_SIZE
25
+
26
+ @request = request
27
+ @request_size = opts[:request_size] || Resources::REQUEST_SIZE
28
+
29
+ @retry_timeout = opts[:retry_timeout] || Resources::RETRY_TIMEOUT
30
+ @retry_max_jitter = opts[:retry_max_jitter] || Resources::RETRY_MAX_JITTER
31
+ @retry_max_attempts = opts[:retry_max_attempts] || Resources::RETRY_MAX_ATTEMPTS
32
+
33
+ @internal_logger = Logger.new($stdout)
34
+ @internal_logger.level = Logger::DEBUG
35
+
36
+ @work_thread_pool = Concurrent::FixedThreadPool.new(Etc.nprocessors)
37
+ # TODO: Expose an option to configure the maximum concurrent requests
38
+ # Requires the instance-global request to be resolved first
39
+ @request_thread_pool = Concurrent::FixedThreadPool.new(Resources::MAX_CONCURRENT_REQUESTS)
40
+
41
+ @scheduled_flush = nil
42
+ end
43
+
44
+ def schedule_flush
45
+ if @scheduled_flush.nil? || @scheduled_flush.complete?
46
+ @scheduled_flush = Concurrent::ScheduledTask.execute(@flush_interval) { flush }
47
+ end
48
+ end
49
+
50
+ def unschedule_flush
51
+ if !@scheduled_flush.nil?
52
+ @scheduled_flush.cancel
53
+ @scheduled_flush = nil
54
+ end
55
+ end
56
+
57
+ def process_message(msg, opts = {})
58
+ processed_message = {
59
+ line: msg,
60
+ app: opts[:app],
61
+ level: opts[:level],
62
+ env: opts[:env],
63
+ meta: opts[:meta],
64
+ timestamp: Time.now.to_i,
65
+ }
66
+ processed_message.delete(:meta) if processed_message[:meta].nil?
67
+ processed_message
68
+ end
69
+
70
+ def write_to_buffer(msg, opts)
71
+ Concurrent::Future.execute({ executor: @work_thread_pool }) { write_to_buffer_sync(msg, opts) }
72
+ end
73
+
74
+ def write_to_buffer_sync(msg, opts)
75
+ processed_message = process_message(msg, opts)
76
+ message_size = processed_message.to_s.bytesize
77
+
78
+ running_size = @lock.synchronize do
79
+ running_size = message_size
80
+ if @buffer.any?
81
+ running_size += @buffer[-1].running_size
82
+ end
83
+ @buffer.push(Message.new(processed_message, running_size))
84
+
85
+ running_size
86
+ end
87
+
88
+ if running_size >= @flush_size
89
+ unschedule_flush
90
+ flush_sync
91
+ else
92
+ schedule_flush
93
+ end
94
+ end
95
+
96
+ ##
97
+ # Flushes all logs to HyperDX asynchronously
98
+ def flush(options = {})
99
+ Concurrent::Future.execute({ executor: @work_thread_pool }) { flush_sync(options) }
100
+ end
101
+
102
+ ##
103
+ # Flushes all logs to HyperDX synchronously
104
+ def flush_sync(options = {})
105
+ slices = @lock.synchronize do
106
+ # Slice the buffer into chunks that try to be no larger than @request_size. Slice points are found with
107
+ # a binary search thanks to the structure of @buffer. We are working backwards because it's cheaper to
108
+ # remove from the tail of an array instead of the head
109
+ slices = []
110
+ until @buffer.empty?
111
+ search_size = @buffer[-1].running_size - @request_size
112
+ if search_size.negative?
113
+ search_size = 0
114
+ end
115
+
116
+ slice_index = @buffer.bsearch_index { |message| message.running_size >= search_size }
117
+ slices.push(@buffer.pop(@buffer.length - slice_index).map(&:source))
118
+ end
119
+ slices
120
+ end
121
+
122
+ # Remember the chunks are in reverse order, this un-reverses them
123
+ slices.reverse_each do |slice|
124
+ if options[:block_on_requests]
125
+ try_request(slice)
126
+ else
127
+ Concurrent::Future.execute({ executor: @request_thread_pool }) { try_request(slice) }
128
+ end
129
+ end
130
+ end
131
+
132
+ def try_request(slice)
133
+ body = slice.to_json
134
+
135
+ flush_id = "#{SecureRandom.uuid} [#{slice.length} lines]"
136
+ error_header = "Flush {#{flush_id}} failed."
137
+ tries = 0
138
+ loop do
139
+ tries += 1
140
+
141
+ if tries > @retry_max_attempts
142
+ @internal_logger.debug("Flush {#{flush_id}} exceeded 3 tries. Discarding flush buffer")
143
+ break
144
+ end
145
+
146
+ if send_request(body, error_header)
147
+ break
148
+ end
149
+
150
+ sleep(@retry_timeout * (1 << (tries - 1)) + rand(@retry_max_jitter))
151
+ end
152
+ end
153
+
154
+ def send_request(body, error_header)
155
+ # TODO: Remove instance-global request object
156
+ @request.body = body
157
+ begin
158
+ response = Net::HTTP.start(
159
+ @uri.hostname,
160
+ @uri.port,
161
+ use_ssl: @uri.scheme == "https"
162
+ ) do |http|
163
+ http.request(@request)
164
+ end
165
+
166
+ code = response.code.to_i
167
+ if [401, 403].include?(code)
168
+ @internal_logger.debug("#{error_header} Please provide a valid ingestion key. Discarding flush buffer")
169
+ return true
170
+ elsif [408, 500, 504].include?(code)
171
+ # These codes might indicate a temporary ingester issue
172
+ @internal_logger.debug("#{error_header} The request failed #{response}. Retrying")
173
+ elsif code == 200
174
+ return true
175
+ else
176
+ @internal_logger.debug("#{error_header} The request failed #{response}. Discarding flush buffer")
177
+ return true
178
+ end
179
+ rescue SocketError
180
+ @internal_logger.debug("#{error_header} Network connectivity issue. Retrying")
181
+ rescue Errno::ECONNREFUSED => e
182
+ @internal_logger.debug("#{error_header} The server is down. #{e.message}. Retrying")
183
+ rescue Timeout::Error => e
184
+ @internal_logger.debug("#{error_header} Timeout error occurred. #{e.message}. Retrying")
185
+ end
186
+
187
+ false
188
+ end
189
+
190
+ def exitout
191
+ unschedule_flush
192
+ @work_thread_pool.shutdown
193
+ if !@work_thread_pool.wait_for_termination(1)
194
+ @internal_logger.warn("Work thread pool unable to shutdown gracefully. Logs potentially dropped")
195
+ end
196
+ @request_thread_pool.shutdown
197
+ if !@request_thread_pool.wait_for_termination(5)
198
+ @internal_logger.warn("Request thread pool unable to shutdown gracefully. Logs potentially dropped")
199
+ end
200
+
201
+ if @buffer.any?
202
+ @internal_logger.debug("Exiting HyperDX logger: Logging remaining messages")
203
+ flush_sync({ block_on_requests: true })
204
+ @internal_logger.debug("Finished flushing logs to HyperDX")
205
+ end
206
+ end
207
+ end
208
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Resources
4
+ LOG_LEVELS = %w[DEBUG INFO WARN ERROR FATAL TRACE].freeze
5
+ DEFAULT_REQUEST_HEADER = { "Content-Type" => "application/json; charset=UTF-8" }.freeze
6
+ DEFAULT_REQUEST_TIMEOUT = 180_000
7
+ MS_IN_A_DAY = 86_400_000
8
+ MAX_REQUEST_TIMEOUT = 300_000
9
+ MAX_LINE_LENGTH = 32_000
10
+ MAX_INPUT_LENGTH = 80
11
+ RETRY_TIMEOUT = 0.25
12
+ RETRY_MAX_ATTEMPTS = 3
13
+ RETRY_MAX_JITTER = 0.5
14
+ FLUSH_INTERVAL = 0.25
15
+ FLUSH_SIZE = 2 * 1_024 * 1_024
16
+ REQUEST_SIZE = 2 * 1_024 * 1_024
17
+ ENDPOINT = "https://in.hyperdx.io"
18
+ MAC_ADDR_CHECK = /^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/.freeze
19
+ IP_ADDR_CHECK = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.freeze
20
+ MAX_CONCURRENT_REQUESTS = 1
21
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Hyperdx
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,133 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "logger"
4
+ require "socket"
5
+ require "uri"
6
+ require_relative "ruby/client"
7
+ require_relative "ruby/resources"
8
+ require_relative "ruby/version"
9
+
10
+ module Hyperdx
11
+ class ValidURLRequired < ArgumentError; end
12
+
13
+ class MaxLengthExceeded < ArgumentError; end
14
+
15
+ class Ruby < ::Logger
16
+ # uncomment line below and line 3 to enforce singleton
17
+ # include Singleton
18
+ Logger::TRACE = 5
19
+ attr_accessor :app, :env, :meta
20
+
21
+ def initialize(key, opts = {})
22
+ super(nil, nil, nil)
23
+ @app = opts[:app] || "default"
24
+ @log_level = opts[:level] || "INFO"
25
+ @env = opts[:env]
26
+ @meta = opts[:meta]
27
+ @internal_logger = Logger.new($stdout)
28
+ @internal_logger.level = Logger::DEBUG
29
+ endpoint = opts[:endpoint] || Resources::ENDPOINT
30
+ hostname = opts[:hostname] || Socket.gethostname
31
+
32
+ if hostname.size > Resources::MAX_INPUT_LENGTH || @app.size > Resources::MAX_INPUT_LENGTH
33
+ @internal_logger.debug("Hostname or Appname is over #{Resources::MAX_INPUT_LENGTH} characters")
34
+ return
35
+ end
36
+
37
+ ip = opts.key?(:ip) ? "&ip=#{opts[:ip]}" : ""
38
+ mac = opts.key?(:mac) ? "&mac=#{opts[:mac]}" : ""
39
+ url = "#{endpoint}?hostname=#{hostname}#{mac}#{ip}"
40
+ uri = URI(url)
41
+
42
+ request = Net::HTTP::Post.new(uri.request_uri, "Content-Type" => "application/json")
43
+ request['Authorization'] = "Bearer #{key}"
44
+ request[:'user-agent'] = opts[:'user-agent'] || "ruby/#{Hyperdx::VERSION}"
45
+ @client = Hyperdx::Client.new(request, uri, opts)
46
+ end
47
+
48
+ def default_opts
49
+ {
50
+ app: @app,
51
+ level: @log_level,
52
+ env: @env,
53
+ meta: @meta,
54
+ }
55
+ end
56
+
57
+ def level
58
+ @log_level
59
+ end
60
+
61
+ def level=(value)
62
+ if value.is_a? Numeric
63
+ @log_level = Resources::LOG_LEVELS[value]
64
+ return
65
+ end
66
+
67
+ @log_level = value
68
+ end
69
+
70
+ def log(message = nil, opts = {})
71
+ if message.nil? && block_given?
72
+ message = yield
73
+ end
74
+ if message.nil?
75
+ @internal_logger.debug("provide either a message or block")
76
+ return
77
+ end
78
+ message = message.to_s.encode("UTF-8")
79
+ @client.write_to_buffer(message, default_opts.merge(opts).merge(
80
+ timestamp: (Time.now.to_f * 1000).to_i
81
+ ))
82
+ end
83
+
84
+ Resources::LOG_LEVELS.each do |lvl|
85
+ name = lvl.downcase
86
+
87
+ define_method name do |msg = nil, opts = {}, &block|
88
+ self.log(msg, opts.merge(
89
+ level: lvl
90
+ ), &block)
91
+ end
92
+
93
+ define_method "#{name}?" do
94
+ return Resources::LOG_LEVELS[self.level] == lvl if level.is_a? Numeric
95
+
96
+ self.level == lvl
97
+ end
98
+ end
99
+
100
+ def clear
101
+ @app = "default"
102
+ @log_level = "INFO"
103
+ @env = nil
104
+ @meta = nil
105
+ end
106
+
107
+ def <<(msg = nil, opts = {})
108
+ log(msg, opts.merge(
109
+ level: ""
110
+ ))
111
+ end
112
+
113
+ def add(*_arg)
114
+ @internal_logger.debug("add not supported in HyperDX logger")
115
+ false
116
+ end
117
+
118
+ def unknown(msg = nil, opts = {})
119
+ log(msg, opts.merge(
120
+ level: "UNKNOWN"
121
+ ))
122
+ end
123
+
124
+ def datetime_format(*_arg)
125
+ @internal_logger.debug("datetime_format not supported in HyperDX logger")
126
+ false
127
+ end
128
+
129
+ def close
130
+ @client&.exitout
131
+ end
132
+ end
133
+ end
metadata ADDED
@@ -0,0 +1,119 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: hyperdx-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Warren Lee
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-05-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: concurrent-ruby
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: json
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: require_all
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.4'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.4'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.18'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.18'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '0.78'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '0.78'
83
+ description: ''
84
+ email:
85
+ - warren@hyperdx.io
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - LICENSE
91
+ - README.md
92
+ - lib/hyperdx/ruby.rb
93
+ - lib/hyperdx/ruby/client.rb
94
+ - lib/hyperdx/ruby/resources.rb
95
+ - lib/hyperdx/ruby/version.rb
96
+ homepage: https://github.com/hyperdxio/hyperdx-ruby
97
+ licenses:
98
+ - MIT
99
+ metadata: {}
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: 2.5.0
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubygems_version: 3.4.10
116
+ signing_key:
117
+ specification_version: 4
118
+ summary: HyperDX Ruby SDK
119
+ test_files: []