mettr 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: 415512a4f4a5861062a28a1d49385c440efcd441bf52df0190520bc7ec34f1a3
4
+ data.tar.gz: 38438568e73d1ea87c593431672375d287388f841816faa2206513a80579332a
5
+ SHA512:
6
+ metadata.gz: bee8458e6c08e67354588dcc44d0b3d222060a84262c212c46b8c4e645f25b649c4c3798a18bd9830ee413dfcf44095519e3146774d56ee5a22ccb004d61531b
7
+ data.tar.gz: 497de2c1816c17879a8e8fb3667f6d2b37f7da8eb61c1bb45b31c776fe2888e4b0d19950fd5b2c5e7c598365460658600dc17f9c27f4a6e615310a1d37dde47d
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alex Babintsev
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # mettr for Ruby
2
+
3
+ Live analytics for websites and SaaS products: who is on your site right
4
+ now, what they do, where they came from and what broke, with no delay.
5
+ This gem sends a Ruby app's side of it to [mettr](https://mettr.app): your
6
+ product's own events, crawlers' visits (search engines and AI crawlers
7
+ seldom run the browser script), 404s, exceptions, response times and
8
+ subscriptions, and serves the browser script from your own domain.
9
+
10
+ ```ruby
11
+ gem "mettr"
12
+ ```
13
+
14
+ Ruby 3.2 or later, no dependencies. Rails is set up on its own; any other
15
+ Rack app (Sinatra, Roda, Hanami) adds the middleware.
16
+
17
+ ## Settings
18
+
19
+ The client reads the environment; `Mettr.configure` wins.
20
+
21
+ | variable | what |
22
+ |---|---|
23
+ | `METTR_SECRET_KEY` | the site's secret key (mettr, the site's settings, Tracking); keep it on the server |
24
+ | `METTR_PUBLIC_KEY` | the site's public key, for the script tag and the proxy |
25
+ | `METTR_ENABLED` | `true` or `false`; by default on once a key is set (Rails: only in production) |
26
+ | `METTR_PROXY_PATH` | the first-party path, `_live` by default; empty serves the script from mettr |
27
+ | `METTR_ENDPOINT` | where mettr runs, `https://mettr.app` |
28
+
29
+ ## Rails
30
+
31
+ Add the gem and the two keys: the middleware goes to the top of the stack
32
+ by itself. In the layout:
33
+
34
+ ```erb
35
+ <head>
36
+ <%= mettr_script_tag %>
37
+ </head>
38
+ ```
39
+
40
+ Sign-ins through Devise (Warden) are sent as `login`, unhandled exceptions
41
+ from Rails' error reporter, and each request's route with its response
42
+ time. Who the user is, and who is staff, in `config/initializers/mettr.rb`:
43
+
44
+ ```ruby
45
+ Mettr.configure do |config|
46
+ config.user = ->(env) { env["warden"]&.user&.id } # the default
47
+ config.staff = ->(env) { env["warden"]&.user&.admin? }
48
+ end
49
+ ```
50
+
51
+ ## Rack
52
+
53
+ ```ruby
54
+ require "mettr"
55
+
56
+ use Mettr::Rack, user: ->(env) { env["rack.session"]&.dig("user_id") }
57
+ ```
58
+
59
+ Behind a proxy of your own whose address is `REMOTE_ADDR`, pass
60
+ `trust_forwarded: true`. In a template: `Mettr.client.script_tag`.
61
+
62
+ ## Your own events
63
+
64
+ ```ruby
65
+ Mettr.event("signup", {plan: "pro"}, user_id: user.id)
66
+ Mettr.revenue("order", 49.5, "EUR", {items: 2})
67
+ Mettr.client.error("PaymentFailed", {provider: "stripe"})
68
+ ```
69
+
70
+ During a request they carry its page, address and browser. Props are
71
+ flat: up to 30, each a string, number, boolean or nil. Events wait a
72
+ second to go together, sent from a background thread; a script or a job
73
+ that ends calls `Mettr.client.flush`.
74
+
75
+ ## Subscriptions
76
+
77
+ For MRR when your billing is your own (anything but Stripe, Paddle or
78
+ Polar, which mettr reads itself), send each subscription whenever it
79
+ changes, and every one once for the history:
80
+
81
+ ```ruby
82
+ Mettr.subscription(
83
+ id: subscription.id.to_s,
84
+ status: "active", # active, past_due, trialing, paused, canceled
85
+ amount: 19, # each cycle, before tax, in the main unit
86
+ currency: "USD",
87
+ interval: "month", # day, week, month, year
88
+ user_id: user.id.to_s,
89
+ plan: "Pro"
90
+ )
91
+ ```
92
+
93
+ ## History and deploys
94
+
95
+ ```ruby
96
+ Mettr.client.import(rows) # each with ts and source_id: a second run adds nothing
97
+ Mettr.client.annotation("Deployed v2.4", url: "https://github.com/acme/app/releases/v2.4")
98
+ ```
99
+
100
+ ## What is sent on its own
101
+
102
+ - A crawler's request: its page and status, as a crawl (mettr names the
103
+ crawler and checks it against its owner's network).
104
+ - A person's 404, as an error.
105
+ - An exception, by its class only, never its message; a client's error
106
+ (a status under 500) is not one.
107
+ - One request in twenty's response time, by route.
108
+ - Nothing for `/up` (`ignore`), for staff, or while mettr is off.
109
+
110
+ Sending never raises into your app: a failed batch answers `false` and is
111
+ told to `on_error`, without its events.
112
+
113
+ ## License
114
+
115
+ MIT
@@ -0,0 +1,343 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cgi/escape"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Mettr
8
+ # What the current request knows of the visitor. mettr uses the address for
9
+ # the place and the visitor hash, and keeps nothing of it. Staff (the
10
+ # site's own people) send nothing.
11
+ Visitor = Struct.new(:url, :ip, :user_agent, :user_id, :staff)
12
+
13
+ # mettr's client: collects events and sends them in batches from a
14
+ # background thread, so a request never waits on mettr. Sending never
15
+ # raises into the app: a failed batch answers false and is told to
16
+ # on_error, without its events.
17
+ class Client
18
+ attr_reader :secret_key, :public_key, :endpoint, :enabled, :proxy_path, :timeout, :flush_interval,
19
+ :response_time_sample, :crawler_pattern, :ignore, :track
20
+
21
+ UNSET = Object.new.freeze
22
+
23
+ # Settings come from the environment (METTR_SECRET_KEY, METTR_PUBLIC_KEY,
24
+ # METTR_ENDPOINT, METTR_ENABLED, METTR_PROXY_PATH); arguments win. mettr
25
+ # is on when METTR_ENABLED says so, or else once a key is set.
26
+ #
27
+ # flush_interval: seconds events wait to go together; 0 sends only on
28
+ # flush, what a serverless function or a script calls before it ends.
29
+ def initialize(
30
+ secret_key: nil, public_key: nil, endpoint: nil, enabled: nil, proxy_path: UNSET,
31
+ timeout: Contract::TIMEOUT_SECONDS, flush_interval: 1.0,
32
+ response_time_sample: Contract::RESPONSE_TIME_SAMPLE, crawler_pattern: Contract::CRAWLER_PATTERN,
33
+ ignore: ["/up"], track: {}, transport: nil, on_error: nil, random: -> { rand }
34
+ )
35
+ env = ENV
36
+ proxy = proxy_path.equal?(UNSET) ? env.fetch("METTR_PROXY_PATH", Contract::PROXY_PATH) : proxy_path
37
+ told = enabled.nil? ? flag(env["METTR_ENABLED"]) : enabled
38
+
39
+ @secret_key = secret_key || env["METTR_SECRET_KEY"]
40
+ @public_key = public_key || env["METTR_PUBLIC_KEY"]
41
+ @endpoint = (endpoint || env["METTR_ENDPOINT"] || Contract::DEFAULT_ENDPOINT).sub(%r{/+\z}, "")
42
+ @enabled = told.nil? ? present?(@secret_key) || present?(@public_key) : told
43
+ trimmed = proxy.to_s.gsub(%r{\A/+|/+\z}, "")
44
+ @proxy_path = trimmed.empty? ? nil : trimmed
45
+ @timeout = timeout
46
+ @flush_interval = flush_interval
47
+ @response_time_sample = response_time_sample
48
+ @crawler_pattern = crawler_pattern
49
+ @ignore = ignore
50
+ @track = {not_found: true, exceptions: true, crawlers: true}.merge(track)
51
+ @transport = transport || Transport.new
52
+ @on_error = on_error
53
+ @random = random
54
+ @mutex = Mutex.new
55
+ @events = []
56
+ @subscriptions = []
57
+ @thread = nil
58
+ @script = nil
59
+ at_exit { flush }
60
+ end
61
+
62
+ # A custom event: client.event("signup", {plan: "pro"}, Visitor.new(user_id: "42")).
63
+ def event(name, props = nil, visitor = nil)
64
+ record({"type" => "event", "name" => name, "props" => props}, visitor)
65
+ end
66
+
67
+ # An error: a 404, an exception, anything that broke.
68
+ def error(name, props = nil, visitor = nil)
69
+ record({"type" => "error", "name" => name, "props" => props}, visitor)
70
+ end
71
+
72
+ # An exception as an error event: its class only, never the message (it
73
+ # may hold what the app's users typed). A client's error (a status under
74
+ # 500: not found, a bad request) is the request's fault, not the app's.
75
+ def exception(error, visitor = nil)
76
+ status = [:status, :status_code, :http_status].map { |name| error.respond_to?(name) ? error.public_send(name) : nil }.compact.first
77
+ return if !@track[:exceptions] || (status.is_a?(Integer) && status < 500)
78
+
79
+ error("exception", {"class" => error.class.name}, visitor)
80
+ end
81
+
82
+ # A payment: an amount in the currency's main unit, negative for a refund.
83
+ def revenue(name, amount, currency, props = nil, visitor = nil)
84
+ record(
85
+ {"type" => "revenue", "name" => name, "revenue" => {"amount" => amount, "currency" => currency}, "props" => props},
86
+ visitor
87
+ )
88
+ end
89
+
90
+ # A crawler's request: the page and its status. mettr names the crawler.
91
+ def crawl(status, visitor)
92
+ record({"type" => "crawl", "props" => {"status" => status}}, visitor)
93
+ end
94
+
95
+ # Adds an event with what the request knows of the visitor. Nothing is
96
+ # added while mettr is off, for staff, or on a path mettr ignores.
97
+ def record(event, visitor = nil)
98
+ visitor ||= Visitor.new
99
+ event = event.transform_keys(&:to_s)
100
+ return if !@enabled || visitor.staff || ignores?(visitor.url)
101
+
102
+ props = event["props"]
103
+ kept = event.merge(
104
+ # An event that says its own address keeps it, even none.
105
+ "url" => event.key?("url") ? event["url"] : visitor.url,
106
+ "ip" => event["ip"] || visitor.ip,
107
+ "user_agent" => event["user_agent"] || visitor.user_agent,
108
+ # A crawl is nobody's (mettr refuses one with a user).
109
+ "user_id" => (event["type"] == "crawl") ? nil : event["user_id"] || visitor.user_id,
110
+ "props" => (props.nil? || props.empty?) ? nil : props.transform_keys(&:to_s)
111
+ ).compact
112
+
113
+ full = @mutex.synchronize do
114
+ @events << kept
115
+ @events.size >= Contract::BATCH
116
+ end
117
+
118
+ schedule(full)
119
+ end
120
+
121
+ # A subscription of the app's own billing, as it is now, for MRR when
122
+ # mettr does not read the billing itself (not Stripe, Paddle or Polar).
123
+ # Send it whenever it changes, and every subscription once for the
124
+ # history. status: active or past_due (both pay), trialing, paused,
125
+ # canceled; amount: each cycle, before tax, in the main unit.
126
+ def subscription(id:, status:, amount:, currency:, interval: "month", interval_count: 1, user_id: nil, plan: nil,
127
+ started_at: nil, canceled_at: nil, changed_at: nil)
128
+ return unless @enabled
129
+
130
+ item = {
131
+ "id" => id, "status" => status, "amount" => amount, "currency" => currency, "interval" => interval,
132
+ "interval_count" => interval_count, "user_id" => user_id, "plan" => plan,
133
+ "started_at" => moment(started_at), "canceled_at" => moment(canceled_at), "changed_at" => moment(changed_at)
134
+ }.compact
135
+
136
+ @mutex.synchronize { @subscriptions << item }
137
+ schedule(false)
138
+ end
139
+
140
+ # Sends what has been collected, now; what a serverless function calls before it ends.
141
+ def flush
142
+ events, subscriptions = @mutex.synchronize do
143
+ taken = [@events, @subscriptions]
144
+ @events = []
145
+ @subscriptions = []
146
+ taken
147
+ end
148
+
149
+ sent_events = events.empty? || send_events(events)
150
+ sent_subscriptions = subscriptions.empty? ||
151
+ post(Contract::PATHS[:subscriptions], "subscriptions", subscriptions, Contract::SUBSCRIPTIONS_BATCH)
152
+
153
+ sent_events && sent_subscriptions
154
+ end
155
+
156
+ # Sends events now, in batches of 100, as mettr's ingest API takes them.
157
+ def send_events(events)
158
+ post(Contract::PATHS[:events], "events", events, Contract::BATCH)
159
+ end
160
+
161
+ # History (POST /api/v1/import), in batches of 1,000: each with ts and source_id.
162
+ def import(events)
163
+ post(Contract::PATHS[:import], "events", events, Contract::IMPORT_BATCH)
164
+ end
165
+
166
+ # A change under the traffic chart, from a deploy script or CI.
167
+ def annotation(title, url: nil, ts: nil)
168
+ request(Contract::PATHS[:annotations], {"title" => title, "url" => url, "ts" => moment(ts)}.compact)
169
+ end
170
+
171
+ # Whether a user agent is a crawler's, as the middleware reads it.
172
+ def crawler?(user_agent)
173
+ @track[:crawlers] && !user_agent.nil? && @crawler_pattern.match?(user_agent)
174
+ end
175
+
176
+ # Whether a URL or path is one mettr sends nothing for (a * matches anything).
177
+ def ignores?(url)
178
+ return false if url.nil?
179
+
180
+ path = path_of(url)
181
+ # Without FNM_PATHNAME a * matches across slashes too, as Laravel's Request::is does.
182
+ @ignore.any? { |pattern| File.fnmatch?("/#{pattern.sub(%r{\A/+}, "")}", path) }
183
+ end
184
+
185
+ # Whether a path is under the proxy path.
186
+ def proxy?(url)
187
+ return false if @proxy_path.nil? || url.nil?
188
+
189
+ path_of(url).start_with?("/#{@proxy_path}/")
190
+ end
191
+
192
+ # What a middleware calls once the response is known: a crawler's
193
+ # request becomes a crawl, a 404 an error, and a sample of requests sends
194
+ # its response time. mettr's own proxy path sends none.
195
+ def finished(status:, ms:, route:, visitor:)
196
+ return if proxy?(visitor.url)
197
+
198
+ if crawler?(visitor.user_agent)
199
+ # Its status says a 404 too: no error beside it.
200
+ crawl(status, visitor)
201
+ elsif status == 404 && @track[:not_found]
202
+ error("404", nil, visitor)
203
+ end
204
+
205
+ return unless @response_time_sample.positive? && @random.call < @response_time_sample
206
+
207
+ event("response_time", {"ms" => ms.round, "route" => route || "(none)", "status" => status}, visitor)
208
+ end
209
+
210
+ # The script tag's attributes, or nil while mettr is off.
211
+ def script_attributes
212
+ return nil if !@enabled || !present?(@public_key)
213
+ return {"data-key" => @public_key, "src" => @endpoint + Contract::PATHS[:script]} if @proxy_path.nil?
214
+
215
+ {"data-key" => @public_key, "data-api" => "/#{@proxy_path}/events", "src" => "/#{@proxy_path}/script.js"}
216
+ end
217
+
218
+ # The tag for the page's <head>; empty while mettr is off.
219
+ def script_tag
220
+ attributes = script_attributes
221
+ return "" if attributes.nil?
222
+
223
+ "<script defer#{attributes.map { |name, value| " #{name}=\"#{CGI.escapeHTML(value)}\"" }.join}></script>"
224
+ end
225
+
226
+ # GET {proxy}/script.js: mettr's browser script from your own domain,
227
+ # fetched once an hour and kept in memory. While mettr cannot be reached
228
+ # the page gets an empty script, tried again in a minute.
229
+ # Answers [status, headers, body], as Rack does.
230
+ def proxy_script
231
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
232
+
233
+ if @script.nil? || @script[1] <= now
234
+ status, body = @transport.get(@endpoint + Contract::PATHS[:script], @timeout)
235
+ return javascript("/* mettr is unavailable */", Contract::SCRIPT_RETRY_SECONDS) unless (200..299).cover?(status)
236
+
237
+ @script = [body, now + Contract::SCRIPT_CACHE_SECONDS]
238
+ end
239
+
240
+ javascript(@script[0], Contract::SCRIPT_CACHE_SECONDS)
241
+ end
242
+
243
+ # POST {proxy}/events: the browser script's events, through your own
244
+ # domain. They go on with the secret key, carrying what only your server
245
+ # knows: the visitor's address and browser as they reached you, and the
246
+ # signed-in user. So only what a browser may say passes: the types and
247
+ # fields of the public key, never a time, a user, an address or revenue.
248
+ # Answers [status, body].
249
+ def proxy_events(raw, visitor)
250
+ return [413, {"message" => "The body is too large."}] if raw.bytesize > Contract::PROXY_MAX_BYTES
251
+
252
+ body = begin
253
+ JSON.parse(raw)
254
+ rescue JSON::ParserError
255
+ nil
256
+ end
257
+
258
+ return [403, {"message" => "Not this site's key."}] if !present?(@public_key) || !body.is_a?(Hash) || body["key"] != @public_key
259
+
260
+ items = body["events"].is_a?(Array) ? body["events"] : [body]
261
+ accepted = 0
262
+
263
+ items.first(Contract::PROXY_MAX_EVENTS).each do |item|
264
+ next unless item.is_a?(Hash) && Contract::PROXY_TYPES.include?(item["type"])
265
+
266
+ kept = item.slice(*Contract::PROXY_FIELDS)
267
+ kept["url"] = item["url"].is_a?(String) ? item["url"] : nil
268
+ record(kept, visitor)
269
+ accepted += 1
270
+ end
271
+
272
+ [202, {"accepted" => accepted}]
273
+ end
274
+
275
+ private
276
+
277
+ def schedule(now)
278
+ return flush if now
279
+ return if @flush_interval <= 0
280
+
281
+ @mutex.synchronize do
282
+ return if @thread&.alive?
283
+
284
+ @thread = Thread.new do
285
+ sleep @flush_interval
286
+ flush
287
+ end
288
+ end
289
+ end
290
+
291
+ def post(path, key, items, size)
292
+ return false if items.empty?
293
+
294
+ # Every batch is sent, even after one fails.
295
+ items.each_slice(size).map { |batch| request(path, {key => batch}) }.all?
296
+ end
297
+
298
+ def request(path, body)
299
+ return false unless present?(@secret_key)
300
+
301
+ status = @transport.post(
302
+ @endpoint + path,
303
+ JSON.generate(body),
304
+ {
305
+ "Authorization" => "Bearer #{@secret_key}",
306
+ "Content-Type" => "application/json",
307
+ "Accept" => "application/json",
308
+ "User-Agent" => "mettr-ruby/#{VERSION}"
309
+ },
310
+ @timeout
311
+ )
312
+ return true if (200..299).cover?(status)
313
+
314
+ @on_error&.call(status.zero? ? "mettr could not be reached on #{path}" : "mettr answered #{status} on #{path}")
315
+ false
316
+ end
317
+
318
+ def javascript(body, max_age)
319
+ [200, {"content-type" => "application/javascript; charset=utf-8", "cache-control" => "public, max-age=#{max_age}"}, body]
320
+ end
321
+
322
+ def path_of(url)
323
+ path = URI.parse(url).path
324
+ (path.nil? || path.empty?) ? "/" : path
325
+ rescue URI::InvalidURIError
326
+ url.split(/[?#]/).first.to_s
327
+ end
328
+
329
+ def moment(time)
330
+ time&.to_time&.utc&.strftime("%Y-%m-%dT%H:%M:%SZ")
331
+ end
332
+
333
+ def flag(value)
334
+ return nil if value.nil? || value.empty?
335
+
336
+ %w[1 true yes on].include?(value.downcase)
337
+ end
338
+
339
+ def present?(value)
340
+ !value.nil? && !value.empty?
341
+ end
342
+ end
343
+ end
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mettr
4
+ # What every mettr SDK shares: the app's resources/sdk-contract.json, copied
5
+ # to this repository's sdk-contract.json (test/contract_test.rb holds the
6
+ # two together).
7
+ module Contract
8
+ DEFAULT_ENDPOINT = "https://mettr.app"
9
+
10
+ PATHS = {
11
+ events: "/api/v1/events",
12
+ import: "/api/v1/import",
13
+ subscriptions: "/api/v1/subscriptions",
14
+ annotations: "/api/v1/annotations",
15
+ script: "/script.js"
16
+ }.freeze
17
+
18
+ BATCH = 100
19
+ IMPORT_BATCH = 1000
20
+ SUBSCRIPTIONS_BATCH = 100
21
+ MAX_PROPS = 30
22
+ MAX_PROP_LENGTH = 500
23
+
24
+ SUBSCRIPTION_STATUSES = %w[active trialing past_due paused canceled].freeze
25
+ SUBSCRIPTION_INTERVALS = %w[day week month year].freeze
26
+
27
+ PROXY_PATH = "_live"
28
+ PROXY_MAX_BYTES = 65_536
29
+ PROXY_MAX_EVENTS = 20
30
+ PROXY_TYPES = %w[pageview event engagement vital presence].freeze
31
+ PROXY_FIELDS = %w[type name url referrer props automated].freeze
32
+ SCRIPT_CACHE_SECONDS = 3600
33
+ SCRIPT_RETRY_SECONDS = 60
34
+
35
+ TIMEOUT_SECONDS = 3
36
+ RESPONSE_TIME_SAMPLE = 0.05
37
+
38
+ CRAWLER_PATTERN = Regexp.new(
39
+ "bot|crawl|spider|slurp|facebookexternalhit|facebookcatalog|embedly|iframely|whatsapp|perplexity|chatgpt" \
40
+ "|claude|anthropic|cohere|diffbot|bytespider|meta-external|uptime|pingdom|statuscake|site24x7|checkly" \
41
+ "|screaming frog",
42
+ Regexp::IGNORECASE
43
+ )
44
+
45
+ # Cloudflare's addresses, from cloudflare.com/ips (October 2026).
46
+ CLOUDFLARE = %w[
47
+ 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18
48
+ 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17
49
+ 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22
50
+ 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32
51
+ 2a06:98c0::/29 2c0f:f248::/32
52
+ ].freeze
53
+ end
54
+ end
data/lib/mettr/ip.rb ADDED
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+
5
+ module Mettr
6
+ # The visitor's address, not the edge node relaying the request.
7
+ module IP
8
+ NETWORKS = Contract::CLOUDFLARE.map { |cidr| IPAddr.new(cidr) }.freeze
9
+
10
+ module_function
11
+
12
+ # Behind Cloudflare, the address the request came from (the relay) is a
13
+ # Cloudflare node: every visitor would be placed where the node is, and
14
+ # would become a new visitor whenever Cloudflare routed them through
15
+ # another. CF-Connecting-IP names the address Cloudflare took the request
16
+ # from, and counts only when the request came from Cloudflare: one sent
17
+ # to the server directly could name any address.
18
+ def visitor(relay, connecting)
19
+ source = parse(relay)
20
+ return (relay.nil? || relay.empty?) ? nil : relay if source.nil?
21
+
22
+ if connecting && NETWORKS.any? { |network| network.family == source.family && network.include?(source) }
23
+ visitor = parse(connecting)
24
+ return visitor.to_s unless visitor.nil?
25
+ end
26
+
27
+ source.to_s
28
+ end
29
+
30
+ # The first address of X-Forwarded-For: the client, as the proxies saw it.
31
+ def forwarded_for(header)
32
+ first = header.to_s.split(",").first.to_s.strip
33
+ parse(first).nil? ? nil : first
34
+ end
35
+
36
+ # An IPv4 address as a dual-stack socket gives it (::ffff:203.0.113.7)
37
+ # is the IPv4 address: placed, hashed and matched as one.
38
+ def parse(address)
39
+ return nil if address.nil? || address.strip.empty?
40
+
41
+ parsed = IPAddr.new(address.strip.split("%").first)
42
+ parsed.ipv4_mapped? ? parsed.native : parsed
43
+ rescue IPAddr::Error
44
+ nil
45
+ end
46
+ end
47
+ end
data/lib/mettr/rack.rb ADDED
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mettr
4
+ # Rack middleware (Rails, Sinatra, Roda, Hanami): serves the first-party
5
+ # proxy (/_live/script.js, /_live/events), and once a response is ready
6
+ # sends a crawler's visit as a crawl, a 404 as an error, an exception by
7
+ # its class and a sample of response times.
8
+ #
9
+ # use Mettr::Rack, user: ->(env) { env["warden"]&.user&.id }
10
+ class Rack
11
+ ENV_KEY = "mettr.visitor"
12
+
13
+ # user: the signed-in user's id from the Rack env (Warden's by default);
14
+ # staff: whether the request is staff's; trust_forwarded: take
15
+ # X-Forwarded-For's first address (an app behind its own proxy, when
16
+ # Rack's REMOTE_ADDR is the proxy's).
17
+ def initialize(app, client: nil, user: nil, staff: nil, trust_forwarded: false)
18
+ @app = app
19
+ @client = client
20
+ @user = user || ->(env) { warden_user_id(env) }
21
+ @staff = staff
22
+ @trust_forwarded = trust_forwarded
23
+ end
24
+
25
+ def call(env)
26
+ client = @client || Mettr.client
27
+ proxied = proxy(client, env)
28
+ return proxied unless proxied.nil?
29
+
30
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
31
+ Thread.current[ENV_KEY] = env
32
+
33
+ begin
34
+ status, headers, body = @app.call(env)
35
+ rescue Exception => error # rubocop:disable Lint/RescueException -- reported, then raised again
36
+ client.exception(error, visitor(env))
37
+ finish(client, env, 500, started)
38
+ raise
39
+ ensure
40
+ Thread.current[ENV_KEY] = nil
41
+ end
42
+
43
+ finish(client, env, status, started)
44
+ [status, headers, body]
45
+ end
46
+
47
+ # The visitor as a Rack env shows them, for the app's own events.
48
+ def visitor(env)
49
+ relay = (Mettr::IP.forwarded_for(env["HTTP_X_FORWARDED_FOR"]) if @trust_forwarded) || env["REMOTE_ADDR"]
50
+ user_id = @user.call(env)
51
+
52
+ Visitor.new(
53
+ url: url(env),
54
+ ip: Mettr::IP.visitor(relay, env["HTTP_CF_CONNECTING_IP"]),
55
+ user_agent: env["HTTP_USER_AGENT"],
56
+ user_id: user_id&.to_s,
57
+ staff: @staff ? @staff.call(env) : false
58
+ )
59
+ end
60
+
61
+ private
62
+
63
+ def proxy(client, env)
64
+ return nil if client.proxy_path.nil?
65
+
66
+ path = env["PATH_INFO"]
67
+ method = env["REQUEST_METHOD"]
68
+
69
+ if method == "GET" && path == "/#{client.proxy_path}/script.js"
70
+ status, headers, body = client.proxy_script
71
+ return [status, headers, [body]]
72
+ end
73
+
74
+ return nil unless method == "POST" && path == "/#{client.proxy_path}/events"
75
+
76
+ # No further than one byte past the cap.
77
+ raw = env["rack.input"]&.read(Contract::PROXY_MAX_BYTES + 1).to_s
78
+ status, body = client.proxy_events(raw, visitor(env))
79
+
80
+ [status, {"content-type" => "application/json"}, [JSON.generate(body)]]
81
+ end
82
+
83
+ def finish(client, env, status, started)
84
+ client.finished(
85
+ status: status.to_i,
86
+ ms: (Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000,
87
+ route: env["mettr.route"],
88
+ visitor: visitor(env)
89
+ )
90
+ end
91
+
92
+ def url(env)
93
+ scheme = env["HTTP_X_FORWARDED_PROTO"]&.split(",")&.first&.strip || env["rack.url_scheme"] || "http"
94
+ host = env["HTTP_X_FORWARDED_HOST"] || env["HTTP_HOST"] || env["SERVER_NAME"] || "localhost"
95
+ query = env["QUERY_STRING"].to_s.empty? ? "" : "?#{env["QUERY_STRING"]}"
96
+
97
+ "#{scheme}://#{host}#{env["SCRIPT_NAME"]}#{env["PATH_INFO"]}#{query}"
98
+ end
99
+
100
+ def warden_user_id(env)
101
+ user = env["warden"]&.user
102
+ user.respond_to?(:id) ? user.id : nil
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,102 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "rails/railtie"
4
+
5
+ module Mettr
6
+ # Rails: the Rack middleware at the top of the stack, the route of each
7
+ # request, unhandled exceptions from Rails' error reporter, sign-ins
8
+ # through Warden (Devise), and mettr_script_tag in views.
9
+ #
10
+ # Settings in config/initializers/mettr.rb:
11
+ #
12
+ # Mettr.configure do |config|
13
+ # config.user = ->(env) { env["warden"]&.user&.id }
14
+ # config.staff = ->(env) { env["warden"]&.user&.admin? }
15
+ # end
16
+ class Railtie < ::Rails::Railtie
17
+ initializer "mettr.middleware" do |app|
18
+ # Off in development and test unless METTR_ENABLED says otherwise.
19
+ Mettr.defaults[:enabled] = false unless ::Rails.env.production? || ENV.key?("METTR_ENABLED")
20
+
21
+ app.middleware.insert(0, Mettr::RailsMiddleware)
22
+ end
23
+
24
+ initializer "mettr.routes" do
25
+ ActiveSupport::Notifications.subscribe("start_processing.action_controller") do |*, payload|
26
+ Mettr::Routes.note(payload[:request])
27
+ end
28
+ end
29
+
30
+ initializer "mettr.errors" do
31
+ ::Rails.error.subscribe(Mettr::ErrorSubscriber.new)
32
+ end
33
+
34
+ initializer "mettr.view" do
35
+ ActiveSupport.on_load(:action_view) { include Mettr::ViewHelper }
36
+ end
37
+
38
+ config.after_initialize do
39
+ Mettr::Logins.install
40
+ end
41
+ end
42
+
43
+ # The route a controller matched (/posts/:id), for the response time sample.
44
+ module Routes
45
+ def self.note(request)
46
+ env = Thread.current[Mettr::Rack::ENV_KEY]
47
+ pattern = request.respond_to?(:route_uri_pattern) ? request.route_uri_pattern : nil
48
+ return if env.nil? || pattern.nil?
49
+
50
+ env["mettr.route"] = pattern.delete_suffix("(.:format)")
51
+ end
52
+ end
53
+
54
+ # The Rack middleware with the settings of Mettr.configure, read per request.
55
+ class RailsMiddleware
56
+ def initialize(app)
57
+ @app = app
58
+ end
59
+
60
+ def call(env)
61
+ configuration = Mettr.configuration
62
+
63
+ Mettr::Rack.new(
64
+ @app,
65
+ user: configuration.user,
66
+ staff: configuration.staff,
67
+ trust_forwarded: configuration.trust_forwarded
68
+ ).call(env)
69
+ end
70
+ end
71
+
72
+ # Rails' error reporter: an exception the app did not handle, by its class.
73
+ class ErrorSubscriber
74
+ def report(error, handled:, **)
75
+ return if handled
76
+
77
+ Mettr.client.exception(error, Mettr.current_visitor)
78
+ end
79
+ end
80
+
81
+ # Sign-ins through Warden (Devise), as the user's login event.
82
+ module Logins
83
+ def self.install
84
+ return unless defined?(::Warden::Manager)
85
+
86
+ ::Warden::Manager.after_authentication do |user, _auth, _options|
87
+ next unless Mettr.configuration.track_logins
88
+
89
+ id = user.respond_to?(:id) ? user.id.to_s : nil
90
+ Mettr.client.record({"type" => "event", "name" => "login", "user_id" => id}, Mettr.current_visitor)
91
+ end
92
+ end
93
+ end
94
+
95
+ # <%= mettr_script_tag %> in the layout's <head>.
96
+ module ViewHelper
97
+ def mettr_script_tag
98
+ # Built and escaped by the client.
99
+ Mettr.client.script_tag.html_safe
100
+ end
101
+ end
102
+ end
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+
6
+ module Mettr
7
+ # HTTP on the standard library: no dependency to clash with the app's.
8
+ # Net::HTTP never follows a redirect (the key stays with mettr) and
9
+ # verifies TLS by default.
10
+ class Transport
11
+ # POST a body; the status mettr answered, or 0 when it could not be reached.
12
+ def post(url, body, headers, timeout)
13
+ request(url, timeout) do |uri|
14
+ post = Net::HTTP::Post.new(uri)
15
+ headers.each { |name, value| post[name] = value }
16
+ post.body = body
17
+ post
18
+ end.first
19
+ end
20
+
21
+ # GET a text; its status and body, or [0, ""] when it could not be reached.
22
+ def get(url, timeout)
23
+ request(url, timeout) { |uri| Net::HTTP::Get.new(uri) }
24
+ end
25
+
26
+ private
27
+
28
+ def request(url, timeout)
29
+ uri = URI.parse(url)
30
+ http = Net::HTTP.new(uri.host, uri.port)
31
+ http.use_ssl = uri.scheme == "https"
32
+ http.open_timeout = http.read_timeout = http.write_timeout = timeout
33
+ response = http.start { |connection| connection.request(yield(uri)) }
34
+
35
+ [response.code.to_i, response.body.to_s.dup.force_encoding(Encoding::UTF_8)]
36
+ rescue # timeouts, refused connections, TLS failures, a malformed endpoint
37
+ [0, ""]
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Mettr
4
+ VERSION = "0.1.0"
5
+ end
data/lib/mettr.rb ADDED
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "mettr/version"
4
+ require "mettr/contract"
5
+ require "mettr/ip"
6
+ require "mettr/transport"
7
+ require "mettr/client"
8
+ require "mettr/rack"
9
+
10
+ # mettr for Ruby: live analytics for websites and SaaS products. Mettr.client
11
+ # sends the app's own events, crawlers' visits, 404s, exceptions and
12
+ # subscriptions; Mettr::Rack and, in Rails, the Railtie send what a request
13
+ # shows on their own.
14
+ module Mettr
15
+ # Settings for Mettr.client and the Rails integration.
16
+ class Configuration
17
+ attr_accessor :user, :staff, :trust_forwarded, :track_logins, :options
18
+
19
+ def initialize
20
+ @user = nil
21
+ @staff = nil
22
+ @trust_forwarded = false
23
+ @track_logins = true
24
+ @options = {}
25
+ end
26
+ end
27
+
28
+ class << self
29
+ # Client options set by an integration before the app's own (Rails:
30
+ # off outside production).
31
+ def defaults
32
+ @defaults ||= {}
33
+ end
34
+
35
+ def configuration
36
+ @configuration ||= Configuration.new
37
+ end
38
+
39
+ # Mettr.configure { |config| config.options = {secret_key: ...}; config.user = ->(env) { ... } }
40
+ def configure
41
+ yield configuration
42
+ @client = nil
43
+ end
44
+
45
+ # The app's one client, from the environment and Mettr.configure.
46
+ def client
47
+ @client ||= Client.new(**defaults, **configuration.options)
48
+ end
49
+
50
+ # Forgets the client and the settings (tests).
51
+ def reset!
52
+ @client = nil
53
+ @configuration = nil
54
+ @defaults = nil
55
+ end
56
+
57
+ # Mettr.event("signup", {plan: "pro"}, user_id: current_user.id)
58
+ def event(name, props = nil, user_id: nil)
59
+ client.record({"type" => "event", "name" => name, "props" => props, "user_id" => user_id&.to_s}, current_visitor)
60
+ end
61
+
62
+ # Mettr.revenue("order", 49.5, "EUR", {items: 2})
63
+ def revenue(name, amount, currency, props = nil, user_id: nil)
64
+ client.record(
65
+ {"type" => "revenue", "name" => name, "revenue" => {"amount" => amount, "currency" => currency}, "props" => props,
66
+ "user_id" => user_id&.to_s},
67
+ current_visitor
68
+ )
69
+ end
70
+
71
+ # A subscription of your own billing, as it is now (Client#subscription).
72
+ def subscription(**)
73
+ client.subscription(**)
74
+ end
75
+
76
+ # The visitor of the request being served, when there is one.
77
+ def current_visitor
78
+ env = Thread.current[Mettr::Rack::ENV_KEY]
79
+ env && Mettr::Rack.new(nil, user: configuration.user, staff: configuration.staff,
80
+ trust_forwarded: configuration.trust_forwarded).visitor(env)
81
+ end
82
+ end
83
+ end
84
+
85
+ # In a Rails app Bundler requires the gem after Rails, and the Railtie loads;
86
+ # elsewhere it never does. One process runs one of the two: rails_test.rb
87
+ # requires mettr/rails itself.
88
+ # :nocov:
89
+ require "mettr/rails" if defined?(Rails::Railtie)
90
+ # :nocov:
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: mettr
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - mettr
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies: []
12
+ description: 'Sends a Ruby app''s side of mettr''s live analytics: the product''s
13
+ own events, crawlers'' visits, 404s, exceptions, response times and subscriptions,
14
+ and serves the browser script from your own domain.'
15
+ executables: []
16
+ extensions: []
17
+ extra_rdoc_files: []
18
+ files:
19
+ - LICENSE
20
+ - README.md
21
+ - lib/mettr.rb
22
+ - lib/mettr/client.rb
23
+ - lib/mettr/contract.rb
24
+ - lib/mettr/ip.rb
25
+ - lib/mettr/rack.rb
26
+ - lib/mettr/rails.rb
27
+ - lib/mettr/transport.rb
28
+ - lib/mettr/version.rb
29
+ homepage: https://mettr.app
30
+ licenses:
31
+ - MIT
32
+ metadata:
33
+ homepage_uri: https://mettr.app
34
+ documentation_uri: https://mettr.app/docs/ruby
35
+ source_code_uri: https://github.com/mettrhq/mettr-ruby
36
+ rubygems_mfa_required: 'true'
37
+ rdoc_options: []
38
+ require_paths:
39
+ - lib
40
+ required_ruby_version: !ruby/object:Gem::Requirement
41
+ requirements:
42
+ - - ">="
43
+ - !ruby/object:Gem::Version
44
+ version: '3.2'
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '0'
50
+ requirements: []
51
+ rubygems_version: 4.0.20
52
+ specification_version: 4
53
+ summary: 'Live analytics for websites and SaaS products: mettr for Ruby, Rack and
54
+ Rails'
55
+ test_files: []