visionary-sdk 0.4.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.
Files changed (39) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +19 -0
  3. data/LICENSE +202 -0
  4. data/README.md +198 -0
  5. data/lib/visionary/agent.rb +174 -0
  6. data/lib/visionary/body.rb +162 -0
  7. data/lib/visionary/config.rb +151 -0
  8. data/lib/visionary/context.rb +97 -0
  9. data/lib/visionary/fork.rb +16 -0
  10. data/lib/visionary/middleware.rb +169 -0
  11. data/lib/visionary/queue.rb +57 -0
  12. data/lib/visionary/railtie.rb +48 -0
  13. data/lib/visionary/redactor.rb +94 -0
  14. data/lib/visionary/retention.rb +90 -0
  15. data/lib/visionary/schema/mysql/requests.sql +37 -0
  16. data/lib/visionary/schema/mysql/system.sql +76 -0
  17. data/lib/visionary/schema/mysql/telemetry.sql +52 -0
  18. data/lib/visionary/schema/postgres/requests.sql +37 -0
  19. data/lib/visionary/schema/postgres/system.sql +76 -0
  20. data/lib/visionary/schema/postgres/telemetry.sql +52 -0
  21. data/lib/visionary/schema/sqlite/requests.sql +37 -0
  22. data/lib/visionary/schema/sqlite/system.sql +76 -0
  23. data/lib/visionary/schema/sqlite/telemetry.sql +52 -0
  24. data/lib/visionary/schema.rb +163 -0
  25. data/lib/visionary/schemas.rb +64 -0
  26. data/lib/visionary/store/active_record.rb +103 -0
  27. data/lib/visionary/store/d1.rb +129 -0
  28. data/lib/visionary/store/sql.rb +272 -0
  29. data/lib/visionary/store.rb +53 -0
  30. data/lib/visionary/system/recorder.rb +353 -0
  31. data/lib/visionary/system/sources.rb +191 -0
  32. data/lib/visionary/telemetry/errors.rb +118 -0
  33. data/lib/visionary/telemetry/hooks.rb +115 -0
  34. data/lib/visionary/telemetry/sql_text.rb +44 -0
  35. data/lib/visionary/telemetry.rb +116 -0
  36. data/lib/visionary/version.rb +5 -0
  37. data/lib/visionary/writer.rb +185 -0
  38. data/lib/visionary.rb +157 -0
  39. metadata +90 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5d9bc46402d28b75e7053fcfa03ac8161a77701c23ba450641dda44385a4e9c9
4
+ data.tar.gz: f516ea1508f97c1ad0d7729013fcd400f8de25768338438d658d7c7d01dde94e
5
+ SHA512:
6
+ metadata.gz: 86c78e45acd34ee3c5fd8bb0733618a7eb9957bc1b1a2cb9ad18c0160504bcbbddf0f49873acd8a16509aaa0062e144f8273b13196d9f6267696ff772256b4ac
7
+ data.tar.gz: 2f750c54be572e26ec4ebcdfc670d69de77a172003bbdf5613e0935514b9f46cdcea91ca327ca7d8dbe24c80e981348e01a7940ef7610e6bb68822c3c5361dd2
data/CHANGELOG.md ADDED
@@ -0,0 +1,19 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ First release of the Ruby SDK (`visionary-sdk`, `require "visionary"`).
6
+
7
+ - Rack middleware for any Rack app, and a Railtie for Rails: one `api_logs`
8
+ row per request with route patterns (Rails, Sinatra, Grape), redacted
9
+ headers and bodies, error codes, users (`Visionary.set_user`) and per-request
10
+ database and HTTP call totals.
11
+ - Spans from `sql.active_record` and `Net::HTTP`, plus `Visionary.span`;
12
+ errors from exceptions escaping the app or rendered as 5xx, plus
13
+ `Visionary.capture_exception`; a `releases` row per process start.
14
+ - System metrics every 15 s, with the node-level columns from `/proc` on Linux.
15
+ - Storage: PostgreSQL (`pg`), MySQL (`mysql2`), SQLite (`sqlite3`), Cloudflare
16
+ D1 over HTTPS, or the app's ActiveRecord pool. Older tables gain new columns
17
+ at startup.
18
+ - Background threads restart in forked workers (Puma, Unicorn) through
19
+ `Process._fork`.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # visionary-sdk (Ruby)
2
+
3
+ The Ruby collector for [Visionary](../../Readme.md). It runs inside your Rack
4
+ or Rails service and writes:
5
+
6
+ - one row per HTTP request into `api_logs` (method, route pattern, status,
7
+ timing, user, redacted headers and bodies, error codes, and how many
8
+ database and outbound HTTP calls the request made),
9
+ - `spans` for database statements and outbound HTTP calls of slow or failed
10
+ requests, `errors` for exceptions, and a `releases` row per deploy,
11
+ - a periodic host / process / runtime sample into `system_metrics`.
12
+
13
+ The Visionary server reads these tables for its dashboards. All slow work
14
+ happens on background threads, so requests are never blocked or slowed. If
15
+ the database is down, the SDK only writes log lines.
16
+
17
+ Every Visionary SDK behaves the same way. The contract is
18
+ [`sdks/SPEC.md`](../SPEC.md).
19
+
20
+ ## Install
21
+
22
+ ```ruby
23
+ # Gemfile
24
+ gem "visionary-sdk", require: "visionary"
25
+ ```
26
+
27
+ Requires Ruby 3.1+. The gem has no runtime dependencies. To write through a
28
+ database URL, the app needs that database's driver: `pg`, `mysql2` or
29
+ `sqlite3`. Cloudflare D1 needs nothing (it is called over HTTPS with
30
+ `Net::HTTP`), and an ActiveRecord app can hand over its own pool instead.
31
+
32
+ ## Quickstart
33
+
34
+ First configure a database (see [Choosing the database](#choosing-the-database)), for example:
35
+
36
+ ```sh
37
+ export VISIONARY_DATABASE_URL=postgres://user:pass@localhost:5432/app
38
+ ```
39
+
40
+ ### Rails
41
+
42
+ Adding the gem is enough: the Railtie inserts `Visionary::Middleware` first in
43
+ the middleware stack, records ActiveRecord queries as spans, and sees the
44
+ exceptions Rails turns into error pages. Collection starts with the first
45
+ request.
46
+
47
+ ```ruby
48
+ # config/initializers/visionary.rb (optional)
49
+ Visionary.configure do |c|
50
+ c.connection = ActiveRecord::Base # write through the app's pool instead of a URL
51
+ c.lookup_user = ->(id) { u = User.find_by(id: id); u && [u.email, u.role] }
52
+ end
53
+
54
+ # app/controllers/application_controller.rb
55
+ before_action { Visionary.set_user(current_user.id, handle: current_user.email, role: current_user.role) if current_user }
56
+ ```
57
+
58
+ - **Route:** the Rails route pattern, `request.route_uri_pattern` on Rails
59
+ 7.1+ (older versions recognize the request again), without `(.:format)`,
60
+ e.g. `/users/:id`.
61
+ - **Request id:** Visionary's id is handed to Rails, so `request.request_id`
62
+ and the `X-Request-ID` response header match the `api_logs` row.
63
+ - **Errors:** exceptions that become a 5xx response are recorded with
64
+ `handled = 0`; ones Rails maps to a 4xx (`RecordNotFound`, routing errors)
65
+ are not errors.
66
+
67
+ ### Sinatra (and any Rack app: Hanami, Roda, Grape)
68
+
69
+ ```ruby
70
+ # config.ru
71
+ require "visionary"
72
+ use Visionary::Middleware # first, so it sees the final response
73
+ run MyApp
74
+ ```
75
+
76
+ Sinatra and Grape route patterns are read automatically
77
+ (`env["sinatra.route"]`, Grape's route info). For other routers, call
78
+ `Visionary.set_route("/users/:id")` in the handler, or configure a resolver:
79
+
80
+ ```ruby
81
+ Visionary.configure { |c| c.route = ->(env) { env["my.router.pattern"] } }
82
+ ```
83
+
84
+ ## API
85
+
86
+ ```ruby
87
+ Visionary.set_user(id, handle: nil, role: nil) # the signed-in user of the current request
88
+ Visionary.set_route("/users/:id") # route pattern, for routers Visionary can't see
89
+ Visionary.span("charge card", kind: "http", target: "api.stripe.com") { ... } # a manual span
90
+ Visionary.capture_exception(e) # a handled error (handled = 1)
91
+ Visionary.start # start now instead of on the first request
92
+ Visionary.close(10) # flush; also runs at exit
93
+ ```
94
+
95
+ `set_user`, `set_route` and spans attach to the request being handled. The
96
+ request is kept in fiber storage (Ruby 3.2+, inherited by child fibers and
97
+ threads) or a fiber-local variable on 3.1, so this works under Puma, Falcon
98
+ and in Async tasks. `lookup_user` runs on the writer thread, once per distinct
99
+ user per batch, for users missing a handle or role.
100
+
101
+ ## Spans and errors
102
+
103
+ - **Database:** every `sql.active_record` notification except `SCHEMA` and
104
+ cached queries becomes a `db` span named after the statement (`SELECT
105
+ users`, `INSERT bookings`, `BEGIN`), with the statement sanitized (literals
106
+ replaced by `?`, `IN (...)` collapsed). Parameter values are never stored.
107
+ - **Outbound HTTP:** `Net::HTTP` (and clients built on it, such as Faraday's
108
+ default adapter and HTTParty) becomes `http` spans named `METHOD host`; a
109
+ 5xx answer or a transport error marks the span as an error.
110
+ - **Manual:** `Visionary.span` for anything else (`cache`, `queue`, `custom`).
111
+
112
+ Every logged request gets `db_count`, `db_ms`, `http_count`, `http_ms`
113
+ (`db_*` are NULL when ActiveRecord isn't loaded and no `db` span was
114
+ recorded). Span rows are stored only for requests that took at least
115
+ `VISIONARY_SPAN_THRESHOLD_MS` or answered 5xx, at most `VISIONARY_SPAN_MAX`
116
+ per request; spans outside requests are stored when they take at least the
117
+ threshold themselves. Visionary's own writes never become spans.
118
+
119
+ Exceptions that escape the app are recorded and re-raised unchanged; the
120
+ middleware logs the request as 500. Errors are grouped by a fingerprint over
121
+ the exception class and the top five frames of your own code (not gems, the
122
+ standard library or this SDK), as `method@path` relative to the working
123
+ directory, so it is stable across deploys and line changes.
124
+
125
+ ## Forking servers (Puma, Unicorn)
126
+
127
+ Threads don't survive `fork`. Visionary hooks `Process._fork` (Ruby 3.1+), so
128
+ when Puma or Unicorn forks workers after the agent started (for example with
129
+ `preload_app!` and an initializer that calls `Visionary.start`), each worker
130
+ restarts its writer, sampler and retention threads with fresh queues and
131
+ connections. If you prefer to be explicit, Puma's hook does the same and is
132
+ safe to combine with it:
133
+
134
+ ```ruby
135
+ # config/puma.rb
136
+ on_worker_boot { Visionary.after_fork }
137
+ on_worker_shutdown { Visionary.close }
138
+ ```
139
+
140
+ Without an explicit start, each worker starts collection on its first
141
+ request, and nothing runs in the master.
142
+
143
+ ## Choosing the database
144
+
145
+ In this order:
146
+
147
+ 1. `Visionary.config.connection = ActiveRecord::Base` (or any abstract
148
+ connection class, e.g. one with its own `connects_to` database). Each write
149
+ checks a connection out of that pool on the background thread and returns
150
+ it right after; Visionary uses at most one pool connection at a time.
151
+ 2. `VISIONARY_DATABASE_URL`: `postgres://` / `postgresql://` (gem `pg`),
152
+ `mysql://` (gem `mysql2`), `sqlite:///absolute/path.db` or
153
+ `sqlite://relative.db` (gem `sqlite3`). Visionary opens one connection of
154
+ its own and reopens it after errors.
155
+ 3. Cloudflare D1: `D1_ACCOUNT_ID`, `D1_DATABASE_ID`, `D1_API_TOKEN` (and
156
+ `D1_API_BASE` for a proxy), or `VISIONARY_DATABASE_URL=d1://` with those.
157
+
158
+ The tables (`api_logs`, `system_metrics`, `spans`, `errors`, `releases`) are
159
+ created on first use, and tables from older versions gain the newer columns.
160
+ With no database configured, Visionary logs one warning and does nothing.
161
+
162
+ ## System metrics
163
+
164
+ Every `VISIONARY_SYSTEM_INTERVAL` a sample is written (four per batch). On
165
+ Linux the host and node columns come from `/proc` (CPU split, load, memory,
166
+ swap, disk I/O, network, TCP, processes, context switches) and `df` (disk
167
+ usage). Process CPU comes from `Process.clock_gettime`, GC count and time
168
+ from `GC.stat`, heap from `GC.stat` slot and page counts, threads from
169
+ `/proc/self/status` (else `Thread.list`). Pool columns come from the
170
+ ActiveRecord pool when it exists, or from `c.db_stats = -> { { total:, idle:,
171
+ in_use:, max: } }`. On macOS and Windows most host columns are NULL.
172
+
173
+ ## Configuration
174
+
175
+ Everything comes from the environment (see the table in
176
+ [`sdks/SPEC.md`](../SPEC.md#environment)); `Visionary.configure` sets the same
177
+ options in code (`c.path_prefix = "/api"`, `c.capture_bodies = false`, ...)
178
+ plus the hooks above. Set it before the first request.
179
+
180
+ | Variable | Default |
181
+ |---|---|
182
+ | `VISIONARY_DATABASE_URL` | — |
183
+ | `VISIONARY_INSTANCE` | hostname |
184
+ | `VISIONARY_LOG_REQUESTS`, `VISIONARY_LOG_BODIES` | `true` |
185
+ | `VISIONARY_LOG_PATH_PREFIX` | everything |
186
+ | `VISIONARY_LOG_MAX_BODY_BYTES` | `8192` |
187
+ | `VISIONARY_LOG_RETENTION_DAYS`, `VISIONARY_SYSTEM_RETENTION_DAYS` | `30` (0 keeps forever) |
188
+ | `VISIONARY_LOG_REDACT_HEADERS`, `_REDACT_FIELDS`, `_REDACT_REQUEST_FIELDS` | added to the defaults |
189
+ | `VISIONARY_LOG_ERROR_CODE_FIELD`, `_ERROR_KEY_FIELD` | `error.code`, `error.key` |
190
+ | `VISIONARY_SYSTEM_METRICS` | `true` |
191
+ | `VISIONARY_SYSTEM_INTERVAL` | `15s` |
192
+ | `VISIONARY_SERVICE` | NULL |
193
+ | `VISIONARY_RELEASE` | the platform's commit variable, shortened to 12 characters |
194
+ | `VISIONARY_SPANS`, `VISIONARY_ERRORS` | `true` |
195
+ | `VISIONARY_SPAN_THRESHOLD_MS`, `VISIONARY_SPAN_MAX` | `100`, `100` |
196
+
197
+ Request bodies are captured as the app reads them, so a body the app never
198
+ reads is not stored (its size still is, from `Content-Length`).
@@ -0,0 +1,174 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+
5
+ module Visionary
6
+ # Logs to stderr when the app gives no logger (the logger gem leaves the
7
+ # default gems in Ruby 3.5, so it is not required here).
8
+ class StderrLogger
9
+ LEVELS = { debug: 0, info: 1, warn: 2, error: 3 }.freeze
10
+
11
+ def initialize(level = :info, io = $stderr)
12
+ @level = LEVELS.fetch(level)
13
+ @io = io
14
+ end
15
+
16
+ LEVELS.each do |name, n|
17
+ define_method(name) do |msg = nil, &block|
18
+ return if n < @level
19
+ @io.puts("#{Visionary.timestamp(Time.now)} #{name.upcase} #{msg || block&.call}")
20
+ rescue IOError
21
+ nil
22
+ end
23
+ end
24
+ end
25
+
26
+ # Runs request logging, telemetry and system metrics for one process. With
27
+ # no database configured it logs one warning and every call is a no-op; it
28
+ # never raises into the app once built.
29
+ class Agent
30
+ attr_reader :config, :http, :telemetry, :logger, :instance
31
+
32
+ def initialize(cfg)
33
+ @config = cfg
34
+ @logger = cfg.logger || StderrLogger.new
35
+ @http = System::HttpCounters.new
36
+ @closed = false
37
+ @started = false
38
+ @lock = Mutex.new
39
+ @store = open_store(cfg)
40
+ return unless @store
41
+
42
+ @instance = cfg.instance.to_s.empty? ? Socket.gethostname : cfg.instance
43
+ @schemas = Schemas.new(@store, @logger)
44
+ if cfg.log_requests || cfg.spans || cfg.errors || cfg.version
45
+ @writer = Writer.new(cfg, @store, @schemas, @logger)
46
+ end
47
+ @telemetry = Telemetry::Recorder.new(cfg, @instance, @writer) if cfg.spans || cfg.errors
48
+ if cfg.system_metrics && cfg.system_interval.to_f.positive?
49
+ @system = System::Recorder.new(cfg, @instance, @store, @schemas, @http, @logger)
50
+ end
51
+ tables = {}
52
+ tables["api_logs"] = cfg.log_retention_days if cfg.log_requests
53
+ if @telemetry
54
+ tables["spans"] = cfg.log_retention_days
55
+ tables["errors"] = cfg.log_retention_days
56
+ end
57
+ tables["system_metrics"] = cfg.system_retention_days if @system
58
+ @retention = Retention.new(@store, @logger, tables)
59
+ end
60
+
61
+ def enabled? = !@store.nil? && !@closed && (!@writer.nil? || !@system.nil?)
62
+
63
+ def log_path?(path) = @config.log_requests && !@writer.nil? && path.start_with?(@config.path_prefix.to_s)
64
+
65
+ # Queues a row for the writer; never blocks.
66
+ def enqueue(item)
67
+ @writer&.enqueue(item) unless @closed
68
+ end
69
+
70
+ # The route pattern for a finished request: the app's own resolver,
71
+ # then what the framework left in the env.
72
+ def route_for(env)
73
+ route = @config.route ? System::Sources.quiet { @config.route.call(env) }.to_s : ""
74
+ route = framework_route(env) if route.empty?
75
+ route.sub(/\(\.:format\)\z/, "")
76
+ end
77
+
78
+ # Launches the background threads. Tables are created on them, so a slow
79
+ # or unreachable database never delays startup. Safe to call twice.
80
+ def start
81
+ @lock.synchronize do
82
+ return self if @started || @closed || !enabled?
83
+ @started = true
84
+ @pid = Process.pid
85
+ end
86
+ @writer&.start
87
+ if @config.log_requests
88
+ @logger.info("visionary: logging requests (path_prefix=#{@config.path_prefix.inspect}, " \
89
+ "bodies=#{@config.capture_bodies}, retention_days=#{@config.log_retention_days})")
90
+ end
91
+ if @system
92
+ @system.start
93
+ @logger.info("visionary: recording system metrics every #{@config.system_interval}s as #{@instance}")
94
+ end
95
+ @retention.start
96
+ install_hooks
97
+ release
98
+ self
99
+ end
100
+
101
+ # Flushes queued rows and buffered samples, waiting at most timeout
102
+ # seconds in total.
103
+ def close(timeout = 10)
104
+ @lock.synchronize do
105
+ return if @closed
106
+ @closed = true
107
+ end
108
+ deadline = mono + timeout
109
+ @retention&.close
110
+ idle = @writer ? @writer.close(timeout) : true
111
+ idle = @system.close([deadline - mono, 0].max) && idle if @system
112
+ @store.close if idle && @store
113
+ rescue StandardError => e
114
+ @logger.error("visionary: close failed: #{e.message}")
115
+ end
116
+
117
+ # Threads don't survive fork (Puma and Unicorn workers with preloading):
118
+ # restart them in the child with fresh queues and connections.
119
+ def after_fork
120
+ return unless @started && !@closed && @pid != Process.pid
121
+ @pid = Process.pid
122
+ @lock = Mutex.new
123
+ @http = System::HttpCounters.new
124
+ @store.after_fork
125
+ @schemas.after_fork
126
+ @system&.http = @http
127
+ @system&.after_fork
128
+ @writer&.after_fork
129
+ @retention&.after_fork if @retention&.needed?
130
+ @logger.info("visionary: restarted in forked process #{@pid}")
131
+ end
132
+
133
+ private
134
+
135
+ def open_store(cfg)
136
+ store = Store.open(cfg)
137
+ unless store
138
+ @logger.warn("visionary: no database configured (set VISIONARY_DATABASE_URL or D1_*); collection is off")
139
+ end
140
+ store
141
+ rescue StandardError => e
142
+ @logger.warn("#{e.message}; collection is off")
143
+ nil
144
+ end
145
+
146
+ def install_hooks
147
+ return unless @telemetry&.spans_on
148
+ Telemetry::NetHTTPHook.install
149
+ Telemetry::ActiveRecordHook.install if defined?(::ActiveRecord::Base) && defined?(::ActiveSupport::Notifications)
150
+ rescue StandardError => e
151
+ @logger.warn("visionary: span hooks not installed: #{e.message}")
152
+ end
153
+
154
+ # One deploy marker per process start when the release is known.
155
+ def release
156
+ return unless @writer && @config.version
157
+ @writer.enqueue([:release, [Visionary.timestamp(Time.now), @config.service, @instance, @config.version,
158
+ "ruby", VERSION, Telemetry.runtime]])
159
+ end
160
+
161
+ def framework_route(env)
162
+ if (p = env["action_dispatch.route_uri_pattern"]) then p.to_s
163
+ elsif (r = env["sinatra.route"]) then r.to_s.split(" ", 2).last.to_s
164
+ elsif (info = env["grape.routing_args"]) && info.is_a?(Hash) && info[:route_info].respond_to?(:path)
165
+ info[:route_info].path.to_s
166
+ else ""
167
+ end
168
+ rescue StandardError
169
+ ""
170
+ end
171
+
172
+ def mono = Process.clock_gettime(Process::CLOCK_MONOTONIC)
173
+ end
174
+ end