sitegoose 0.3.3 → 0.3.5

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: f88d90ea071f9dde430e079a88e42a22dabd4f0faeaa4a662da5c94eb8cd942c
4
- data.tar.gz: 1033458a91be1a78a2464a9439d2d021eaedce386b0cfb7eb7662db4927a3e50
3
+ metadata.gz: ce69bd61fa38892bea9ea285bebd0688fd618deacd1715ae19ec14e3c7f61f02
4
+ data.tar.gz: 83dcc0b5e52dab1c905b45dcb25c20bc242e96cd9c06cde495c5283d2a2812cd
5
5
  SHA512:
6
- metadata.gz: e20cd12422c5830f3a710340198b634c2c192e9d26a830879fa756ebd1901a95c28054ab5d74d73812a80b7243653078592ddd59d9df02048760039b6e9f543b
7
- data.tar.gz: 5190a6b466bdf730a41265537aa1fdf01090aaeb77966d0bf720532ec12db816ebcb15b9ee96561e0a1f45c4d5f9d83256a1adf049f05873f94e57118896c635
6
+ metadata.gz: a433baa5a8baa140e54ec32e47778576e8f37a1978216ffd91fe5ec059b2ccab3a187bec96aead0f5d3f54dc12abb1ee33beceb8d0942a99a4804d6ba6593aee
7
+ data.tar.gz: 215d28e1a1ac655eb425c112be445495bbdf14dd03ea454dc32bd7b433054b7a3d40fcc9c835557674c1c75ce307d91be707f552e1d5b336f525f80137824c43
data/README.md CHANGED
@@ -76,6 +76,8 @@ ActiveJob class under ActiveJob): its errors carry the route
76
76
  nor sent.
77
77
  - What's waiting is sent when Sidekiq shuts down.
78
78
  - Don't also wrap a job in `platform.job`: it would be timed twice.
79
+ - Each queue's backlog is shown too ([Job queues](#job-queues)), from the
80
+ same line.
79
81
 
80
82
  ## Puma, Unicorn and Passenger
81
83
 
@@ -101,9 +103,9 @@ fork doesn't wait for a send in flight.
101
103
  | `maintenance` | A "back soon" page while maintenance mode is on in the dashboard | on |
102
104
  | `headers` | Adds the security headers you pick on the Security page; your own headers win | on |
103
105
  | `forms` | Checks forms before you accept them: `platform.check_form(request)` | on |
104
- | `performance` | Response times and errors of every route (Health → Server speed): Rails and Sinatra route patterns. With it, the database queries each route runs (below) | on |
105
- | `crawlers` | Which search engines and AI bots fetch your pages (Health → Crawlers), counted by the middleware | on |
106
- | `resources` | This machine's CPU, load, memory, disks and network, once a minute (Health → Server resources). Linux | on |
106
+ | `performance` | Response times and errors of every route (Health → Server speed): Rails and Sinatra route patterns. With it, the database queries each route runs, its outgoing calls and your job queues (below) | on |
107
+ | `crawlers` | Which search engines and AI bots fetch your pages (Off-site → Crawlers), counted by the middleware | on |
108
+ | `resources` | This machine's CPU, load, memory, disks and network, once a minute (Health → Server resources), and how close the app is to a limit ([below](#server-limits)). Linux | on |
107
109
  | `inventory` | The installed gems and Ruby version, once a day, so the Security check can flag known security holes (`{host: ...}`: the server's name) | on |
108
110
  | `posture` | How the server is set up, once a day, for the Security check: Rails' environment, `consider_all_requests_local`, `secret_key_base`, `config.hosts`, `force_ssl` and session cookie settings (when it's a Rails app), whether the app runs as root, code anyone on the machine can write, and files in the folders you serve to the web that shouldn't be public (a dump, a `.env`, a `.bak`). Reads only, and sends no file's contents. `{roots: ["public", {dir: "uploads", prefix: "files"}]}` (default: Rails' `public/`), `{checks: -> { [...] }}` for checks of your own (protocol: `sdk/protocols/posture.md`) | on |
109
111
 
@@ -143,6 +145,26 @@ slow. Every value is replaced by `?` before anything is counted
143
145
 
144
146
  - **MongoDB** (the `mongo` gem, Mongoid): automatic, through the driver's
145
147
  command monitoring.
148
+ - **ClickHouse**: the `click_house` gem, one line, where you make the
149
+ connection; only that connection is timed (`select_all`, `select_one`,
150
+ `select_value`, `execute`, `insert`). An insert is filed as
151
+ `INSERT INTO <table>`, and its rows are never read. The ClickHouse adapter
152
+ for Active Record (`clickhouse-activerecord`) is automatic, like any other
153
+ adapter.
154
+
155
+ ```ruby
156
+ CLICKHOUSE = ClickHouse::Connection.new(ClickHouse::Config.new(url: ENV["CLICKHOUSE_URL"]))
157
+ SiteGoose.watch_database(CLICKHOUSE)
158
+ ```
159
+
160
+ - **Redis**: automatic with `redis-client` (so the `redis` gem 5 and Sidekiq 7
161
+ too), through its own `RedisClient.register` middleware. Each command is its
162
+ command and first key's shape only (`GET user:?:cart`), never an argument or
163
+ value; a pipeline is one `PIPELINE GET user:?` call and a `multi` one
164
+ `MULTI INCR hits:?`. Blocking commands (`BRPOP`, Sidekiq's fetch) and the
165
+ package's own queue readings aren't timed; Sidekiq's other commands are. An
166
+ error reply or no answer is a failure; a nil or a `MOVED` isn't. The `redis`
167
+ gem 4 has its own connection code, which isn't seen.
146
168
 
147
169
  A query counts under the request (or Sidekiq or `platform.job` run) it ran
148
170
  in, with the same method and route Server speed shows; one outside them,
@@ -155,6 +177,98 @@ recorded; `queries: false` keeps Server speed without the queries:
155
177
  SiteGoose.configure(site_id: ..., secret: ..., endpoint: ..., queries: false)
156
178
  ```
157
179
 
180
+ ## Outgoing calls
181
+
182
+ Server speed → Calls: how long each route waited on other services (a
183
+ payment provider, an email API, your own microservices) by the host it
184
+ called (`api.stripe.com`), with how many calls failed
185
+ (protocol: `sdk/protocols/calls.md`). Faraday, one line per connection, with
186
+ Faraday's own middleware; nothing is patched:
187
+
188
+ ```ruby
189
+ require "sitegoose/faraday"
190
+
191
+ STRIPE = Faraday.new(url: "https://api.stripe.com") do |f|
192
+ f.request :sitegoose # first, so a retried call counts once
193
+ # ... your other middleware and adapter
194
+ end
195
+ ```
196
+
197
+ Anything else (`Net::HTTP`, a vendor's own client), around the call:
198
+
199
+ ```ruby
200
+ SiteGoose.time_call("https://api.postmarkapp.com", method: "POST") { client.deliver(mail) }
201
+ ```
202
+
203
+ - **Only the host is sent.** A call's path, query string, headers and body
204
+ never leave your server: paths carry IDs and keys.
205
+ - A call that got no answer (refused, timed out, reset), or a 5xx, is a
206
+ failed one; a 4xx is the other side's answer, also when Faraday's
207
+ `raise_error` raises it. A `time_call` block that raises counts as failed.
208
+ - Faraday hands the response back whole, so the time includes reading its
209
+ body.
210
+ - Calls are filed as queries are: under the request, the Sidekiq or
211
+ `platform.job` run, or `JOB (background)`. The package's own calls to us,
212
+ and a watched `click_house` connection's HTTP (they are its queries), are
213
+ left out, and a Faraday call inside a `time_call` block counts once.
214
+ - They ride on Server speed's switch; `calls: false` leaves them out.
215
+
216
+ ## Job queues
217
+
218
+ Server speed → Jobs shows each queue's backlog once a minute: jobs waiting,
219
+ running, delayed and failed, how long the oldest has waited, and jobs added
220
+ against jobs finished, so a queue falling behind shows before the emails go
221
+ out an hour late (protocol: `sdk/protocols/queues.md`). Sidekiq, from the
222
+ same line as above:
223
+
224
+ ```ruby
225
+ # config/initializers/sidekiq.rb
226
+ require "sitegoose/sidekiq"
227
+ SiteGoose::Sidekiq.install
228
+ ```
229
+
230
+ - The Sidekiq process reads them through Sidekiq's API: waiting is each
231
+ queue's size, the oldest wait its latency, running the jobs in progress,
232
+ delayed the scheduled jobs and those waiting to retry, failed the Dead
233
+ set. One Sidekiq process reads a minute; the others only count.
234
+ - Added and finished are counted where they happen: every process that runs
235
+ the initializer (your web servers too) counts the jobs it pushes, and the
236
+ Sidekiq process the jobs that left for good: done, failed on the last
237
+ attempt, or given up. A job is counted once: the client middleware marks
238
+ the job it counted (a `sitegoose_added` field, stored with the job), so
239
+ the scheduler or a retry pushing it back isn't a new one; a retried
240
+ failure isn't finished.
241
+ - Redis is named by host, port and database; never a password.
242
+ - With several queues, a scheduled, retry or Dead set over 1,000 jobs isn't
243
+ counted per queue: that figure is left out rather than read job by job
244
+ every minute. With one queue the set's size is used, and nothing is read.
245
+ - A reading that fails is a gap, not a zero.
246
+ - They ride on Server speed's switch; `queues: false` leaves them out.
247
+
248
+ ## Server limits
249
+
250
+ With `resources` on, each sample also says how close the app is to a wall,
251
+ which on a container or a busy Puma is rarely the machine (protocol:
252
+ `sdk/protocols/resources.md`, "Limits"). Nothing to set up:
253
+
254
+ - The container's memory cap and what counts against it (its working set),
255
+ its CPU cap, how often the cap throttled it, and processes in it killed
256
+ for memory. A cap at or above the machine's own isn't one, so a bare
257
+ machine reports none.
258
+ - Waiting time for CPU, memory and disk (Linux's pressure figures),
259
+ connections refused because the app didn't accept them in time, and how
260
+ full the connection-tracking table is.
261
+ - Open files against the process's limit, and milliseconds in garbage
262
+ collection (Ruby 3.1+).
263
+ - Puma's thread pool: busy threads against `max_threads`, and requests
264
+ waiting for one.
265
+ - The most requests in progress at once, from the middleware's own timing
266
+ (nothing until it has seen a request).
267
+
268
+ Puma's workers each report as themselves, so their figures aren't mixed up.
269
+ Ruby has no heap cap, so no heap figures are sent. Anything this machine
270
+ won't say is left out, never sent as 0.
271
+
158
272
  ## Firewall
159
273
 
160
274
  Rules, monitor or block mode and reports are in the dashboard (Security →
@@ -191,6 +305,11 @@ end
191
305
  SiteGoose.configure(..., firewall: { counter: counter })
192
306
  ```
193
307
 
308
+ The same counter carries the page limits (a cap set in the dashboard on one
309
+ kind of request: the login form, checkout, search), except a limit counted
310
+ per page, which stays in each worker. Over a blocking page limit the visitor
311
+ gets a 429 with `Retry-After` set to that limit's window; nothing is banned.
312
+
194
313
  **Bot protection:** Devise's failed logins are counted on their own;
195
314
  elsewhere call `platform.login_failed(request)` when a login fails. Past the
196
315
  site's limit the address is banned here straight away and on your other
@@ -241,8 +360,8 @@ it can be, after a restart too; each error keeps the time it happened.
241
360
 
242
361
  An error in a request or job also shows the steps before it. Add them with
243
362
  `SiteGoose.add_breadcrumb("Order saved")`; a step added outside a
244
- request or job is dropped. Outgoing HTTP calls aren't recorded on their own
245
- (Ruby has no public hook for them); in Rails the controller, mailer and job
363
+ request or job is dropped. Outgoing HTTP calls aren't steps of their own
364
+ (`Net::HTTP` has no public hook); in Rails the controller, mailer and job
246
365
  notifications are.
247
366
 
248
367
  Background jobs other than Sidekiq's:
@@ -257,7 +376,7 @@ Their errors carry the job's name as the route, a job that raises is sent
257
376
  **Several apps on one site** (a Rails app, a Sidekiq process, a Node service
258
377
  next to it): install the package in each, with the same `site_id`, `secret`
259
378
  and `endpoint`, and a `server_name` of its own. Errors, Server speed,
260
- Crawlers and Security → Updates then tell the apps apart, and Health → All
379
+ Crawlers and Health → Updates then tell the apps apart, and Health → All
261
380
  systems lists each with a light: the package checks in about once a minute
262
381
  (`sdk/protocols/checkin.md`). A service only your other apps call takes
263
382
  `firewall: false, proxy: false, maintenance: false`; on a machine shared by
@@ -0,0 +1,175 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Outgoing calls (sdk/protocols/calls.md), part of Server speed: per minute,
4
+ # request method and route, the host called and the call's own method, how
5
+ # many calls, how many failed, their total and slowest time and a count per
6
+ # time bucket, sent to POST /events/server-calls. Only the host is kept: a
7
+ # call's path, query string, headers and body never leave the server.
8
+ #
9
+ # Caught through public hooks only, never by patching a library:
10
+ # Faraday: the SiteGoose::Faraday middleware, one line per connection
11
+ # (require "sitegoose/faraday"; conn.request :sitegoose).
12
+ # Anything else: SiteGoose.time_call("api.example.com") { ... }.
13
+ # Net::HTTP itself is left alone (nothing in it is a public hook).
14
+ #
15
+ # Filed like queries: under the request or job it ran in, else
16
+ # "JOB" "(background)". A call that got no answer or a 5xx counts as failed;
17
+ # a 4xx is the other side's answer. The package's own calls to the collector
18
+ # are left out, and so are a database client's own HTTP requests (the
19
+ # click_house gem's: they are its queries). Rides on the performance module:
20
+ # with Server speed off nothing is recorded; calls: false keeps Server speed
21
+ # without them.
22
+
23
+ require "uri"
24
+
25
+ module SiteGoose
26
+ class Calls
27
+ include MinuteRows
28
+ FIELDS = %w[call_method host].freeze
29
+ PATH = "/events/server-calls"
30
+ MOD = "calls"
31
+ REQUEST = Context::CALLS
32
+ HOST = /\A[a-z0-9._\-\[\]:]{1,255}\z/.freeze
33
+ CALL_METHOD = /\A[A-Z]{1,10}\z/.freeze
34
+ # Set while time_call times a call, so a Faraday call inside it (a
35
+ # vendor's client built on Faraday) isn't counted a second time.
36
+ TIMING = :sitegoose_call_timing
37
+
38
+ @open = []
39
+ @lock = Mutex.new
40
+ extend OpenList
41
+
42
+ class << self
43
+ def timing?
44
+ Thread.current[TIMING] ? true : false
45
+ end
46
+
47
+ def timing
48
+ saved = Thread.current[TIMING]
49
+ Thread.current[TIMING] = true
50
+ yield
51
+ ensure
52
+ Thread.current[TIMING] = saved
53
+ end
54
+
55
+ # One finished call, from any hook: target a URL (a URI or a string) or
56
+ # a bare host ("api.example.com", "localhost:8080").
57
+ def record(call_method, target, ms, failed: false)
58
+ active&.record(call_method, target, ms, failed: failed)
59
+ rescue StandardError
60
+ nil
61
+ end
62
+
63
+ # A URI for target, or nil.
64
+ def uri_of(target)
65
+ return target if target.is_a?(URI::Generic)
66
+
67
+ text = SiteGoose.text(target).strip
68
+ return nil if text.empty?
69
+
70
+ text = "https://#{text}" unless text.match?(%r{\A[a-zA-Z][a-zA-Z0-9+.-]*://})
71
+ URI.parse(text)
72
+ rescue URI::Error, ArgumentError
73
+ nil
74
+ end
75
+
76
+ # The host as calls.md stores it: lower case, with its port only when
77
+ # it isn't the scheme's own. "" when it isn't one.
78
+ def host_of(target)
79
+ uri = uri_of(target)
80
+ return "" if uri.nil? || uri.host.nil? || uri.host.empty?
81
+
82
+ host = uri.host.downcase
83
+ host = "#{host}:#{uri.port}" if uri.port && uri.port != uri.default_port
84
+ host.match?(HOST) ? host : ""
85
+ rescue StandardError
86
+ ""
87
+ end
88
+
89
+ # scheme://host[:port]/path, lower case and without a trailing slash,
90
+ # to tell the package's own calls to the collector from the app's.
91
+ def address_of(target)
92
+ uri = uri_of(target)
93
+ return "" if uri.nil? || uri.host.nil?
94
+
95
+ port = uri.port && uri.port != uri.default_port ? ":#{uri.port}" : ""
96
+ "#{uri.scheme.to_s.downcase}://#{uri.host.downcase}#{port}#{uri.path.to_s.sub(%r{/+\z}, '')}"
97
+ rescue StandardError
98
+ ""
99
+ end
100
+
101
+ # The status an HTTP library's error carries (Faraday's raise_error:
102
+ # a 404 raised is still the other side's answer), or nil.
103
+ def status_of_error(error)
104
+ return error.response_status.to_i if error.respond_to?(:response_status) && error.response_status
105
+ return nil unless error.respond_to?(:response)
106
+
107
+ response = error.response
108
+ status = response.is_a?(Hash) ? (response[:status] || response["status"]) : nil
109
+ status&.to_i
110
+ rescue StandardError
111
+ nil
112
+ end
113
+
114
+ # Whether a call that ended with status failed: no answer, or a 5xx.
115
+ def failed_status?(status)
116
+ status = status.respond_to?(:to_i) ? status.to_i : 0
117
+ !(status.positive? && status < 500)
118
+ end
119
+ end
120
+
121
+ def initialize(core, server_name: nil)
122
+ start_rows(core, server_name)
123
+ @own = Calls.address_of(core.endpoint)
124
+ Calls.opened(self)
125
+ end
126
+
127
+ # The package's own calls to the collector.
128
+ def own?(target)
129
+ return false if @own.empty?
130
+
131
+ address = Calls.address_of(target)
132
+ address == @own || address.start_with?("#{@own}/")
133
+ end
134
+
135
+ # One finished call: into its request's (or job's) calls, or, with none
136
+ # around it, straight into the minute's rows as background.
137
+ def record(call_method, target, ms, failed: false)
138
+ return unless on?
139
+ return if own?(target)
140
+
141
+ host = Calls.host_of(target)
142
+ call_method = SiteGoose.text(call_method.nil? ? "GET" : call_method).upcase
143
+ return if host.empty? || !call_method.match?(CALL_METHOD)
144
+
145
+ file(call_method, host, ms, failed)
146
+ end
147
+
148
+ def close
149
+ Calls.closed(self)
150
+ stop_rows
151
+ end
152
+ end
153
+
154
+ # Times one outgoing call made by anything the Faraday middleware doesn't
155
+ # see (Health -> Server speed -> Calls): target is the URL or host called.
156
+ # The block's result is returned; a block that raises counts as a failed
157
+ # call and the exception is raised on (a block left with return, break or
158
+ # next is a call that ended). Only the host is kept.
159
+ #
160
+ # SiteGoose.time_call("https://api.stripe.com", method: "POST") { stripe.charge(...) }
161
+ def self.time_call(target, method: "GET")
162
+ return yield if Calls.active.nil? || Queries.timing? || Calls.timing?
163
+
164
+ started = clock
165
+ failed = false
166
+ begin
167
+ Calls.timing { yield }
168
+ rescue Exception # rubocop:disable Lint/RescueException -- raised on; a timeout is a call with no answer
169
+ failed = true
170
+ raise
171
+ ensure
172
+ Calls.record(method, target, (clock - started) * 1000, failed: failed)
173
+ end
174
+ end
175
+ end
@@ -27,6 +27,7 @@ module SiteGoose
27
27
  REQUEST = :sitegoose_request
28
28
  TRAIL = :sitegoose_trail
29
29
  QUERIES = :sitegoose_queries
30
+ CALLS = :sitegoose_calls
30
31
  CRUMB_MAX = 15
31
32
 
32
33
  module_function
@@ -40,16 +41,17 @@ module SiteGoose
40
41
  end
41
42
 
42
43
  # Runs the block as one request or job: fields (a callable or a hash), a
43
- # new trail and no database queries yet (Queries), all put back as they
44
- # were afterwards.
44
+ # new trail and no database queries or outgoing calls yet (Queries,
45
+ # Calls), all put back as they were afterwards.
45
46
  def with(fields)
46
- saved = [Thread.current[REQUEST], Thread.current[TRAIL], Thread.current[QUERIES]]
47
+ saved = [Thread.current[REQUEST], Thread.current[TRAIL], Thread.current[QUERIES], Thread.current[CALLS]]
47
48
  Thread.current[REQUEST] = fields
48
49
  Thread.current[TRAIL] = []
49
50
  Thread.current[QUERIES] = nil
51
+ Thread.current[CALLS] = nil
50
52
  yield
51
53
  ensure
52
- Thread.current[REQUEST], Thread.current[TRAIL], Thread.current[QUERIES] = saved
54
+ Thread.current[REQUEST], Thread.current[TRAIL], Thread.current[QUERIES], Thread.current[CALLS] = saved
53
55
  end
54
56
 
55
57
  def add_breadcrumb(text, type = "note")
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Outgoing calls made through Faraday (sdk/protocols/calls.md), timed by a
4
+ # Faraday middleware: Faraday's own public extension point, so neither
5
+ # Faraday nor its adapter is changed. One line per connection:
6
+ #
7
+ # require "sitegoose/faraday"
8
+ # conn = Faraday.new(url: "https://api.stripe.com") do |f|
9
+ # f.request :sitegoose # first, so a retried call is timed once
10
+ # ...
11
+ # end
12
+ # # or: conn.use SiteGoose::Faraday
13
+ #
14
+ # A call is timed from being handed to the adapter to Faraday handing the
15
+ # response back (with a parallel adapter, its on_complete). Faraday gives the
16
+ # answer over whole, so a body read with it is in the time; a body streamed
17
+ # with on_data is too. Only the host is kept (Calls).
18
+
19
+ require "faraday"
20
+ require_relative "../sitegoose" unless defined?(SiteGoose::Calls)
21
+
22
+ module SiteGoose
23
+ class Faraday < ::Faraday::Middleware
24
+ def call(env)
25
+ return @app.call(env) if Calls.active.nil? || Queries.timing? || Calls.timing?
26
+
27
+ started = SiteGoose.clock
28
+ call_method = env.method.to_s.upcase
29
+ url = env.url
30
+ begin
31
+ response = @app.call(env)
32
+ rescue Exception => e # rubocop:disable Lint/RescueException -- raised on; a timeout around it is no answer
33
+ # raise_error inside this middleware: a 4xx raised is still an answer.
34
+ Calls.record(call_method, url, (SiteGoose.clock - started) * 1000,
35
+ failed: Calls.failed_status?(Calls.status_of_error(e)))
36
+ raise
37
+ end
38
+ return response unless response.respond_to?(:on_complete)
39
+
40
+ response.on_complete do |done|
41
+ status = done.respond_to?(:status) ? done.status : nil
42
+ Calls.record(call_method, url, (SiteGoose.clock - started) * 1000, failed: Calls.failed_status?(status))
43
+ end
44
+ response
45
+ end
46
+ end
47
+
48
+ # f.request :sitegoose, f.use :sitegoose, f.response :sitegoose all name it.
49
+ [::Faraday::Request, ::Faraday::Middleware, ::Faraday::Response].each do |registry|
50
+ registry.register_middleware(sitegoose: SiteGoose::Faraday) if registry.respond_to?(:register_middleware)
51
+ rescue StandardError
52
+ nil
53
+ end
54
+ end