dogstatsd-ruby 4.8.2 → 5.4.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: dca98cecf21fceb3e5a4c4e76ceb8be8ffa2032ad317d63d1b3df7817dd60ef7
4
- data.tar.gz: 0ef534d77693c3f1efbd8e8c8e1399f54ee6664e1044a16c913e4f9fa302e3d7
3
+ metadata.gz: d780ad7a840c021ee3cb31a9e8b512ef7ccff4b82b14be9e300206d3a07cc61e
4
+ data.tar.gz: 2da798fe3a84f313c5c84655136597c562e3dc1bfaa24f8ba6441ef722c7cc45
5
5
  SHA512:
6
- metadata.gz: d95681cd4c29de465efb5f6429227716d5cf4c6d1c57d1d5f6ba06cae2297b6ac06a961763a800b7997e6bf0011fa6f922826fdea7842fde536943c151c8e050
7
- data.tar.gz: 0b560868db6815d18283ae938536c234d169e5aba4e1d602ee97759b36ad19fab626297b56cecf07b426c14de211e4bab43a010474e51a347387f82cd0c9cabe
6
+ metadata.gz: 8f92d7dab8099d571c291e26497020e53087ccdbeecfd84d955778f484112f9b94fb0f4ec7d043b9efabd5d249333168fa44e4fe6e54ba4c9541447b92983ceb
7
+ data.tar.gz: 8dadc086c84a821d4a1b1824a25ea4861bdf0b6a36cfcf8c50a8d06e19d6853c35974dbefb03fedc9ccd7a3f57ff13a19d206c5eef152c1aa5ffbc1f789da1bc
data/README.md CHANGED
@@ -22,22 +22,83 @@ To instantiate a DogStatsd client:
22
22
  # Import the library
23
23
  require 'datadog/statsd'
24
24
 
25
- # Create a DogStatsD client instance.
25
+ # Create a DogStatsD client instance
26
26
  statsd = Datadog::Statsd.new('localhost', 8125)
27
+ # ...
28
+ # release resources used by the client instance
29
+ statsd.close()
27
30
  ```
28
31
  Or if you want to connect over Unix Domain Socket:
29
32
  ```ruby
30
33
  # Connection over Unix Domain Socket
31
34
  statsd = Datadog::Statsd.new(socket_path: '/path/to/socket/file')
35
+ # ...
36
+ # release resources used by the client instance
37
+ statsd.close()
32
38
  ```
33
39
 
34
- Find a list of all the available options for your DogStatsD Client in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd) or in the [Datadog public DogStatsD documentation](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby#client-instantiation-parameters).
40
+ Find a list of all the available options for your DogStatsD Client in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd) or in the [Datadog public DogStatsD documentation](https://docs.datadoghq.com/developers/dogstatsd/?code-lang=ruby#client-instantiation-parameters).
41
+
42
+ ### Migrating from v4.x to v5.x
43
+
44
+ If you are already using DogStatsD-ruby v4.x and you want to migrate to a version v5.x, the major
45
+ change concerning you is the new [threading model](#threading-model):
46
+
47
+ In practice, it means two things:
48
+
49
+ 1. Now that the client is buffering metrics before sending them, you have to call `Datadog::Statsd#flush(sync: true)` if you want synchronous behavior. In most cases, this is not needed, as the sender thread will automatically flush the buffered metrics if the buffer gets full or when you are closing the instance.
50
+
51
+ 2. You have to make sure you are either:
52
+
53
+ * Using a singleton instance of the DogStatsD client instead of creating a new instance whenever you need one; this will let the buffering mechanism flush metrics regularly
54
+ * Or properly disposing of the DogStatsD client instance when it is not needed anymore using the method `Datadog::Statsd#close`
55
+
56
+ If you have issues with the sender thread or the buffering mode, you can instantiate a client that behaves exactly as in v4.x (i.e. no sender thread and flush on every metric submission):
57
+
58
+ ```ruby
59
+ # Create a DogStatsD client instance using UDP
60
+ statsd = Datadog::Statsd.new('localhost', 8125, single_thread: true, buffer_max_pool_size: 1)
61
+ # ...
62
+ statsd.close()
63
+ ```
64
+
65
+ or
66
+
67
+ ```ruby
68
+ # Create a DogStatsD client instance using UDS
69
+ statsd = Datadog::Statsd.new(socket_path: '/path/to/socket/file', single_thread: true, buffer_max_pool_size: 1)
70
+ # ...
71
+ statsd.close()
72
+ ```
73
+
74
+ ### v5.x Common Pitfalls
75
+
76
+ Version v5.x of `dogstatsd-ruby` is using a sender thread for flushing. This provides better performance, but you need to consider the following pitfalls:
77
+
78
+ 1. Applications that use `fork` after having created the dogstatsd instance: the child process will automatically spawn a new sender thread to flush metrics.
79
+
80
+ 2. Applications that create multiple instances of the client without closing them: it is important to `#close` all instances to free the thread and the socket they are using otherwise you will leak those resources.
81
+
82
+ If you are using [Sidekiq](https://github.com/mperham/sidekiq), please make sure to close the client instances that are instantiated. [See this example on using DogStatsD-ruby v5.x with Sidekiq](https://github.com/DataDog/dogstatsd-ruby/blob/master/examples/sidekiq_example.rb).
83
+
84
+ If you are using [Puma](https://github.com/puma/puma) or [Unicorn](https://yhbt.net/unicorn.git), please make sure to create the instance of DogStatsD in the workers, not in the main process before it forks to create its workers. See [this comment for more details](https://github.com/DataDog/dogstatsd-ruby/issues/179#issuecomment-845570345).
85
+
86
+ Applications that run into issues but can't apply these recommendations should use the `single_thread` mode which disables the use of the sender thread.
87
+ Here is how to instantiate a client in this mode:
88
+
89
+ ```ruby
90
+ statsd = Datadog::Statsd.new('localhost', 8125, single_thread: true)
91
+ # ...
92
+ # release resources used by the client instance and flush last metrics
93
+ statsd.close()
94
+ ```
35
95
 
36
96
  ### Origin detection over UDP
37
97
 
38
- Origin detection is a method to detect which pod DogStatsD packets are coming from in order to add the pod's tags to the tag list.
98
+ Origin detection is a method to detect which pod DogStatsD packets are coming from, in order to add the pod's tags to the tag list.
99
+
100
+ To enable origin detection over UDP, add the following lines to your application manifest:
39
101
 
40
- To enable origin detection over UDP, add the following lines to your application manifest
41
102
  ```yaml
42
103
  env:
43
104
  - name: DD_ENTITY_ID
@@ -45,49 +106,124 @@ env:
45
106
  fieldRef:
46
107
  fieldPath: metadata.uid
47
108
  ```
109
+
48
110
  The DogStatsD client attaches an internal tag, `entity_id`. The value of this tag is the content of the `DD_ENTITY_ID` environment variable, which is the pod’s UID.
49
111
 
50
112
  ## Usage
51
113
 
52
- In order to use DogStatsD metrics, events, and Service Checks the Agent must be [running and available](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby).
114
+ In order to use DogStatsD metrics, events, and Service Checks the Datadog Agent must be [running and available](https://docs.datadoghq.com/developers/dogstatsd/?tab=ruby).
53
115
 
54
116
  ### Metrics
55
117
 
56
- After the client is created, you can start sending custom metrics to Datadog. See the dedicated [Metric Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby) to see how to submit all supported metric types to Datadog with working code examples:
118
+ After the client is created, you can start sending custom metrics to Datadog. See the dedicated [Metric Submission: DogStatsD documentation](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby) to see how to submit all supported metric types to Datadog with working code examples:
57
119
 
58
- * [Submit a COUNT metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#count).
59
- * [Submit a GAUGE metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#gauge).
60
- * [Submit a SET metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#set)
61
- * [Submit a HISTOGRAM metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#histogram)
62
- * [Submit a DISTRIBUTION metric](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#distribution)
120
+ * [Submit a COUNT metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#count).
121
+ * [Submit a GAUGE metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#gauge).
122
+ * [Submit a SET metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#set)
123
+ * [Submit a HISTOGRAM metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#histogram)
124
+ * [Submit a DISTRIBUTION metric](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?code-lang=ruby#distribution)
63
125
 
64
- Some options are suppported when submitting metrics, like [applying a Sample Rate to your metrics](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-submission-options) or [tagging your metrics with your custom tags](https://docs.datadoghq.com/developers/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-tagging). Find all the available functions to report metrics in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd).
126
+ Some options are suppported when submitting metrics, like [applying a Sample Rate to your metrics](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-submission-options) or [tagging your metrics with your custom tags](https://docs.datadoghq.com/metrics/dogstatsd_metrics_submission/?tab=ruby#metric-tagging). Find all the available functions to report metrics in the [DogStatsD-ruby rubydoc](https://www.rubydoc.info/github/DataDog/dogstatsd-ruby/master/Datadog/Statsd).
65
127
 
66
128
  ### Events
67
129
 
68
- After the client is created, you can start sending events to your Datadog Event Stream. See the dedicated [Event Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/events/dogstatsd/?tab=ruby) to see how to submit an event to Datadog your Event Stream.
130
+ After the client is created, you can start sending events to your Datadog Event Stream. See the dedicated [Event Submission: DogStatsD documentation](https://docs.datadoghq.com/events/guides/dogstatsd/?code-lang=ruby) to see how to submit an event to Datadog your Event Stream.
69
131
 
70
132
  ### Service Checks
71
133
 
72
134
  After the client is created, you can start sending Service Checks to Datadog. See the dedicated [Service Check Submission: DogStatsD documentation](https://docs.datadoghq.com/developers/service_checks/dogstatsd_service_checks_submission/?tab=ruby) to see how to submit a Service Check to Datadog.
73
135
 
74
- ### Maximum packets size in high-throughput scenarios
136
+ ### Maximum packet size in high-throughput scenarios
75
137
 
76
138
  In order to have the most efficient use of this library in high-throughput scenarios,
77
- default values for the maximum packets size have already been set for both UDS (8192 bytes)
78
- and UDP (1432 bytes) in order to have the best usage of the underlying network.
79
- However, if you perfectly know your network and you know that a different value for the maximum packets
80
- size should be used, you can set it with the parameter `buffer_max_payload_size`. Example:
139
+ recommended values for the maximum packet size have already been set for both UDS (8192 bytes)
140
+ and UDP (1432 bytes).
141
+
142
+ However, if are in control of your network and want to use a different value for the maximum packet
143
+ size, you can do it by setting the `buffer_max_payload_size` parameter:
81
144
 
82
145
  ```ruby
83
- # Create a DogStatsD client instance.
84
146
  statsd = Datadog::Statsd.new('localhost', 8125, buffer_max_payload_size: 4096)
147
+ # ...
148
+ statsd.close()
149
+ ```
150
+
151
+ ## Threading model
152
+
153
+ Starting with version 5.0, `dogstatsd-ruby` employs a new threading model where one instance of `Datadog::Statsd` can be shared between threads and where data sending is non-blocking (asynchronous).
154
+
155
+ When you instantiate a `Datadog::Statsd`, a sender thread is spawned. This thread will be called the Sender thread, as it is modeled by the [Sender](../lib/datadog/statsd/sender.rb) class. You can make use of `single_thread: true` to disable this behavior.
156
+
157
+ This thread is stopped when you close the statsd client (`Datadog::Statsd#close`). Instantiating a lot of statsd clients without calling `#close` after they are not needed anymore will most likely lead to threads being leaked.
158
+
159
+ The sender thread has the following logic (from `Datadog::Statsd::Sender#send_loop`):
160
+
85
161
  ```
162
+ while the sender message queue is not closed do
163
+ read message from sender message queue
164
+
165
+ if message is a Control message to flush
166
+ flush buffer in connection
167
+ else if message is a Control message to synchronize
168
+ synchronize with calling thread
169
+ else
170
+ add message to the buffer
171
+ end
172
+ end while
173
+ ```
174
+
175
+ There are three different kinds of messages:
176
+
177
+ 1. a control message to flush the buffer in the connection
178
+ 2. a control message to synchronize any thread with the sender thread
179
+ 3. a message to append to the buffer
180
+
181
+ There is also an implicit message which closes the queue which will cause the sender thread to finish processing and exit.
182
+
183
+
184
+ ```ruby
185
+ statsd = Datadog::Statsd.new('localhost', 8125)
186
+ ```
187
+
188
+ The message queue's maximum size (in messages) is given by the `sender_queue_size` argument, and has appropriate defaults for UDP (2048) and UDS (512).
189
+
190
+ The `buffer_flush_interval`, if enabled, is implemented with an additional thread which manages the timing of those flushes. This additional thread is used even if `single_thread: true`.
191
+
192
+ ### Usual workflow
193
+
194
+ You push metrics to the statsd client which writes them quickly to the sender message queue. The sender thread receives those message, buffers them and flushes them to the connection when the buffer limit is reached.
195
+
196
+ ### Flushing
197
+
198
+ When calling `Datadog::Statsd#flush`, a specific control message (`:flush`) is sent to the sender thread. When the sender thread receives it, it flushes its internal buffer into the connection.
199
+
200
+ ### Rendez-vous
201
+
202
+ It is possible to ensure a message has been consumed by the sender thread and written to the buffer by simply calling a rendez-vous right after. This is done when you are doing a synchronous flush using `Datadog::Statsd#flush(sync: true)`.
203
+
204
+ Doing so means the caller thread is blocked and waiting until the data has been flushed by the sender thread.
205
+
206
+ This is useful when preparing to exit the application or when checking unit tests.
207
+
208
+ ### Thread-safety
209
+
210
+ By default, instances of `Datadog::Statsd` are thread-safe and we recommend that a single instance be reused by all application threads (even in applications that employ forking). The sole exception is the `#close` method — this method is not yet thread safe (work in progress here [#209](https://github.com/DataDog/dogstatsd-ruby/pull/209)).
211
+
212
+ When using the `single_thread: true` mode, instances of `Datadog::Statsd` are still thread-safe, but you may run into contention on heavily-threaded applications, so we don’t recommend (for performance reasons) reusing these instances.
213
+
214
+ ## Versioning
215
+
216
+ This Ruby gem is using [Semantic Versioning](https://guides.rubygems.org/patterns/#semantic-versioning) but please note that supported Ruby versions can change in a minor release of this library.
217
+ As much as possible, we will add a "future deprecation" message in the minor release preceding the one dropping the support.
218
+
219
+ ## Ruby Versions
220
+
221
+ This gem supports and is tested on Ruby minor versions 2.1 through 3.1.
222
+ Support for Ruby 2.0 was dropped in version 5.4.0.
86
223
 
87
224
  ## Credits
88
225
 
89
- dogstatsd-ruby is forked from Rien Henrichs [original Statsd
90
- client](https://github.com/reinh/statsd).
226
+ dogstatsd-ruby is forked from Rein Henrichs' [original Statsd client](https://github.com/reinh/statsd).
91
227
 
92
228
  Copyright (c) 2011 Rein Henrichs. See LICENSE.txt for
93
229
  further details.
@@ -3,32 +3,24 @@
3
3
  module Datadog
4
4
  class Statsd
5
5
  class Connection
6
- def initialize(telemetry)
6
+ def initialize(telemetry: nil, logger: nil)
7
7
  @telemetry = telemetry
8
+ @logger = logger
8
9
  end
9
10
 
10
- # Close the underlying socket
11
- def close
12
- begin
13
- @socket && @socket.close if instance_variable_defined?(:@socket)
14
- rescue StandardError => boom
15
- logger.error { "Statsd: #{boom.class} #{boom}" } if logger
16
- end
17
- @socket = nil
11
+ def reset_telemetry
12
+ telemetry.reset
18
13
  end
19
14
 
15
+ # not thread safe: `Sender` instances that use this are required to properly synchronize or sequence calls to this method
20
16
  def write(payload)
21
17
  logger.debug { "Statsd: #{payload}" } if logger
22
18
 
23
- flush_telemetry = telemetry.flush?
24
-
25
- payload += telemetry.flush if flush_telemetry
26
-
27
19
  send_message(payload)
28
20
 
29
- telemetry.reset if flush_telemetry
21
+ telemetry.sent(packets: 1, bytes: payload.length) if telemetry
30
22
 
31
- telemetry.sent(packets: 1, bytes: payload.length)
23
+ true
32
24
  rescue StandardError => boom
33
25
  # Try once to reconnect if the socket has been closed
34
26
  retries ||= 1
@@ -39,23 +31,29 @@ module Datadog
39
31
  retries += 1
40
32
  begin
41
33
  close
34
+ connect
42
35
  retry
43
36
  rescue StandardError => e
44
37
  boom = e
45
38
  end
46
39
  end
47
40
 
48
- telemetry.dropped(packets: 1, bytes: payload.length)
41
+ telemetry.dropped_writer(packets: 1, bytes: payload.length) if telemetry
49
42
  logger.error { "Statsd: #{boom.class} #{boom}" } if logger
50
43
  nil
51
44
  end
52
45
 
53
46
  private
47
+
54
48
  attr_reader :telemetry
55
49
  attr_reader :logger
56
50
 
57
- def socket
58
- @socket ||= connect
51
+ def connect
52
+ raise 'Should be implemented by subclass'
53
+ end
54
+
55
+ def close
56
+ raise 'Should be implemented by subclass'
59
57
  end
60
58
  end
61
59
  end
@@ -0,0 +1,76 @@
1
+ module Datadog
2
+ class Statsd
3
+ class ConnectionCfg
4
+ attr_reader :host
5
+ attr_reader :port
6
+ attr_reader :socket_path
7
+ attr_reader :transport_type
8
+
9
+ def initialize(host: nil, port: nil, socket_path: nil)
10
+ initialize_with_constructor_args(host: host, port: port, socket_path: socket_path) ||
11
+ initialize_with_env_vars ||
12
+ initialize_with_defaults
13
+ end
14
+
15
+ def make_connection(**params)
16
+ case @transport_type
17
+ when :udp
18
+ UDPConnection.new(@host, @port, **params)
19
+ when :uds
20
+ UDSConnection.new(@socket_path, **params)
21
+ end
22
+ end
23
+
24
+ private
25
+
26
+ DEFAULT_HOST = '127.0.0.1'
27
+ DEFAULT_PORT = 8125
28
+
29
+ def initialize_with_constructor_args(host: nil, port: nil, socket_path: nil)
30
+ try_initialize_with(host: host, port: port, socket_path: socket_path,
31
+ not_both_error_message:
32
+ "Both UDP: (host/port #{host}:#{port}) and UDS (socket_path #{socket_path}) " +
33
+ "constructor arguments were given. Use only one or the other.",
34
+ )
35
+ end
36
+
37
+ def initialize_with_env_vars()
38
+ try_initialize_with(
39
+ host: ENV['DD_AGENT_HOST'],
40
+ port: ENV['DD_DOGSTATSD_PORT'] && ENV['DD_DOGSTATSD_PORT'].to_i,
41
+ socket_path: ENV['DD_DOGSTATSD_SOCKET'],
42
+ not_both_error_message:
43
+ "Both UDP (DD_AGENT_HOST/DD_DOGSTATSD_PORT #{ENV['DD_AGENT_HOST']}:#{ENV['DD_DOGSTATSD_PORT']}) " +
44
+ "and UDS (DD_DOGSTATSD_SOCKET #{ENV['DD_DOGSTATSD_SOCKET']}) environment variables are set. " +
45
+ "Set only one or the other.",
46
+ )
47
+ end
48
+
49
+ def initialize_with_defaults()
50
+ try_initialize_with(host: DEFAULT_HOST, port: DEFAULT_PORT)
51
+ end
52
+
53
+ def try_initialize_with(host: nil, port: nil, socket_path: nil, not_both_error_message: "")
54
+ if (host || port) && socket_path
55
+ raise ArgumentError, not_both_error_message
56
+ end
57
+
58
+ if host || port
59
+ @host = host || DEFAULT_HOST
60
+ @port = port || DEFAULT_PORT
61
+ @socket_path = nil
62
+ @transport_type = :udp
63
+ return true
64
+ elsif socket_path
65
+ @host = nil
66
+ @port = nil
67
+ @socket_path = socket_path
68
+ @transport_type = :uds
69
+ return true
70
+ end
71
+
72
+ return false
73
+ end
74
+ end
75
+ end
76
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ class Statsd
5
+ class Forwarder
6
+ attr_reader :telemetry
7
+ attr_reader :transport_type
8
+
9
+ def initialize(
10
+ connection_cfg: nil,
11
+
12
+ buffer_max_payload_size: nil,
13
+ buffer_max_pool_size: nil,
14
+ buffer_overflowing_stategy: :drop,
15
+ buffer_flush_interval: nil,
16
+
17
+ sender_queue_size: nil,
18
+
19
+ telemetry_flush_interval: nil,
20
+ global_tags: [],
21
+
22
+ single_thread: false,
23
+
24
+ logger: nil
25
+ )
26
+ @transport_type = connection_cfg.transport_type
27
+
28
+ if telemetry_flush_interval
29
+ @telemetry = Telemetry.new(telemetry_flush_interval,
30
+ global_tags: global_tags,
31
+ transport_type: @transport_type
32
+ )
33
+ end
34
+
35
+ @connection = connection_cfg.make_connection(logger: logger, telemetry: telemetry)
36
+
37
+ # Initialize buffer
38
+ buffer_max_payload_size ||= (@transport_type == :udp ?
39
+ UDP_DEFAULT_BUFFER_SIZE : UDS_DEFAULT_BUFFER_SIZE)
40
+
41
+ if buffer_max_payload_size <= 0
42
+ raise ArgumentError, 'buffer_max_payload_size cannot be <= 0'
43
+ end
44
+
45
+ unless telemetry.nil? || telemetry.would_fit_in?(buffer_max_payload_size)
46
+ raise ArgumentError, "buffer_max_payload_size is not high enough to use telemetry (tags=(#{global_tags.inspect}))"
47
+ end
48
+
49
+ buffer = MessageBuffer.new(@connection,
50
+ max_payload_size: buffer_max_payload_size,
51
+ max_pool_size: buffer_max_pool_size || DEFAULT_BUFFER_POOL_SIZE,
52
+ overflowing_stategy: buffer_overflowing_stategy,
53
+ )
54
+
55
+ sender_queue_size ||= (@transport_type == :udp ?
56
+ UDP_DEFAULT_SENDER_QUEUE_SIZE : UDS_DEFAULT_SENDER_QUEUE_SIZE)
57
+
58
+ @sender = single_thread ?
59
+ SingleThreadSender.new(
60
+ buffer,
61
+ logger: logger,
62
+ flush_interval: buffer_flush_interval) :
63
+ Sender.new(
64
+ buffer,
65
+ logger: logger,
66
+ flush_interval: buffer_flush_interval,
67
+ telemetry: @telemetry,
68
+ queue_size: sender_queue_size)
69
+ @sender.start
70
+ end
71
+
72
+ def send_message(message)
73
+ sender.add(message)
74
+
75
+ tick_telemetry
76
+ end
77
+
78
+ def sync_with_outbound_io
79
+ sender.rendez_vous
80
+ end
81
+
82
+ def flush(flush_telemetry: false, sync: false)
83
+ do_flush_telemetry if telemetry && flush_telemetry
84
+
85
+ sender.flush(sync: sync)
86
+ end
87
+
88
+ def host
89
+ return nil unless transport_type == :udp
90
+
91
+ connection.host
92
+ end
93
+
94
+ def port
95
+ return nil unless transport_type == :udp
96
+
97
+ connection.port
98
+ end
99
+
100
+ def socket_path
101
+ return nil unless transport_type == :uds
102
+
103
+ connection.socket_path
104
+ end
105
+
106
+ def close
107
+ sender.stop
108
+ connection.close
109
+ end
110
+
111
+ private
112
+ attr_reader :sender
113
+ attr_reader :connection
114
+
115
+ def do_flush_telemetry
116
+ telemetry_snapshot = telemetry.flush
117
+ telemetry.reset
118
+
119
+ telemetry_snapshot.each do |message|
120
+ sender.add(message)
121
+ end
122
+ end
123
+
124
+ def tick_telemetry
125
+ return nil unless telemetry
126
+
127
+ do_flush_telemetry if telemetry.should_flush?
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,97 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Datadog
4
+ class Statsd
5
+ class MessageBuffer
6
+ PAYLOAD_SIZE_TOLERANCE = 0.05
7
+
8
+ def initialize(connection,
9
+ max_payload_size: nil,
10
+ max_pool_size: DEFAULT_BUFFER_POOL_SIZE,
11
+ overflowing_stategy: :drop
12
+ )
13
+ raise ArgumentError, 'max_payload_size keyword argument must be provided' unless max_payload_size
14
+ raise ArgumentError, 'max_pool_size keyword argument must be provided' unless max_pool_size
15
+
16
+ @connection = connection
17
+ @max_payload_size = max_payload_size
18
+ @max_pool_size = max_pool_size
19
+ @overflowing_stategy = overflowing_stategy
20
+
21
+ @buffer = String.new
22
+ clear_buffer
23
+ end
24
+
25
+ def add(message)
26
+ message_size = message.bytesize
27
+
28
+ return nil unless message_size > 0 # to avoid adding empty messages to the buffer
29
+ return nil unless ensure_sendable!(message_size)
30
+
31
+ flush if should_flush?(message_size)
32
+
33
+ buffer << "\n" unless buffer.empty?
34
+ buffer << message
35
+
36
+ @message_count += 1
37
+
38
+ # flush when we're pretty sure that we won't be able
39
+ # to add another message to the buffer
40
+ flush if preemptive_flush?
41
+
42
+ true
43
+ end
44
+
45
+ def reset
46
+ clear_buffer
47
+ connection.reset_telemetry
48
+ end
49
+
50
+ def flush
51
+ return if buffer.empty?
52
+
53
+ connection.write(buffer)
54
+ clear_buffer
55
+ end
56
+
57
+ private
58
+
59
+ attr :max_payload_size
60
+ attr :max_pool_size
61
+
62
+ attr :overflowing_stategy
63
+
64
+ attr :connection
65
+ attr :buffer
66
+
67
+ def should_flush?(message_size)
68
+ return true if buffer.bytesize + 1 + message_size >= max_payload_size
69
+
70
+ false
71
+ end
72
+
73
+ def clear_buffer
74
+ buffer.clear
75
+ @message_count = 0
76
+ end
77
+
78
+ def preemptive_flush?
79
+ @message_count == max_pool_size || buffer.bytesize > bytesize_threshold
80
+ end
81
+
82
+ def ensure_sendable!(message_size)
83
+ return true if message_size <= max_payload_size
84
+
85
+ if overflowing_stategy == :raise
86
+ raise Error, 'Message too big for payload limit'
87
+ end
88
+
89
+ false
90
+ end
91
+
92
+ def bytesize_threshold
93
+ @bytesize_threshold ||= (max_payload_size - PAYLOAD_SIZE_TOLERANCE * max_payload_size).to_i
94
+ end
95
+ end
96
+ end
97
+ end