ddmetrics-1.0.1/0000755000175000017500000000000013336511551013050 5ustar boutilboutilddmetrics-1.0.1/Rakefile0000644000175000017500000000051313336511551014514 0ustar boutilboutil# frozen_string_literal: true require 'rubocop/rake_task' require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) do |t| t.verbose = false end task :test_samples do sh 'bundle exec ruby samples/cache.rb > /dev/null' end RuboCop::RakeTask.new(:rubocop) task default: :test task test: %i[spec rubocop test_samples] ddmetrics-1.0.1/.travis.yml0000644000175000017500000000031713336511551015162 0ustar boutilboutillanguage: ruby rvm: - "2.3" - "2.4" - "2.5" branches: only: - "master" before_install: - gem update --system - gem install bundler -v 1.16.0 cache: bundler sudo: false git: depth: 10 ddmetrics-1.0.1/ddmetrics.gemspec0000644000175000017500000000107513336511551016376 0ustar boutilboutil# frozen_string_literal: true require_relative 'lib/ddmetrics/version' Gem::Specification.new do |spec| spec.name = 'ddmetrics' spec.version = DDMetrics::VERSION spec.authors = ['Denis Defreyne'] spec.email = ['denis+rubygems@denis.ws'] spec.summary = 'Non-timeseries measurements for Ruby programs' spec.homepage = 'https://github.com/ddfreyne/ddmetrics' spec.license = 'MIT' spec.required_ruby_version = '>= 2.3.0' spec.files = `git ls-files -z`.split("\x0") spec.require_paths = ['lib'] end ddmetrics-1.0.1/.rspec0000644000175000017500000000006113336511551014162 0ustar boutilboutil-r ./spec/spec_helper.rb --format Fuubar --color ddmetrics-1.0.1/README.md0000644000175000017500000001517113336511551014334 0ustar boutilboutil[![Gem version](https://img.shields.io/gem/v/ddmetrics.svg)](http://rubygems.org/gems/ddmetrics) [![Gem downloads](https://img.shields.io/gem/dt/ddmetrics.svg)](http://rubygems.org/gems/ddmetrics) [![Build status](https://img.shields.io/travis/ddfreyne/ddmetrics.svg)](https://travis-ci.org/ddfreyne/ddmetrics) [![Code Climate](https://img.shields.io/codeclimate/github/ddfreyne/ddmetrics.svg)](https://codeclimate.com/github/ddfreyne/ddmetrics) [![Code Coverage](https://img.shields.io/codecov/c/github/ddfreyne/ddmetrics.svg)](https://codecov.io/gh/ddfreyne/ddmetrics) # DDMetrics _DDMetrics_ is a Ruby library for recording and analysing measurements in short-running Ruby processes. If you are looking for a full-featured timeseries monitoring system, look no further than [Prometheus](https://prometheus.io/). ## Example Take the following (naïve) cache implementation as a starting point: ```ruby class Cache def initialize @map = {} end def []=(key, value) @map[key] = value end def [](key) @map[key] end end ``` To start instrumenting this code, require `ddmetrics`, create a counter, and record some metrics: ```ruby require 'ddmetrics' class Cache attr_reader :counter def initialize @map = {} @counter = DDMetrics::Counter.new end def []=(key, value) @counter.increment(type: :set) @map[key] = value end def [](key) if @map.key?(key) @counter.increment(type: :get_hit) else @counter.increment(type: :get_miss) end @map[key] end end ``` Let’s construct a cache and exercise it: ```ruby cache = Cache.new cache['greeting'] cache['greeting'] cache['greeting'] = 'Hi there!' cache['greeting'] cache['greeting'] cache['greeting'] ``` Finally, get the recorded values: ```ruby cache.counter.get(type: :set) # => 1 cache.counter.get(type: :get_hit) # => 3 cache.counter.get(type: :get_miss) # => 2 ``` Or even print all stats: ```ruby puts cache.counter ``` ``` type │ count ─────────┼────── get_hit │ 3 get_miss │ 2 set │ 1 ``` ## Scope * No timeseries: Metrics are not recorded over time. If you want to record timeseries data, consider using [Prometheus](https://prometheus.io/). * Not intended for long-running processes: Metrics data (particularly summary metrics) can accumulate in memory and cause memory pressure. This project is not suited for long-running processes, such as servers. For monitoring long-running processes, consider using [Prometheus](https://prometheus.io/). * Not thread-safe: The implementation is not thread-safe. If you require thread safety, consider wrapping the functionality provided. ## Installation Add this line to your application's Gemfile: ```ruby gem 'ddmetrics' ``` And then execute: $ bundle Or install it yourself as: $ gem install ddmetrics ## Usage _DDMetrics_ provides two metric types: * A **counter** is an integer metric that only ever increases. Examples: cache hits, number of files written, … * A **summary** records observations, and provides functionality for describing the distribution of the observations through quantiles. Examples: outgoing request durations, size of written files, … Each metric is recorded with a label, which is a hash that is useful to further refine the kind of data that is being recorded. For example: ```ruby cache_hits_counter.increment(target: :file_cache) request_durations_summary.observe(1.07, api: :weather) ``` ### Counters To create a counter, instantiate `DDMetrics::Counter`: ```ruby counter = DDMetrics::Counter.new ``` To increment a counter, call `#increment` with a label: ```ruby counter.increment(target: :file_cache) ``` To get the value for a certain label, use `#get`: ```ruby counter.get(target: :file_cache) # => 1 ``` ### Summaries To create a summary, instantiate `DDMetrics::Summary`: ```ruby summary = DDMetrics::Summary.new ``` To observe a value, call `#observe` with the value to observe, along with a label: ```ruby summary.observe(0.88, api: :weather) summary.observe(1.07, api: :weather) summary.observe(0.91, api: :weather) ``` To get the list of observations for a certain label, use `#get`, which will return a `DDMetrics::Stats` instance: ```ruby summary.get(api: :weather) # => ``` The following methods are available on `DDMetrics::Stats`: * `#count`: returns the number of values * `#sum`: returns the sum of all values * `#avg`: returns the average of all values * `#min`: returns the minimum value * `#max`: returns the maximum value * `#quantile(fraction)`: returns the quantile at the given fraction (0.0 – 1.0) ### Printing metrics To print a metric, use `#to_s`. For example: ```ruby summary = DDMetrics::Summary.new summary.observe(2.1, filter: :erb) summary.observe(4.1, filter: :erb) summary.observe(5.3, filter: :haml) puts summary ``` Output: ``` filter │ count min .50 .90 .95 max tot ───────┼──────────────────────────────────────────────── erb │ 2 2.10 3.10 3.90 4.00 4.10 6.20 haml │ 1 5.30 5.30 5.30 5.30 5.30 5.30 ``` ### Stopwatch The `DDMetrics::Stopwatch` class can be used to measure durations. Use `#start` and `#stop` to start and stop the stopwatch, respectively, and `#duration` to read the value of the stopwatch: ```ruby stopwatch = DDMetrics::Stopwatch.new stopwatch.start sleep 1 stopwatch.stop puts "That took #{stopwatch.duration}s." # Output: That took 1.006831s. ``` A stopwatch, once created, will never reset its duration. Running the stopwatch again will add to the existing duration: ```ruby stopwatch.start sleep 1 stopwatch.stop puts "That took #{stopwatch.duration}s." # Output: That took 2.012879s. ``` You can query whether or not a stopwatch is running using `#running?`; `#stopped?` is the opposite of `#running?`. ## Development Install dependencies: $ bundle Run tests: $ bundle exec rake ## Contributing Bug reports and pull requests are welcome on GitHub at https://github.com/ddfreyne/ddmetrics. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. ## License The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). ## Code of Conduct Everyone interacting in the DDMetrics project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/ddfreyne/ddmetrics/blob/master/CODE_OF_CONDUCT.md). ddmetrics-1.0.1/.gitignore0000644000175000017500000000006313336511551015037 0ustar boutilboutil.DS_Store *.gem /.vscode/ /coverage/ /Gemfile.lock ddmetrics-1.0.1/Gemfile0000644000175000017500000000035413336511551014345 0ustar boutilboutil# frozen_string_literal: true source 'https://rubygems.org' gemspec group :devel do gem 'codecov', require: false gem 'fuubar' gem 'rake' gem 'rspec' gem 'rspec-its' gem 'rubocop', '~> 0.52' gem 'timecop', '~> 0.9' end ddmetrics-1.0.1/CODE_OF_CONDUCT.md0000644000175000017500000000624413336511551015655 0ustar boutilboutil# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at denis.defreyne@stoneship.org. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ ddmetrics-1.0.1/scripts/0000755000175000017500000000000013336511551014537 5ustar boutilboutilddmetrics-1.0.1/scripts/release0000755000175000017500000000530613336511551016111 0ustar boutilboutil#!/usr/bin/env ruby # frozen_string_literal: true require 'fileutils' require 'json' require 'netrc' require 'octokit' require 'shellwords' require 'uri' def run(*args) puts(' ' + args.map { |s| Shellwords.escape(s) }.join(' ')) system(*args) end gem_name = 'ddmetrics' version_constant = 'DDMetrics::VERSION' gem_path = 'ddmetrics' puts '=== Logging in to GitHub’s API…' client = Octokit::Client.new(netrc: true) puts puts '=== Deleting old *.gem files…' Dir['*.gem'].each do |fn| puts "deleting #{fn}…" FileUtils.rm_f(fn) end puts puts '=== Verifying presence of release date…' unless File.readlines('NEWS.md').drop(2).first =~ / \(\d{4}-\d{2}-\d{2}\)$/ warn 'No proper release date found!' exit 1 end puts puts '=== Reading version…' require "./lib/#{gem_path}/version" version = eval(version_constant) # rubocop:disable Security/Eval puts "Version = #{version}" puts puts '=== Building new gem…' run('gem', 'build', 'ddmetrics.gemspec') puts puts '=== Verifying that gems were built properly…' gem_filename = "#{gem_name}-#{version}.gem" unless File.file?(gem_filename) warn "Error: Could not find gem: #{gem_filename}" exit 1 end puts puts '=== Verifying that gem version does not yet exist…' url = URI.parse("https://rubygems.org/api/v1/versions/#{gem_name}.json") response = Net::HTTP.get_response(url) existing_versions = case response.code when '404' [] when '200' JSON.parse(response.body).map { |e| e.fetch('number') } else warn "Error: Couldn’t fetch version information for #{gem_name} (status #{response.code})" exit 1 end if existing_versions.include?(version) warn "Error: #{gem_name} v#{version} already exists" exit 1 end puts puts '=== Verifying that release does not yet exist…' releases = client.releases('ddfreyne/ddmetrics') release = releases.find { |r| r.tag_name == DDMetrics::VERSION } if release warn 'Release already exists!' warn 'ABORTED!' exit 1 end puts puts '=== Creating Git tag…' run('git', 'tag', '--sign', '--annotate', DDMetrics::VERSION, '--message', "Version #{DDMetrics::VERSION}") puts puts '=== Pushing Git data…' run('git', 'push', 'origin', '--tags') puts puts '=== Pushing gem…' run('gem', 'push', "ddmetrics-#{DDMetrics::VERSION}.gem") puts puts '=== Reading release notes…' release_notes = File.readlines('NEWS.md') .drop(4) .take_while { |l| l !~ /^## / } .join puts puts '=== Creating release on GitHub…' sleep 3 # Give GitHub some time to detect the new tag is_prerelease = DDMetrics::VERSION =~ /a|b|rc/ || DDMetrics::VERSION =~ /^0/ client.create_release( 'ddfreyne/ddmetrics', DDMetrics::VERSION, prerelease: !is_prerelease.nil?, body: release_notes ) puts puts 'DONE!' ddmetrics-1.0.1/NEWS.md0000644000175000017500000000063213336511551014147 0ustar boutilboutil# DDMetrics news ## 1.0.1 (2018-07-19) Enhancements: * Improved formatting of labels in tables (#7) ## 1.0.0 (2018-01-07) (identical to 1.0.0rc1) ## 1.0.0rc1 (2018-01-04) Changes: * Renamed to DDMetrics (from DDTelemetry) ## 1.0.0a3 (2017-12-25) Changes: * Made labels be a hash ## 1.0.0a2 (2017-12-18) Changes: * Many API changes to make usage simpler ## 1.0.0a1 (2017-12-02) Initial release. ddmetrics-1.0.1/samples/0000755000175000017500000000000013336511551014514 5ustar boutilboutilddmetrics-1.0.1/samples/cache.rb0000644000175000017500000000127713336511551016113 0ustar boutilboutil# frozen_string_literal: true require 'ddmetrics' class Cache attr_reader :counter def initialize @map = {} @counter = DDMetrics::Counter.new end def []=(key, value) @counter.increment(type: :set) @map[key] = value end def [](key) if @map.key?(key) @counter.increment(type: :get_hit) else @counter.increment(type: :get_miss) end @map[key] end end cache = Cache.new cache['greeting'] cache['greeting'] cache['greeting'] = 'Hi there!' cache['greeting'] cache['greeting'] cache['greeting'] p cache.counter.get(type: :set) # => 1 p cache.counter.get(type: :get_hit) # => 3 p cache.counter.get(type: :get_miss) # => 2 puts cache.counter ddmetrics-1.0.1/lib/0000755000175000017500000000000013336511551013616 5ustar boutilboutilddmetrics-1.0.1/lib/ddmetrics/0000755000175000017500000000000013336511551015574 5ustar boutilboutilddmetrics-1.0.1/lib/ddmetrics/printer.rb0000644000175000017500000000252313336511551017606 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Printer def summary_to_s(summary) table_for_summary(summary).to_s end def counter_to_s(counter) table_for_counter(counter).to_s end private def table_for_summary(summary) header_labels = nil headers = ['count', 'min', '.50', '.90', '.95', 'max', 'tot'] rows = summary.labels.map do |label| header_labels ||= label.to_a.sort.map(&:first).map(&:to_s) stats = summary.get(label) count = stats.count min = stats.min p50 = stats.quantile(0.50) p90 = stats.quantile(0.90) p95 = stats.quantile(0.95) tot = stats.sum max = stats.max label.to_a.sort.map(&:last).map(&:to_s) + [count.to_s] + [min, p50, p90, p95, max, tot].map { |r| format('%4.2f', r) } end DDMetrics::Table.new([header_labels + headers] + rows, num_headers: header_labels.size) end def table_for_counter(counter) header_labels = nil headers = ['count'] rows = counter.labels.map do |label| header_labels ||= label.to_a.sort.map(&:first).map(&:to_s) label.to_a.sort.map(&:last).map(&:to_s) + [counter.get(label).to_s] end DDMetrics::Table.new([header_labels + headers] + rows, num_headers: header_labels.size) end end end ddmetrics-1.0.1/lib/ddmetrics/stopwatch.rb0000644000175000017500000000172513336511551020142 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Stopwatch class AlreadyRunningError < StandardError def message 'Cannot start, because stopwatch is already running' end end class NotRunningError < StandardError def message 'Cannot stop, because stopwatch is not running' end end class StillRunningError < StandardError def message 'Cannot get duration, because stopwatch is still running' end end def initialize @duration = 0.0 @last_start = nil end def start raise AlreadyRunningError if running? @last_start = Time.now end def stop raise NotRunningError unless running? @duration += (Time.now - @last_start) @last_start = nil end def duration raise StillRunningError if running? @duration end def running? !@last_start.nil? end def stopped? !running? end end end ddmetrics-1.0.1/lib/ddmetrics/version.rb0000644000175000017500000000011013336511551017576 0ustar boutilboutil# frozen_string_literal: true module DDMetrics VERSION = '1.0.1' end ddmetrics-1.0.1/lib/ddmetrics/counter.rb0000644000175000017500000000056613336511551017607 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Counter < Metric def increment(label) validate_label(label) basic_metric_for(label, BasicCounter).increment end def get(label) validate_label(label) basic_metric_for(label, BasicCounter).value end def to_s DDMetrics::Printer.new.counter_to_s(self) end end end ddmetrics-1.0.1/lib/ddmetrics/stats.rb0000644000175000017500000000160313336511551017257 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Stats class EmptyError < StandardError def message 'Not enough data to perform calculation' end end def initialize(values) @values = values end def inspect "<#{self.class} count=#{count}>" end def count @values.size end def sum raise EmptyError if @values.empty? @values.reduce(:+) end def avg sum.to_f / count end def min quantile(0.0) end def max quantile(1.0) end def quantile(fraction) raise EmptyError if @values.empty? target = (@values.size - 1) * fraction.to_f interp = target % 1.0 sorted_values[target.floor] * (1.0 - interp) + sorted_values[target.ceil] * interp end private def sorted_values @sorted_values ||= @values.sort end end end ddmetrics-1.0.1/lib/ddmetrics/table.rb0000644000175000017500000000223113336511551017206 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Table def initialize(rows, num_headers: 1) @rows = rows @num_headers = num_headers end def to_s columns = @rows.transpose column_lengths = columns.map { |c| c.map(&:size).max } [].tap do |lines| # header lines << row_to_s(@rows[0], column_lengths) # separator lines << separator(column_lengths) # body rows = sort_rows(@rows.drop(1)) lines.concat(rows.map { |r| row_to_s(r, column_lengths) }) end.join("\n") end private def sort_rows(rows) rows.sort_by { |r| r.first.downcase } end def row_to_s(row, column_lengths) values = row.zip(column_lengths).map { |text, length| text.rjust(length) } values.take(@num_headers).join(' ') + ' │ ' + values.drop(@num_headers).join(' ') end def separator(column_lengths) (+'').tap do |s| s << column_lengths.take(@num_headers).map { |l| '─' * l }.join('───') s << '─┼─' s << column_lengths.drop(@num_headers).map { |l| '─' * l }.join('───') end end end end ddmetrics-1.0.1/lib/ddmetrics/basic_summary.rb0000644000175000017500000000031513336511551020756 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class BasicSummary attr_reader :values def initialize @values = [] end def observe(value) @values << value end end end ddmetrics-1.0.1/lib/ddmetrics/metric.rb0000644000175000017500000000125013336511551017402 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Metric include Enumerable def initialize @basic_metrics = {} end def get(label) basic_metric_for(label, BasicCounter) end def labels @basic_metrics.keys end def each @basic_metrics.each_key do |label| yield(label, get(label)) end end # @api private def basic_metric_for(label, basic_class) @basic_metrics.fetch(label) { @basic_metrics[label] = basic_class.new } end # @api private def validate_label(label) return if label.is_a?(Hash) raise ArgumentError, 'label argument must be a hash' end end end ddmetrics-1.0.1/lib/ddmetrics/summary.rb0000644000175000017500000000065513336511551017624 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class Summary < Metric def observe(value, label) validate_label(label) basic_metric_for(label, BasicSummary).observe(value) end def get(label) validate_label(label) values = basic_metric_for(label, BasicSummary).values DDMetrics::Stats.new(values) end def to_s DDMetrics::Printer.new.summary_to_s(self) end end end ddmetrics-1.0.1/lib/ddmetrics/basic_counter.rb0000644000175000017500000000030013336511551020732 0ustar boutilboutil# frozen_string_literal: true module DDMetrics class BasicCounter attr_reader :value def initialize @value = 0 end def increment @value += 1 end end end ddmetrics-1.0.1/lib/ddmetrics.rb0000644000175000017500000000066413336511551016127 0ustar boutilboutil# frozen_string_literal: true require_relative 'ddmetrics/version' module DDMetrics end require_relative 'ddmetrics/basic_counter' require_relative 'ddmetrics/basic_summary' require_relative 'ddmetrics/metric' require_relative 'ddmetrics/counter' require_relative 'ddmetrics/summary' require_relative 'ddmetrics/stopwatch' require_relative 'ddmetrics/table' require_relative 'ddmetrics/printer' require_relative 'ddmetrics/stats' ddmetrics-1.0.1/spec/0000755000175000017500000000000013336511551014002 5ustar boutilboutilddmetrics-1.0.1/spec/spec_helper.rb0000644000175000017500000000047613336511551016627 0ustar boutilboutil# frozen_string_literal: true require 'simplecov' SimpleCov.start require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov require 'ddmetrics' require 'fuubar' require 'rspec/its' require 'timecop' RSpec.configure do |c| c.fuubar_progress_bar_options = { format: '%c/%C |<%b>%i| %p%%', } end ddmetrics-1.0.1/spec/ddmetrics/0000755000175000017500000000000013336511551015760 5ustar boutilboutilddmetrics-1.0.1/spec/ddmetrics/basic_counter_spec.rb0000644000175000017500000000056513336511551022145 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::BasicCounter do subject(:counter) { described_class.new } it 'starts at 0' do expect(counter.value).to eq(0) end describe '#increment' do subject { counter.increment } it 'increments' do expect { subject } .to change { counter.value } .from(0) .to(1) end end end ddmetrics-1.0.1/spec/ddmetrics/counter_spec.rb0000644000175000017500000000471013336511551021000 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::Counter do subject(:counter) { described_class.new } describe 'new counter' do it 'starts at 0' do expect(subject.get(filter: :erb)).to eq(0) expect(subject.get(filter: :haml)).to eq(0) end end describe '#increment' do subject { counter.increment(filter: :erb) } it 'increments the matching value' do expect { subject } .to change { counter.get(filter: :erb) } .from(0) .to(1) end it 'does not increment any other value' do expect(counter.get(filter: :haml)).to eq(0) expect { subject } .not_to change { counter.get(filter: :haml) } end context 'non-hash label' do subject { counter.increment('WRONG UGH') } it 'errors' do expect { subject }.to raise_error(ArgumentError, 'label argument must be a hash') end end end describe '#get' do subject { counter.get(filter: :erb) } context 'not incremented' do it { is_expected.to eq(0) } end context 'incremented' do before { counter.increment(filter: :erb) } it { is_expected.to eq(1) } end context 'other incremented' do before { counter.increment(filter: :haml) } it { is_expected.to eq(0) } end end describe '#labels' do subject { counter.labels } before do counter.increment(filter: :erb) counter.increment(filter: :erb) counter.increment(filter: :haml) end it { is_expected.to match_array([{ filter: :haml }, { filter: :erb }]) } end describe '#each' do subject do {}.tap do |res| counter.each { |label, count| res[label] = count } end end before do counter.increment(filter: :erb) counter.increment(filter: :erb) counter.increment(filter: :haml) end it { is_expected.to eq({ filter: :haml } => 1, { filter: :erb } => 2) } it 'is enumerable' do expect(counter.map { |_label, count| count }.sort) .to eq([1, 2]) end end describe '#to_s' do subject { counter.to_s } before do counter.increment(filter: :erb) counter.increment(filter: :erb) counter.increment(filter: :haml) end it 'returns table' do expected = <<~TABLE filter │ count ───────┼────── erb │ 2 haml │ 1 TABLE expect(subject.strip).to eq(expected.strip) end end end ddmetrics-1.0.1/spec/ddmetrics/table_spec.rb0000644000175000017500000000175313336511551020414 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::Table do let(:table) { described_class.new(rows) } let(:rows) do [ %w[name awesomeness], %w[denis high], %w[REDACTED low], ] end example do expect(table.to_s).to eq(<<~TABLE.rstrip) name │ awesomeness ─────────┼──────────── denis │ high REDACTED │ low TABLE end context 'unsorted data' do let(:rows) do [ %w[name awesomeness], %w[ccc highc], %w[bbb highb], %w[ddd highd], %w[eee highe], %w[aaa higha], ] end example do expect(table.to_s).to eq(<<~TABLE.rstrip) name │ awesomeness ─────┼──────────── aaa │ higha bbb │ highb ccc │ highc ddd │ highd eee │ highe TABLE end end end ddmetrics-1.0.1/spec/ddmetrics/basic_summary_spec.rb0000644000175000017500000000074513336511551022163 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::BasicSummary do subject(:summary) { described_class.new } context 'no observations' do its(:values) { is_expected.to be_empty } end context 'one observation' do before { subject.observe(2.1) } its(:values) { is_expected.to eq([2.1]) } end context 'two observations' do before do subject.observe(2.1) subject.observe(4.1) end its(:values) { is_expected.to eq([2.1, 4.1]) } end end ddmetrics-1.0.1/spec/ddmetrics/stats_spec.rb0000644000175000017500000000547613336511551020471 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::Stats do subject(:stats) { described_class.new(values) } context 'no values' do let(:values) { [] } it 'errors on #min' do expect { subject.min } .to raise_error(DDMetrics::Stats::EmptyError) end it 'errors on #max' do expect { subject.max } .to raise_error(DDMetrics::Stats::EmptyError) end it 'errors on #avg' do expect { subject.avg } .to raise_error(DDMetrics::Stats::EmptyError) end it 'errors on #sum' do expect { subject.sum } .to raise_error(DDMetrics::Stats::EmptyError) end its(:count) { is_expected.to eq(0) } end context 'one value' do let(:values) { [2.1] } its(:inspect) { is_expected.to eq('') } its(:count) { is_expected.to eq(1) } its(:sum) { is_expected.to eq(2.1) } its(:avg) { is_expected.to eq(2.1) } its(:min) { is_expected.to eq(2.1) } its(:max) { is_expected.to eq(2.1) } it 'has proper quantiles' do expect(subject.quantile(0.00)).to eq(2.1) expect(subject.quantile(0.25)).to eq(2.1) expect(subject.quantile(0.50)).to eq(2.1) expect(subject.quantile(0.90)).to eq(2.1) expect(subject.quantile(0.99)).to eq(2.1) end end context 'two values' do let(:values) { [2.1, 4.1] } its(:inspect) { is_expected.to eq('') } its(:count) { is_expected.to be_within(0.000001).of(2) } its(:sum) { is_expected.to be_within(0.000001).of(6.2) } its(:avg) { is_expected.to be_within(0.000001).of(3.1) } its(:min) { is_expected.to be_within(0.000001).of(2.1) } its(:max) { is_expected.to be_within(0.000001).of(4.1) } it 'has proper quantiles' do expect(subject.quantile(0.00)).to be_within(0.000001).of(2.1) expect(subject.quantile(0.25)).to be_within(0.000001).of(2.6) expect(subject.quantile(0.50)).to be_within(0.000001).of(3.1) expect(subject.quantile(0.90)).to be_within(0.000001).of(3.9) expect(subject.quantile(0.99)).to be_within(0.000001).of(4.08) end end context 'integer values' do let(:values) { [1, 2] } its(:count) { is_expected.to be_within(0.000001).of(2) } its(:sum) { is_expected.to be_within(0.000001).of(3) } its(:avg) { is_expected.to be_within(0.000001).of(1.5) } its(:min) { is_expected.to be_within(0.000001).of(1) } its(:max) { is_expected.to be_within(0.000001).of(2) } it 'has proper quantiles' do expect(subject.quantile(0.00)).to be_within(0.000001).of(1.0) expect(subject.quantile(0.25)).to be_within(0.000001).of(1.25) expect(subject.quantile(0.50)).to be_within(0.000001).of(1.5) expect(subject.quantile(0.90)).to be_within(0.000001).of(1.9) expect(subject.quantile(0.99)).to be_within(0.000001).of(1.99) end end end ddmetrics-1.0.1/spec/ddmetrics/stopwatch_spec.rb0000644000175000017500000000360613336511551021340 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::Stopwatch do subject(:stopwatch) { described_class.new } after { Timecop.return } it 'is zero by default' do expect(stopwatch.duration).to eq(0.0) end it 'records correct duration after start+stop' do Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 0)) stopwatch.start Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 1)) stopwatch.stop expect(stopwatch.duration).to eq(1.0) end it 'records correct duration after start+stop+start+stop' do Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 0)) stopwatch.start Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 1)) stopwatch.stop Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 3)) stopwatch.start Timecop.freeze(Time.local(2008, 9, 1, 10, 5, 6)) stopwatch.stop expect(stopwatch.duration).to eq(1.0 + 3.0) end it 'errors when stopping when not started' do expect { stopwatch.stop } .to raise_error( DDMetrics::Stopwatch::NotRunningError, 'Cannot stop, because stopwatch is not running', ) end it 'errors when starting when already started' do stopwatch.start expect { stopwatch.start } .to raise_error( DDMetrics::Stopwatch::AlreadyRunningError, 'Cannot start, because stopwatch is already running', ) end it 'reports running status' do expect(stopwatch).not_to be_running expect(stopwatch).to be_stopped stopwatch.start expect(stopwatch).to be_running expect(stopwatch).not_to be_stopped stopwatch.stop expect(stopwatch).not_to be_running expect(stopwatch).to be_stopped end it 'errors when getting duration while running' do stopwatch.start expect { stopwatch.duration } .to raise_error( DDMetrics::Stopwatch::StillRunningError, 'Cannot get duration, because stopwatch is still running', ) end end ddmetrics-1.0.1/spec/ddmetrics/summary_spec.rb0000644000175000017500000000622713336511551021023 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics::Summary do subject(:summary) { described_class.new } describe '#observe' do context 'non-hash label' do subject { summary.observe(1.23, 'WRONG UGH') } it 'errors' do expect { subject }.to raise_error(ArgumentError, 'label argument must be a hash') end end end describe '#get' do subject { summary.get(filter: :erb) } before do summary.observe(2.1, filter: :erb) summary.observe(4.1, filter: :erb) summary.observe(5.3, filter: :haml) end it { is_expected.to be_a(DDMetrics::Stats) } its(:sum) { is_expected.to eq(2.1 + 4.1) } its(:count) { is_expected.to eq(2) } end describe '#labels' do subject { summary.labels } before do summary.observe(2.1, filter: :erb) summary.observe(4.1, filter: :erb) summary.observe(5.3, filter: :haml) end it { is_expected.to match_array([{ filter: :haml }, { filter: :erb }]) } end describe '#each' do subject do {}.tap do |res| summary.each { |label, stats| res[label] = stats.avg.round(2) } end end before do summary.observe(2.1, filter: :erb) summary.observe(4.1, filter: :erb) summary.observe(5.3, filter: :haml) end it { is_expected.to eq({ filter: :haml } => 5.3, { filter: :erb } => 3.1) } it 'is enumerable' do expect(summary.map { |_label, stats| stats.sum }.sort) .to eq([5.3, 2.1 + 4.1]) end end describe '#to_s' do subject { summary.to_s } context 'one label' do before do summary.observe(2.1, filter: :erb) summary.observe(4.1, filter: :erb) summary.observe(5.3, filter: :haml) end it 'returns table' do expected = <<~TABLE filter │ count min .50 .90 .95 max tot ───────┼──────────────────────────────────────────────── erb │ 2 2.10 3.10 3.90 4.00 4.10 6.20 haml │ 1 5.30 5.30 5.30 5.30 5.30 5.30 TABLE expect(subject.strip).to eq(expected.strip) end end context 'multiple labels' do before do summary.observe(2.1, filter: :erb, stage: :pre) summary.observe(4.1, filter: :erb, stage: :pre) summary.observe(1.2, filter: :erb, stage: :post) summary.observe(5.3, filter: :haml, stage: :post) end it 'returns table' do expected = <<~TABLE filter stage │ count min .50 .90 .95 max tot ───────────────┼──────────────────────────────────────────────── erb pre │ 2 2.10 3.10 3.90 4.00 4.10 6.20 erb post │ 1 1.20 1.20 1.20 1.20 1.20 1.20 haml post │ 1 5.30 5.30 5.30 5.30 5.30 5.30 TABLE expect(subject.strip).to eq(expected.strip) end end end end ddmetrics-1.0.1/spec/ddmetrics_spec.rb0000644000175000017500000000021313336511551017313 0ustar boutilboutil# frozen_string_literal: true describe DDMetrics do it 'has a version number' do expect(DDMetrics::VERSION).not_to be nil end end ddmetrics-1.0.1/.rubocop.yml0000644000175000017500000000207613336511551015327 0ustar boutilboutil# ----- CONFIGURED ----- AllCops: TargetRubyVersion: 2.3 DisplayCopNames: true Style/TrailingCommaInArguments: EnforcedStyleForMultiline: comma Style/TrailingCommaInArrayLiteral: EnforcedStyleForMultiline: comma Style/TrailingCommaInHashLiteral: EnforcedStyleForMultiline: comma Layout/IndentArray: EnforcedStyle: consistent # Documentation lives elsewhere, and not everything needs to be documented. Style/Documentation: Enabled: false # This doesn’t work well with RSpec. Lint/AmbiguousBlockAssociation: Exclude: - spec/**/*_spec.rb # ----- DISABLED (metrics) ----- # Cops for metrics are disabled because they should not cause tests to fail. Metrics/AbcSize: Enabled: false Metrics/BlockLength: Enabled: false Metrics/BlockNesting: Enabled: false Metrics/ClassLength: Enabled: false Metrics/CyclomaticComplexity: Enabled: false Metrics/LineLength: Enabled: false Metrics/MethodLength: Enabled: false Metrics/ModuleLength: Enabled: false Metrics/ParameterLists: Enabled: false Metrics/PerceivedComplexity: Enabled: false ddmetrics-1.0.1/LICENSE.txt0000644000175000017500000000210013336511551014664 0ustar boutilboutilThe MIT License (MIT) Copyright (c) 2017–2018 Denis Defreyne Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.