|
| 1 | +require 'securerandom' |
| 2 | +require 'digest' |
| 3 | +require 'socket' |
| 4 | +require 'pact/support/metrics' |
| 5 | +require 'pact/mock_service/version' |
| 6 | +require 'net/http' |
| 7 | + |
| 8 | +module Pact |
| 9 | + module Support |
| 10 | + class Metrics |
| 11 | + |
| 12 | + def self.report_metric(event, category, action, value = 1) |
| 13 | + in_thread do |
| 14 | + begin |
| 15 | + if track_events? |
| 16 | + Pact.configuration.output_stream.puts "WARN: Please note: we are tracking events anonymously to gather important usage statistics like Pact-Ruby version and operating system. To disable tracking, set the 'PACT_DO_NOT_TRACK' environment variable to 'true'." |
| 17 | + |
| 18 | + uri = URI('https://www.google-analytics.com/collect') |
| 19 | + req = Net::HTTP::Post.new(uri) |
| 20 | + req.set_form_data(create_tracking_event(event, category, action, value)) |
| 21 | + |
| 22 | + Net::HTTP.start(uri.hostname, uri.port, read_timeout:2, open_timeout:2, :use_ssl => true ) do |http| |
| 23 | + http.request(req) |
| 24 | + end |
| 25 | + end |
| 26 | + rescue StandardError => e |
| 27 | + handle_error(e) |
| 28 | + end |
| 29 | + end |
| 30 | + end |
| 31 | + |
| 32 | + private |
| 33 | + |
| 34 | + def self.handle_error e |
| 35 | + if ENV['PACT_METRICS_DEBUG'] == 'true' |
| 36 | + Pact.configuration.output_stream.puts("DEBUG: #{e.inspect}\n" + e.backtrace.join("\n")) |
| 37 | + end |
| 38 | + end |
| 39 | + |
| 40 | + def self.in_thread |
| 41 | + Thread.new do |
| 42 | + yield |
| 43 | + end |
| 44 | + end |
| 45 | + |
| 46 | + def self.create_tracking_event(event, category, action, value) |
| 47 | + { |
| 48 | + "v" => 1, |
| 49 | + "t" => "event", |
| 50 | + "tid" => "UA-117778936-1", |
| 51 | + "cid" => calculate_cid, |
| 52 | + "an" => "Pact Mock Service", |
| 53 | + "av" => Pact::MockService::VERSION, |
| 54 | + "aid" => "pact-mock_service", |
| 55 | + "aip" => 1, |
| 56 | + "ds" => ENV['PACT_EXECUTING_LANGUAGE'] ? "client" : "cli", |
| 57 | + "cd2" => ENV['CI'] == "true" ? "CI" : "unknown", |
| 58 | + "cd3" => RUBY_PLATFORM, |
| 59 | + "cd6" => ENV['PACT_EXECUTING_LANGUAGE'] || "unknown", |
| 60 | + "cd7" => ENV['PACT_EXECUTING_LANGUAGE_VERSION'], |
| 61 | + "el" => event, |
| 62 | + "ec" => category, |
| 63 | + "ea" => action, |
| 64 | + "ev" => value |
| 65 | + } |
| 66 | + end |
| 67 | + |
| 68 | + def self.track_events? |
| 69 | + ENV['PACT_DO_NOT_TRACK'] != 'true' |
| 70 | + end |
| 71 | + |
| 72 | + def self.calculate_cid |
| 73 | + if RUBY_PLATFORM.include? "windows" |
| 74 | + hostname = ENV['COMPUTERNAME'] |
| 75 | + else |
| 76 | + hostname = ENV['HOSTNAME'] |
| 77 | + end |
| 78 | + if !hostname |
| 79 | + hostname = Socket.gethostname |
| 80 | + end |
| 81 | + Digest::MD5.hexdigest hostname || SecureRandom.urlsafe_base64(5) |
| 82 | + end |
| 83 | + end |
| 84 | + end |
| 85 | +end |
0 commit comments