dynoscale_ruby 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e345e1b86543193c0c74bb99d95a9dcc689328c306d658f00028d07781ed53ce
4
+ data.tar.gz: d279fc98ebb9e52b5184bc7070abf37113d4c8e69195d875ac399582d179b352
5
+ SHA512:
6
+ metadata.gz: c309a0e91e54b7c15e97e7a2e226baf0dbedac4ab9f08c9ebcbf2af7780ffaf35cec855785a45cb65590ddc48280cc0e57993cab35519469d490c654662324b6
7
+ data.tar.gz: c5484500c166a50f91117800e4ddf828053a7a195b8832b831388586a3358b7a0d79067e5267e67544dd3f7a9121bf27326203b9f5a3bb6960f35f0fd142f546
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.4.1
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at ericthredsbeard@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,16 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in dynoscale_ruby.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
8
+ gem "vcr", ">= 3.0"
9
+ gem "webmock"
10
+ gem "pry-byebug"
11
+ gem "sidekiq", ">= 5.0"
12
+ gem "delayed_job"
13
+ gem "delayed_job_active_record"
14
+ gem "que"
15
+ gem "resque"
16
+ gem "activesupport"
data/Gemfile.lock ADDED
@@ -0,0 +1,120 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ dynoscale_ruby (1.0.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ activemodel (5.2.6)
10
+ activesupport (= 5.2.6)
11
+ activerecord (5.2.6)
12
+ activemodel (= 5.2.6)
13
+ activesupport (= 5.2.6)
14
+ arel (>= 9.0)
15
+ activesupport (5.2.6)
16
+ concurrent-ruby (~> 1.0, >= 1.0.2)
17
+ i18n (>= 0.7, < 2)
18
+ minitest (~> 5.1)
19
+ tzinfo (~> 1.1)
20
+ addressable (2.8.0)
21
+ public_suffix (>= 2.0.2, < 5.0)
22
+ arel (9.0.0)
23
+ byebug (11.1.3)
24
+ coderay (1.1.3)
25
+ concurrent-ruby (1.1.9)
26
+ connection_pool (2.2.5)
27
+ crack (0.4.5)
28
+ rexml
29
+ delayed_job (4.1.9)
30
+ activesupport (>= 3.0, < 6.2)
31
+ delayed_job_active_record (4.1.6)
32
+ activerecord (>= 3.0, < 6.2)
33
+ delayed_job (>= 3.0, < 5)
34
+ diff-lcs (1.4.4)
35
+ hashdiff (1.0.1)
36
+ i18n (1.8.10)
37
+ concurrent-ruby (~> 1.0)
38
+ method_source (1.0.0)
39
+ minitest (5.14.4)
40
+ mono_logger (1.1.1)
41
+ multi_json (1.15.0)
42
+ mustermann (1.1.1)
43
+ ruby2_keywords (~> 0.0.1)
44
+ pry (0.13.1)
45
+ coderay (~> 1.1)
46
+ method_source (~> 1.0)
47
+ pry-byebug (3.9.0)
48
+ byebug (~> 11.0)
49
+ pry (~> 0.13.0)
50
+ public_suffix (4.0.6)
51
+ que (0.14.3)
52
+ rack (2.2.3)
53
+ rack-protection (2.1.0)
54
+ rack
55
+ rake (12.3.3)
56
+ redis (4.1.4)
57
+ redis-namespace (1.8.1)
58
+ redis (>= 3.0.4)
59
+ resque (2.1.0)
60
+ mono_logger (~> 1.0)
61
+ multi_json (~> 1.0)
62
+ redis-namespace (~> 1.6)
63
+ sinatra (>= 0.9.2)
64
+ vegas (~> 0.1.2)
65
+ rexml (3.2.5)
66
+ rspec (3.10.0)
67
+ rspec-core (~> 3.10.0)
68
+ rspec-expectations (~> 3.10.0)
69
+ rspec-mocks (~> 3.10.0)
70
+ rspec-core (3.10.1)
71
+ rspec-support (~> 3.10.0)
72
+ rspec-expectations (3.10.1)
73
+ diff-lcs (>= 1.2.0, < 2.0)
74
+ rspec-support (~> 3.10.0)
75
+ rspec-mocks (3.10.2)
76
+ diff-lcs (>= 1.2.0, < 2.0)
77
+ rspec-support (~> 3.10.0)
78
+ rspec-support (3.10.2)
79
+ ruby2_keywords (0.0.5)
80
+ sidekiq (5.2.9)
81
+ connection_pool (~> 2.2, >= 2.2.2)
82
+ rack (~> 2.0)
83
+ rack-protection (>= 1.5.0)
84
+ redis (>= 3.3.5, < 4.2)
85
+ sinatra (2.1.0)
86
+ mustermann (~> 1.0)
87
+ rack (~> 2.2)
88
+ rack-protection (= 2.1.0)
89
+ tilt (~> 2.0)
90
+ thread_safe (0.3.6)
91
+ tilt (2.0.10)
92
+ tzinfo (1.2.9)
93
+ thread_safe (~> 0.1)
94
+ vcr (6.0.0)
95
+ vegas (0.1.11)
96
+ rack (>= 1.0.0)
97
+ webmock (3.14.0)
98
+ addressable (>= 2.8.0)
99
+ crack (>= 0.3.2)
100
+ hashdiff (>= 0.4.0, < 2.0.0)
101
+
102
+ PLATFORMS
103
+ x86_64-darwin-18
104
+
105
+ DEPENDENCIES
106
+ activesupport
107
+ delayed_job
108
+ delayed_job_active_record
109
+ dynoscale_ruby!
110
+ pry-byebug
111
+ que
112
+ rake (~> 12.0)
113
+ resque
114
+ rspec (~> 3.0)
115
+ sidekiq (>= 5.0)
116
+ vcr (>= 3.0)
117
+ webmock
118
+
119
+ BUNDLED WITH
120
+ 2.2.27
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 Eric Abrahamsn
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,34 @@
1
+ # Dynoscale Ruby
2
+
3
+ #### Simple yet efficient scaling agent for Ruby/Rails apps on Heroku
4
+
5
+ ## Getting Started
6
+
7
+ 1. Add __dynoscale__ to your app on Heroku: `heroku addons:create dscale`
8
+ 2. Add the agent Gem to your Gemfile: `gem 'dynoscale_ruby'`
9
+ 3. Run bundle: `bundle install`
10
+ 4. Profit! (Literally, this will save you money 😏
11
+
12
+ The environment variable `DYNOSCALE_URL` must be set in order for your application to communicate with Dynoscale Servers.
13
+
14
+ ## Non-Rails Rack Based Apps
15
+
16
+ In addition to the above steps, you will need to `require 'dynoscale_ruby/middleware'` and add the `DynoscaleRuby::Middleware` before the `Rack::Runtime` in your application.
17
+
18
+ ## Data Shared with Dynoscale
19
+
20
+ * Dyno Name
21
+ * Application Name
22
+ * queue measurement data for web and worker dynos
23
+
24
+ ## Worker Adapter
25
+
26
+ In addition to Web scaling, Dynoscale collects data on Worker jobs too. At this time Sidekiq and Resque are currently supported.
27
+
28
+ ## Contributing
29
+
30
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Mjolnir-Software/dynoscale_ruby.
31
+
32
+ ## License
33
+
34
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT)
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "dynoscale_agent"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,31 @@
1
+ require_relative 'lib/dynoscale_ruby/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "dynoscale_ruby"
5
+ spec.version = DynoscaleRuby::VERSION
6
+ spec.authors = ["Eric Abrahamsen"]
7
+ spec.email = ["eric@dynoscale.net"]
8
+
9
+ spec.summary = "This gem is an agent for the Dynoscale Heroku add-on."
10
+ spec.homepage = "https://www.dynoscale.net"
11
+ spec.license = "MIT"
12
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
13
+
14
+ spec.metadata = {
15
+ "homepage_uri" => "https://dynoscale.net",
16
+ "bug_tracker_uri" => "https://github.com/Mjolnir-Software/dynoscale_ruby/issues",
17
+ "documentation_uri" => "https://dynoscale.net/getting_started",
18
+ "changelog_uri" => "https://github.com/Mjolnir-Software/dynoscale_ruby/blob/master/CHANGELOG.md",
19
+ "source_code_uri" => "https://github.com/Mjolnir-Software/dynoscale_ruby",
20
+ }
21
+
22
+ spec.version = '1.0.1'
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
27
+ end
28
+ spec.bindir = "exe"
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ["lib"]
31
+ end
@@ -0,0 +1,49 @@
1
+ require 'uri'
2
+ require 'net/http'
3
+ require 'net/https'
4
+ require 'json'
5
+
6
+ module DynoscaleRuby
7
+ class ApiWrapper
8
+ def initialize(dyno, url, app_name)
9
+ @dyno = dyno
10
+ @url = URI(url)
11
+ @app_name = app_name
12
+ end
13
+
14
+ def publish_reports(reports, current_time = Time.now, http = Net::HTTP.new(@url.host, @url.port), &block)
15
+ headers = { "Content-Type": "text/csv",
16
+ "User-Agent": "dynoscale-ruby;#{Gem.loaded_specs["dynoscale_ruby"].version.to_s}",
17
+ "X_REQUEST_START": "t=#{current_time.to_i}",
18
+ "X_DYNO": @dyno,
19
+ "X_APP_NAME": @app_name
20
+ }
21
+
22
+ body = reports.reduce(""){|t, r| "#{t}#{r.to_csv}"}
23
+
24
+ begin
25
+ response = request(http, headers, body)
26
+ rescue Timeout::Error, Errno::ECONNRESET, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
27
+ # ignore and let the retry mechanism handle it
28
+ end
29
+
30
+ success = (response&.code&.to_i >= 200 && response&.code&.to_i < 300) || false
31
+
32
+
33
+ config = JSON.parse(response&.body || "{}")["config"] || {}
34
+ published_reports = success ? reports : []
35
+
36
+ block.call(success, published_reports, config)
37
+ end
38
+
39
+ private
40
+
41
+ def request(http, headers, body)
42
+ http.use_ssl = true if @url.scheme == "https"
43
+ request = Net::HTTP::Post.new(@url, headers)
44
+
45
+ request.body = body
46
+ http.request(request)
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,20 @@
1
+ require 'logger'
2
+
3
+ module DynoscaleRuby
4
+ module Logger
5
+
6
+ def self.logger
7
+ @@logger ||= if defined?(Rails)
8
+ Rails.logger
9
+ else
10
+ ::Logger.new(STDOUT)
11
+ end
12
+ if ENV['DYNOSCALE_DEV']
13
+ @@logger.level = ::Logger::DEBUG
14
+ else
15
+ @@logger.level = ::Logger::WARN
16
+ end
17
+ @@logger
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,3 @@
1
+ module DynoscaleRuby
2
+ Measurement = Struct.new(:timestamp, :metric, :source, :metadata)
3
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dynoscale_ruby/request_calculator'
4
+ require 'dynoscale_ruby/reporter'
5
+ require 'dynoscale_ruby/recorder'
6
+ require 'dynoscale_ruby/worker/sidekiq'
7
+ require 'dynoscale_ruby/worker/resque'
8
+ require 'dynoscale_ruby/logger'
9
+
10
+ module DynoscaleRuby
11
+ class Middleware
12
+ include Logger
13
+
14
+ MEASUREMENT_TTL = 5 # minutes
15
+
16
+
17
+ def initialize(app)
18
+ @app = app
19
+ end
20
+
21
+ def call(env)
22
+ is_dev = ENV['DYNOSCALE_DEV'] == 'true'
23
+ dyno = is_dev ? "dev.1" : ENV['DYNO']
24
+
25
+ unless ENV['DYNOSCALE_URL']
26
+ puts "Missing DYNOSCALE_URL environment variable"
27
+ return @app.call(env)
28
+ end
29
+ return @app.call(env) if ENV['SKIP_DYNASCALE_AGENT']
30
+ return @app.call(env) unless is_dev || ENV['DYNO']&.split(".")&.last == "1"
31
+
32
+ request_calculator = RequestCalculator.new(env)
33
+ workers = DynoscaleRuby::Worker.constants.select{|c| DynoscaleRuby::Worker.const_get(c).is_a? Class }.map{|c| DynoscaleRuby::Worker.const_get(c) }
34
+ Recorder.record!(request_calculator, workers)
35
+
36
+ api_wrapper = DynoscaleRuby::ApiWrapper.new(dyno, ENV['DYNOSCALE_URL'], ENV['HEROKU_APP_NAME'])
37
+ Reporter.start!(Recorder, api_wrapper) unless Reporter.running?
38
+
39
+
40
+ @app.call(env)
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dynoscale_ruby/middleware'
4
+
5
+ module DynoscaleAgent
6
+ class Railtie < Rails::Railtie
7
+ initializer "dynoscale_agent.middleware" do |app|
8
+ app.middleware.insert_before Rack::Runtime, DynoscaleRuby::Middleware
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,54 @@
1
+ require 'dynoscale_ruby/report'
2
+ require 'dynoscale_ruby/request_calculator'
3
+ require 'singleton'
4
+ require 'dynoscale_ruby/logger'
5
+
6
+ module DynoscaleRuby
7
+ class Recorder
8
+ include Singleton
9
+ extend Logger
10
+
11
+ REPORT_RECORDING_FREQ = 5 #seconds
12
+
13
+ def self.record!(request_calculator, workers)
14
+ is_dev = ENV['DYNOSCALE_DEV'] == 'true'
15
+ dyno = is_dev ? "dev.1" : ENV['DYNO']
16
+
17
+ queue_time = request_calculator.request_queue_time
18
+ current_time = Time.now
19
+
20
+ @@current_report ||= Report.new(current_time + REPORT_RECORDING_FREQ)
21
+
22
+ if queue_time
23
+ @@current_report.add_measurement(current_time, queue_time, 'web', nil)
24
+ Logger.logger.debug "Web measurement #{current_time}, #{queue_time} recorded in report."
25
+ end
26
+
27
+ workers.each do |worker|
28
+ if worker.enabled?
29
+ queue_latencies = worker.queue_latencies
30
+ queue_latencies.each do |queue, latency, depth|
31
+ @@current_report.add_measurement(current_time, latency, "#{worker.name}:#{queue}", nil)
32
+ Logger.logger.debug "#{worker.name.capitalize} worker measurement #{current_time}, #{latency} recorded in report."
33
+ end
34
+ end
35
+ end
36
+
37
+ @@reports ||= {}
38
+ @@reports[@@current_report.publish_timestamp] = @@current_report
39
+ @@reports.values
40
+ end
41
+
42
+ def self.reports
43
+ @@reports ||= {}
44
+ @@reports.values || []
45
+ end
46
+
47
+ def self.remove_published_reports!(reports)
48
+ reports.each do |report|
49
+ @@current_report = nil if report.publish_timestamp == @@current_report.publish_timestamp
50
+ @@reports.delete(report.publish_timestamp)
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,35 @@
1
+ require 'dynoscale_ruby/measurement'
2
+
3
+ module DynoscaleRuby
4
+ class Report
5
+
6
+ REPORT_TTL = 5 * 60 # minutes
7
+
8
+ attr_reader :publish_timestamp, :measurements
9
+
10
+ def initialize(publish_timestamp)
11
+ @measurements = []
12
+ @publish_timestamp = publish_timestamp
13
+ end
14
+
15
+ def add_measurement(current_time = Time.now, metric, source, metadata)
16
+ @measurements << Measurement.new(current_time.to_i, metric, source, metadata)
17
+ end
18
+
19
+ def add_measurements(measurements)
20
+ @measurements.unshift(*measurements)
21
+ end
22
+
23
+ def ready_to_publish?(current_time = Time.now)
24
+ @measurements.any? && publish_timestamp < current_time
25
+ end
26
+
27
+ def expired?(current_time = Time.now)
28
+ publish_timestamp < (current_time - REPORT_TTL)
29
+ end
30
+
31
+ def to_csv
32
+ @measurements.reduce(""){|t, m| "#{t}#{m.timestamp},#{m.metric},#{m.source},#{m.metadata}\n"}
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,58 @@
1
+ require 'dynoscale_ruby/api_wrapper'
2
+ require 'dynoscale_ruby/recorder'
3
+ require 'dynoscale_ruby/logger'
4
+
5
+ module DynoscaleRuby
6
+ class Reporter
7
+ include Singleton
8
+ extend Logger
9
+
10
+ # Production delays
11
+ REPORT_PUBLISH_FREQ = 30 # seconds
12
+ REPORT_PUBLISH_RETRY_FREQ = 15 #seconds
13
+
14
+ def self.start!(recorder, api_wrapper, break_after_first_iteration: false)
15
+ @@reporter_thread ||= Thread.start do
16
+ loop do
17
+ if recorder.reports.any?(&:ready_to_publish?)
18
+ api_wrapper.publish_reports(recorder.reports) do |success, published_reports, config|
19
+ if success
20
+ recorder.remove_published_reports!(published_reports)
21
+ @@config = config
22
+ Logger.logger.debug "Report publish was successful"
23
+ sleep report_publish_freq
24
+ else
25
+ Logger.logger.error "Report publish failed"
26
+ sleep report_publish_retry_freq
27
+ end
28
+ end
29
+ else
30
+ sleep report_publish_retry_freq
31
+ end
32
+ break if break_after_first_iteration
33
+ end
34
+ end
35
+ end
36
+
37
+ def self.running?
38
+ @@reporter_thread ||= nil
39
+ !!@@reporter_thread && @@reporter_thread.alive?
40
+ end
41
+
42
+ def self.report_publish_freq
43
+ is_dev = ENV['DYNOSCALE_DEV'] == 'true'
44
+ if is_dev
45
+ 0
46
+ elsif @@config && @@config['publish_frequency']
47
+ @@config['publish_frequency']&.to_i || REPORT_PUBLISH_FREQ
48
+ else
49
+ REPORT_PUBLISH_FREQ
50
+ end
51
+ end
52
+
53
+ def self.report_publish_retry_freq
54
+ is_dev = ENV['DYNOSCALE_DEV'] == 'true'
55
+ is_dev ? 0 : REPORT_PUBLISH_RETRY_FREQ
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,28 @@
1
+ module DynoscaleRuby
2
+ class RequestCalculator
3
+
4
+ def initialize(env)
5
+ @env = env
6
+ end
7
+
8
+ def request_queue_time(time_now = Time.now)
9
+ is_dev = ENV['DYNOSCALE_DEV'] == 'true'
10
+
11
+ if is_dev
12
+ request_start = "#{Time.now - (rand*100).ceil}"
13
+ else
14
+ request_start = @env['HTTP_X_REQUEST_START']
15
+ end
16
+ raise MissingRequestStartError if request_start.nil?
17
+
18
+ request_body_wait = @env['puma.request_body_wait'] || 0
19
+
20
+ request_start_string = request_start.match(/([0-9])+/)&.[](0)
21
+ start_at = Time.at(request_start_string.to_i / 1000)
22
+
23
+ (time_now - start_at).to_i + request_body_wait.to_i
24
+ end
25
+ end
26
+ class MissingRequestStartError < StandardError
27
+ end
28
+ end
@@ -0,0 +1,3 @@
1
+ module DynoscaleRuby
2
+ VERSION = "1.0.1"
3
+ end
@@ -0,0 +1,32 @@
1
+ require 'singleton'
2
+
3
+ module DynoscaleRuby
4
+ module Worker
5
+ class Resque
6
+ include Singleton
7
+
8
+ def self.enabled?
9
+ require 'resque'
10
+ require 'resque_latency'
11
+ true
12
+ rescue LoadError
13
+ false
14
+ end
15
+
16
+ def self.queue_latencies
17
+ queues.map do |queue|
18
+ [queue.name, (::Resque.latency(queue)* 1000).ceil, ::Resque.size(queue)]
19
+ end
20
+ end
21
+
22
+ def self.queues(source = ::Resque.queues)
23
+ @@queues ||= source
24
+ end
25
+
26
+ def self.name
27
+ 'resque'
28
+ end
29
+ end
30
+ end
31
+ end
32
+
@@ -0,0 +1,30 @@
1
+ require 'singleton'
2
+
3
+ module DynoscaleRuby
4
+ module Worker
5
+ class Sidekiq
6
+ include Singleton
7
+
8
+ def self.enabled?
9
+ require 'sidekiq/api'
10
+ true
11
+ rescue LoadError
12
+ false
13
+ end
14
+
15
+ def self.queue_latencies
16
+ queues.map do |queue|
17
+ [queue.name, (queue.latency * 1000).ceil, queue.size]
18
+ end
19
+ end
20
+
21
+ def self.queues(source = ::Sidekiq::Queue.all)
22
+ @@queues ||= source
23
+ end
24
+
25
+ def self.name
26
+ 'sidekiq'
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'dynoscale_ruby/version'
4
+ require 'dynoscale_ruby/railtie' if defined?(Rails::Railtie) && Rails::Railtie.respond_to?(:initializer)
5
+
6
+ module DynoscaleRuby
7
+ class Error < StandardError; end
8
+ end
@@ -0,0 +1,48 @@
1
+ module Resque
2
+
3
+ def Job.create(queue, klass, *args)
4
+ Resque.validate(klass, queue)
5
+
6
+ if Resque.inline?
7
+ new(:inline, {'class' => klass, 'args' => decode(encode(args)), 'timestamp' => Time.now.utc.to_i}).perform
8
+ else
9
+ Resque.push(queue, 'class' => klass.to_s, 'args' => args, 'timestamp' => Time.now.utc.to_i)
10
+ end
11
+ end
12
+
13
+ def Job.new(queue, payload)
14
+ key = ['latency', queue].join(':')
15
+
16
+ enqueue_time = payload.is_a?(Hash) ? payload['timestamp'] : 0
17
+
18
+ latency = Time.now.utc.to_i - enqueue_time.to_i
19
+ redis = Resque.redis
20
+ redis.set key, [ latency.to_s, Time.now.utc.to_i ].join(':')
21
+
22
+ super
23
+ end
24
+
25
+ def latency(queue)
26
+ redis = Resque.redis
27
+ l = redis.get("latency:#{queue}")
28
+
29
+ return nil if l.nil?
30
+
31
+ l = l.split(':').first.to_i
32
+
33
+ return 0 if l <= 0
34
+
35
+ l
36
+ end
37
+
38
+ def latency_updated_at(queue)
39
+ redis = Resque.redis
40
+ l = redis.get("latency:#{queue}")
41
+
42
+ return nil if l.nil?
43
+
44
+ Time.at(l.split(':').last.to_i)
45
+ end
46
+ end
47
+
48
+
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: dynoscale_ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Eric Abrahamsen
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-02-23 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description:
14
+ email:
15
+ - eric@dynoscale.net
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".gitignore"
21
+ - ".rspec"
22
+ - ".travis.yml"
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - Gemfile.lock
26
+ - LICENSE.txt
27
+ - README.md
28
+ - Rakefile
29
+ - bin/console
30
+ - bin/setup
31
+ - dynoscale_ruby.gemspec
32
+ - lib/dynoscale_ruby.rb
33
+ - lib/dynoscale_ruby/api_wrapper.rb
34
+ - lib/dynoscale_ruby/logger.rb
35
+ - lib/dynoscale_ruby/measurement.rb
36
+ - lib/dynoscale_ruby/middleware.rb
37
+ - lib/dynoscale_ruby/railtie.rb
38
+ - lib/dynoscale_ruby/recorder.rb
39
+ - lib/dynoscale_ruby/report.rb
40
+ - lib/dynoscale_ruby/reporter.rb
41
+ - lib/dynoscale_ruby/request_calculator.rb
42
+ - lib/dynoscale_ruby/version.rb
43
+ - lib/dynoscale_ruby/worker/resque.rb
44
+ - lib/dynoscale_ruby/worker/sidekiq.rb
45
+ - lib/resque_latency.rb
46
+ homepage: https://www.dynoscale.net
47
+ licenses:
48
+ - MIT
49
+ metadata:
50
+ homepage_uri: https://dynoscale.net
51
+ bug_tracker_uri: https://github.com/Mjolnir-Software/dynoscale_ruby/issues
52
+ documentation_uri: https://dynoscale.net/getting_started
53
+ changelog_uri: https://github.com/Mjolnir-Software/dynoscale_ruby/blob/master/CHANGELOG.md
54
+ source_code_uri: https://github.com/Mjolnir-Software/dynoscale_ruby
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 2.3.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.1.4
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: This gem is an agent for the Dynoscale Heroku add-on.
74
+ test_files: []