sentrace 0.0.1

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 (55) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.txt +21 -0
  3. data/README.md +192 -0
  4. data/app/controllers/sentrace/application_controller.rb +4 -0
  5. data/app/controllers/sentrace/ingestion_controller.rb +169 -0
  6. data/app/controllers/sentrace/internal/base_controller.rb +47 -0
  7. data/app/controllers/sentrace/internal/events_controller.rb +25 -0
  8. data/app/controllers/sentrace/internal/issues_controller.rb +36 -0
  9. data/app/controllers/sentrace/internal/projects_controller.rb +58 -0
  10. data/app/controllers/sentrace/internal/stats_controller.rb +10 -0
  11. data/app/controllers/sentrace/mcp_controller.rb +74 -0
  12. data/app/jobs/sentrace/retention_cleanup_job.rb +9 -0
  13. data/app/models/sentrace/application_record.rb +5 -0
  14. data/app/models/sentrace/event.rb +41 -0
  15. data/app/models/sentrace/issue.rb +32 -0
  16. data/app/models/sentrace/mcp_token.rb +82 -0
  17. data/app/models/sentrace/project.rb +50 -0
  18. data/app/models/sentrace/project_key.rb +60 -0
  19. data/config/routes.rb +11 -0
  20. data/db/migrate/20261116000001_create_sentrace_projects.rb +12 -0
  21. data/db/migrate/20261116000002_create_sentrace_project_keys.rb +14 -0
  22. data/db/migrate/20261116000003_create_sentrace_issues.rb +25 -0
  23. data/db/migrate/20261116000004_create_sentrace_events.rb +31 -0
  24. data/db/migrate/20261116000005_create_sentrace_mcp_tokens.rb +17 -0
  25. data/lib/generators/sentrace/install/install_generator.rb +91 -0
  26. data/lib/generators/sentrace/install/templates/initializer.rb.tt +34 -0
  27. data/lib/generators/sentrace/install/templates/sentrace_setup.rake.tt +21 -0
  28. data/lib/sentrace/benchmark/storage_runner.rb +289 -0
  29. data/lib/sentrace/configuration.rb +198 -0
  30. data/lib/sentrace/dsn.rb +123 -0
  31. data/lib/sentrace/engine.rb +10 -0
  32. data/lib/sentrace/errors.rb +20 -0
  33. data/lib/sentrace/ingestion/envelope_parser.rb +143 -0
  34. data/lib/sentrace/ingestion/event_normalizer.rb +315 -0
  35. data/lib/sentrace/ingestion/processor.rb +90 -0
  36. data/lib/sentrace/ingestion/sanitizer.rb +293 -0
  37. data/lib/sentrace/issues/fingerprint.rb +177 -0
  38. data/lib/sentrace/issues/grouper.rb +184 -0
  39. data/lib/sentrace/mcp/dispatcher.rb +23 -0
  40. data/lib/sentrace/mcp/environment_router.rb +266 -0
  41. data/lib/sentrace/mcp/local_backend.rb +425 -0
  42. data/lib/sentrace/mcp/remote_http_client.rb +310 -0
  43. data/lib/sentrace/mcp/server.rb +417 -0
  44. data/lib/sentrace/mcp/stdio_runner.rb +55 -0
  45. data/lib/sentrace/mcp/token_manager.rb +73 -0
  46. data/lib/sentrace/project_manager.rb +64 -0
  47. data/lib/sentrace/retention/cleaner.rb +105 -0
  48. data/lib/sentrace/storage_stats.rb +136 -0
  49. data/lib/sentrace/version.rb +3 -0
  50. data/lib/sentrace.rb +40 -0
  51. data/lib/tasks/sentrace_benchmark.rake +9 -0
  52. data/lib/tasks/sentrace_mcp.rake +36 -0
  53. data/lib/tasks/sentrace_projects.rake +22 -0
  54. data/lib/tasks/sentrace_retention.rake +16 -0
  55. metadata +148 -0
@@ -0,0 +1,289 @@
1
+ require "json"
2
+ require "securerandom"
3
+
4
+ module Sentrace
5
+ module Benchmark
6
+ class StorageRunner
7
+ DEFAULT_EVENT_COUNT = 500
8
+ DISTINCT_ISSUE_COUNT = 25
9
+
10
+ EXCEPTION_CLASSES = %w[
11
+ ActiveRecord::RecordNotFound
12
+ Stripe::CardError
13
+ Redis::TimeoutError
14
+ NoMethodError
15
+ ActionController::ParameterMissing
16
+ ].freeze
17
+
18
+ class << self
19
+ def run(event_count: DEFAULT_EVENT_COUNT, batch_size: 250, cleanup: true)
20
+ new(event_count: event_count, batch_size: batch_size, cleanup: cleanup).run
21
+ end
22
+
23
+ def print_report(event_count: DEFAULT_EVENT_COUNT, batch_size: 250, io: $stdout)
24
+ report = run(event_count: event_count, batch_size: batch_size, cleanup: true)
25
+ io.puts "=== Sentrace PostgreSQL Storage & Performance Benchmark ==="
26
+ io.puts "Events generated: #{report["event_count"]} (#{report["distinct_issues"]} distinct issues)"
27
+ io.puts "DB size before ingestion: #{report["db_bytes_before"]} bytes"
28
+ io.puts "DB size after ingestion: #{report["db_bytes_after"]} bytes (delta: +#{report["net_storage_delta_bytes"]} bytes)"
29
+ io.puts "Avg PostgreSQL bytes / event: #{report["avg_bytes_per_event"]} bytes"
30
+ io.puts "Index overhead (after): #{report["index_overhead_bytes"]} bytes (#{report["index_overhead_pct"]}%)"
31
+ io.puts "Envelope parse latency (avg): #{report["envelope_parse_ms"]} ms (target < 50 ms)"
32
+ io.puts "Event persist latency (avg): #{report["event_persist_avg_ms"]} ms (target < 100 ms)"
33
+ io.puts "Write throughput: #{report["write_events_per_second"]} events/sec"
34
+ io.puts "Issue lookup latency: #{report["issue_lookup_ms"]} ms (target < 100 ms)"
35
+ io.puts "Event retrieval latency: #{report["event_retrieval_ms"]} ms (target < 100 ms)"
36
+ io.puts "MCP list_issues latency: #{report["mcp_list_issues_ms"]} ms (target < 500 ms)"
37
+ io.puts "Retention delete throughput: #{report["retention_delete_events_per_second"]} events/sec (#{report["retention_deleted_events"]} pruned)"
38
+ report
39
+ end
40
+ end
41
+
42
+ def initialize(event_count: DEFAULT_EVENT_COUNT, batch_size: 250, cleanup: true)
43
+ @event_count = [ event_count.to_i, 1 ].max
44
+ @batch_size = [ batch_size.to_i, 1 ].max
45
+ @cleanup = cleanup
46
+ end
47
+
48
+ def run
49
+ slug = "bench-#{SecureRandom.hex(6)}"
50
+ project, key = Project.provision!(slug: slug, name: "Sentrace Storage Benchmark")
51
+ dsn = Dsn.build(base_url: "http://localhost:3000/sentrace", public_key: key.public_key, project_id: project.id).to_s
52
+
53
+ vacuum_sentrace_tables_if_allowed!
54
+ before_stats = StorageStats.collect
55
+
56
+ envelopes = Array.new(@event_count) { |idx| build_representative_envelope(idx, dsn: dsn) }
57
+
58
+ # 1. Measure envelope parsing latency
59
+ parse_samples = envelopes.first([ 25, envelopes.size ].min)
60
+ parse_started = monotonic_now
61
+ parse_samples.each { |raw| Ingestion::EnvelopeParser.parse(raw) }
62
+ envelope_parse_ms = (((monotonic_now - parse_started) / parse_samples.size) * 1_000.0).round(3)
63
+
64
+ # 2. Measure ingestion + PostgreSQL persistence throughput & latency
65
+ bench_config = Sentrace.configuration.dup
66
+ bench_config.retention_period = 30.days
67
+ bench_config.retention_batch_size = @batch_size
68
+
69
+ ingest_started = monotonic_now
70
+ envelopes.each do |raw|
71
+ Ingestion::Processor.process_raw_envelope(raw, project: project.id, config: bench_config)
72
+ end
73
+ ingest_elapsed = [ monotonic_now - ingest_started, 0.000_001 ].max
74
+ event_persist_avg_ms = ((ingest_elapsed / @event_count) * 1_000.0).round(3)
75
+ write_eps = (@event_count / ingest_elapsed).round(1)
76
+
77
+ vacuum_sentrace_tables_if_allowed!
78
+ after_stats = StorageStats.collect
79
+ distinct_issues_count = project.issues.count
80
+
81
+ sample_issue = project.issues.order(last_seen_at: :desc).first
82
+ sample_event = project.events.order(occurred_at: :desc).first
83
+ backend = Mcp::LocalBackend.new(environment_name: "local")
84
+
85
+ # 3. Measure query & MCP latencies
86
+ t0 = monotonic_now
87
+ backend.get_issue(issue_id: sample_issue.id, project_id: project.id)
88
+ issue_lookup_ms = ((monotonic_now - t0) * 1_000.0).round(3)
89
+
90
+ t1 = monotonic_now
91
+ backend.get_event(event_id: sample_event.event_id.strip, project_id: project.id)
92
+ event_retrieval_ms = ((monotonic_now - t1) * 1_000.0).round(3)
93
+
94
+ mcp_server = Mcp::Server.build(dispatcher: Mcp::Dispatcher.new(config: bench_config, remote_client: nil))
95
+ rpc_req = JSON.generate(
96
+ jsonrpc: "2.0",
97
+ id: 1,
98
+ method: "tools/call",
99
+ params: { name: "list_issues", arguments: { project_id: project.id, limit: 25 } }
100
+ )
101
+ t2 = monotonic_now
102
+ mcp_server.handle_json(rpc_req)
103
+ mcp_list_issues_ms = ((monotonic_now - t2) * 1_000.0).round(3)
104
+
105
+ # 4. Measure batch retention deletion throughput
106
+ t3 = monotonic_now
107
+ cleanup_res = Retention::Cleaner.run!(config: bench_config)
108
+ retention_elapsed = [ monotonic_now - t3, 0.000_001 ].max
109
+ retention_eps = (cleanup_res.deleted_events_count / retention_elapsed).round(1)
110
+
111
+ compute_report(
112
+ before_stats: before_stats,
113
+ after_stats: after_stats,
114
+ distinct_issues: distinct_issues_count,
115
+ envelope_parse_ms: envelope_parse_ms,
116
+ event_persist_avg_ms: event_persist_avg_ms,
117
+ write_eps: write_eps,
118
+ issue_lookup_ms: issue_lookup_ms,
119
+ event_retrieval_ms: event_retrieval_ms,
120
+ mcp_list_issues_ms: mcp_list_issues_ms,
121
+ deleted_events: cleanup_res.deleted_events_count,
122
+ retention_eps: retention_eps
123
+ )
124
+ ensure
125
+ project&.destroy if @cleanup
126
+ end
127
+
128
+ private
129
+ def compute_report(
130
+ before_stats:,
131
+ after_stats:,
132
+ distinct_issues:,
133
+ envelope_parse_ms:,
134
+ event_persist_avg_ms:,
135
+ write_eps:,
136
+ issue_lookup_ms:,
137
+ event_retrieval_ms:,
138
+ mcp_list_issues_ms:,
139
+ deleted_events:,
140
+ retention_eps:
141
+ )
142
+ db_before = before_stats["database_storage_bytes"]
143
+ db_after = after_stats["database_storage_bytes"]
144
+ net_delta = [ db_after - db_before, 0 ].max
145
+
146
+ events_rel_after = after_stats["tables"].find { |t| t["table_name"] == "sentrace_events" } || {}
147
+ events_rel_before = before_stats["tables"].find { |t| t["table_name"] == "sentrace_events" } || {}
148
+ events_delta = [ events_rel_after["total_bytes"].to_i - events_rel_before["total_bytes"].to_i, 0 ].max
149
+
150
+ avg_bytes =
151
+ if events_delta.positive?
152
+ (events_delta.to_f / @event_count).round(2)
153
+ else
154
+ total_after = [ after_stats["total_events"].to_i, 1 ].max
155
+ (events_rel_after["total_bytes"].to_f / total_after).round(2)
156
+ end
157
+
158
+ idx_bytes = after_stats["index_bytes"]
159
+ total_bytes = [ db_after, 1 ].max
160
+ idx_pct = ((idx_bytes.to_f / total_bytes) * 100.0).round(2)
161
+
162
+ {
163
+ "event_count" => @event_count,
164
+ "distinct_issues" => distinct_issues,
165
+ "db_bytes_before" => db_before,
166
+ "db_bytes_after" => db_after,
167
+ "net_storage_delta_bytes" => net_delta,
168
+ "avg_bytes_per_event" => avg_bytes,
169
+ "index_overhead_bytes" => idx_bytes,
170
+ "index_overhead_pct" => idx_pct,
171
+ "envelope_parse_ms" => envelope_parse_ms,
172
+ "event_persist_avg_ms" => event_persist_avg_ms,
173
+ "write_events_per_second" => write_eps,
174
+ "issue_lookup_ms" => issue_lookup_ms,
175
+ "event_retrieval_ms" => event_retrieval_ms,
176
+ "mcp_list_issues_ms" => mcp_list_issues_ms,
177
+ "retention_deleted_events" => deleted_events,
178
+ "retention_delete_events_per_second" => retention_eps
179
+ }
180
+ end
181
+
182
+ def build_representative_envelope(index, dsn:)
183
+ issue_bucket = index % DISTINCT_ISSUE_COUNT
184
+ exc_class = EXCEPTION_CLASSES[issue_bucket % EXCEPTION_CLASSES.size]
185
+ event_id = format("%032x", index + 1)
186
+ occurred_at = (42.days.ago.utc + index.seconds).iso8601
187
+
188
+ envelope_header = JSON.generate(
189
+ event_id: event_id,
190
+ dsn: dsn,
191
+ sent_at: occurred_at
192
+ )
193
+ item_header = JSON.generate(type: "event")
194
+ payload = JSON.generate(
195
+ event_id: event_id,
196
+ timestamp: occurred_at,
197
+ platform: "ruby",
198
+ level: "error",
199
+ environment: "production",
200
+ release: "2026.11.#{issue_bucket % 4}",
201
+ server_name: "web-#{(index % 4) + 1}",
202
+ exception: {
203
+ values: [
204
+ {
205
+ type: exc_class,
206
+ value: "#{exc_class} in workflow bucket ##{issue_bucket} for request #{index}",
207
+ stacktrace: {
208
+ frames: build_frames(issue_bucket)
209
+ }
210
+ }
211
+ ]
212
+ },
213
+ request: {
214
+ url: "https://app.example.com/api/v1/orders/#{index}?page=1",
215
+ method: "POST",
216
+ headers: { "User-Agent" => "SentraceBenchmark/1.0", "Accept" => "application/json" }
217
+ },
218
+ breadcrumbs: {
219
+ values: Array.new(8) do |b_idx|
220
+ {
221
+ timestamp: occurred_at,
222
+ category: b_idx.even? ? "sql.active_record" : "http.client",
223
+ level: "info",
224
+ message: "Executed step #{b_idx} during checkout pipeline"
225
+ }
226
+ end
227
+ },
228
+ tags: {
229
+ "service" => "checkout",
230
+ "region" => "us-east-1",
231
+ "queue" => "critical",
232
+ "bucket" => "b#{issue_bucket}"
233
+ },
234
+ contexts: {
235
+ "runtime" => { "name" => "ruby", "version" => RUBY_VERSION },
236
+ "os" => { "name" => "Linux" }
237
+ },
238
+ user: {
239
+ "id" => "usr_#{(index % 50) + 1}",
240
+ "email" => "redacted@example.com"
241
+ }
242
+ )
243
+
244
+ "#{envelope_header}\n#{item_header}\n#{payload}\n"
245
+ end
246
+
247
+ def build_frames(issue_bucket)
248
+ framework_frames = Array.new(6) do |idx|
249
+ {
250
+ filename: "gems/actionpack-8.1.4/lib/action_dispatch/middleware/stack_#{idx}.rb",
251
+ function: "call",
252
+ lineno: 40 + idx,
253
+ in_app: false
254
+ }
255
+ end
256
+
257
+ app_frames = [
258
+ {
259
+ filename: "app/controllers/orders_controller.rb",
260
+ function: "create",
261
+ lineno: 18,
262
+ in_app: true
263
+ },
264
+ {
265
+ filename: "app/services/order_processor_#{issue_bucket}.rb",
266
+ function: "execute!",
267
+ lineno: 52 + issue_bucket,
268
+ in_app: true
269
+ }
270
+ ]
271
+
272
+ framework_frames + app_frames
273
+ end
274
+
275
+ def vacuum_sentrace_tables_if_allowed!
276
+ conn = ActiveRecord::Base.connection
277
+ return unless conn.open_transactions.zero?
278
+
279
+ StorageStats::ENGINE_TABLES.each do |table|
280
+ conn.execute("VACUUM ANALYZE #{conn.quote_table_name(table)}")
281
+ end
282
+ end
283
+
284
+ def monotonic_now
285
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
286
+ end
287
+ end
288
+ end
289
+ end
@@ -0,0 +1,198 @@
1
+ require "active_support/core_ext/numeric/bytes"
2
+ require "active_support/core_ext/numeric/time"
3
+ require "uri"
4
+
5
+ module Sentrace
6
+ class Configuration
7
+ DEFAULT_REDACT_FIELDS = %w[
8
+ password
9
+ token
10
+ authorization
11
+ cookie
12
+ credit_card
13
+ ].freeze
14
+
15
+ LOOPBACK_HOSTS = %w[localhost 127.0.0.1 ::1 [::1]].freeze
16
+
17
+ POSITIVE_NUMERIC_ATTRIBUTES = %i[
18
+ retention_period
19
+ orphan_issue_retention_period
20
+ max_envelope_size
21
+ max_message_bytes
22
+ max_stack_frames
23
+ max_breadcrumbs
24
+ max_tags
25
+ max_tag_key_bytes
26
+ max_tag_value_bytes
27
+ max_context_entries
28
+ max_context_bytes
29
+ remote_timeout
30
+ ].freeze
31
+
32
+ EnvironmentDefinition = Data.define(:name, :transport, :url, :token, :timeout) do
33
+ def inspect
34
+ masked_token = token ? "[REDACTED]" : "nil"
35
+ "#<#{self.class.name} name=#{name.inspect} transport=#{transport.inspect} url=#{url.inspect} token=#{masked_token} timeout=#{timeout.inspect}>"
36
+ end
37
+ alias_method :to_s, :inspect
38
+ end
39
+
40
+ attr_accessor :enabled,
41
+ :deployment_environment,
42
+ :retention_period,
43
+ :orphan_issue_retention_period,
44
+ :retention_batch_size,
45
+ :max_envelope_size,
46
+ :max_message_bytes,
47
+ :max_stack_frames,
48
+ :max_breadcrumbs,
49
+ :max_tags,
50
+ :max_tag_key_bytes,
51
+ :max_tag_value_bytes,
52
+ :max_context_entries,
53
+ :max_context_bytes,
54
+ :redact_fields,
55
+ :sanitizer,
56
+ :internal_authenticator,
57
+ :user_hash_secret,
58
+ :remote_timeout
59
+
60
+ attr_reader :environments
61
+
62
+ def initialize
63
+ @enabled = true
64
+ @deployment_environment = default_deployment_environment
65
+ @retention_period = 30.days
66
+ @orphan_issue_retention_period = 7.days
67
+ @retention_batch_size = 1_000
68
+ @max_envelope_size = 1.megabyte
69
+ @max_message_bytes = 4.kilobytes
70
+ @max_stack_frames = 50
71
+ @max_breadcrumbs = 20
72
+ @max_tags = 32
73
+ @max_tag_key_bytes = 64
74
+ @max_tag_value_bytes = 256
75
+ @max_context_entries = 16
76
+ @max_context_bytes = 8.kilobytes
77
+ @redact_fields = DEFAULT_REDACT_FIELDS.dup
78
+ @sanitizer = nil
79
+ @internal_authenticator = nil
80
+ @user_hash_secret = nil
81
+ @remote_timeout = 5.0
82
+ self.environments = { local: { transport: :local } }
83
+ end
84
+
85
+ def environments=(raw_environments)
86
+ unless raw_environments.is_a?(Hash) && raw_environments.any?
87
+ raise ConfigurationError, "environments must be a non-empty Hash"
88
+ end
89
+
90
+ @environments = raw_environments.each_with_object({}) do |(key, value), acc|
91
+ unless value.is_a?(Hash)
92
+ raise ConfigurationError, "environment #{key.inspect} definition must be a Hash"
93
+ end
94
+
95
+ env_name = key.to_sym
96
+ opts = value.transform_keys(&:to_sym)
97
+ transport = opts[:transport]&.to_sym
98
+
99
+ acc[env_name] = EnvironmentDefinition.new(
100
+ name: env_name,
101
+ transport: transport,
102
+ url: opts[:url],
103
+ token: opts[:token],
104
+ timeout: opts.fetch(:timeout, @remote_timeout)
105
+ )
106
+ end
107
+ end
108
+
109
+ def validate!
110
+ POSITIVE_NUMERIC_ATTRIBUTES.each do |attr|
111
+ val = public_send(attr)
112
+ unless val.is_a?(Numeric) && val.positive?
113
+ raise ConfigurationError, "#{attr} must be a positive number (got #{val.inspect})"
114
+ end
115
+ end
116
+
117
+ unless redact_fields.is_a?(Array) && redact_fields.all? { |f| f.is_a?(String) || f.is_a?(Symbol) }
118
+ raise ConfigurationError, "redact_fields must be an Array of field names"
119
+ end
120
+
121
+ unless retention_batch_size.is_a?(Integer) && retention_batch_size.positive?
122
+ raise ConfigurationError, "retention_batch_size must be a positive Integer (got #{retention_batch_size.inspect})"
123
+ end
124
+
125
+ if !sanitizer.nil? && !sanitizer.respond_to?(:call)
126
+ raise ConfigurationError, "sanitizer must respond to #call"
127
+ end
128
+
129
+ if !internal_authenticator.nil? && !internal_authenticator.respond_to?(:call)
130
+ raise ConfigurationError, "internal_authenticator must respond to #call"
131
+ end
132
+
133
+ if deployment_environment.nil? || deployment_environment.to_s.strip.empty?
134
+ raise ConfigurationError, "deployment_environment must be a non-empty String or Symbol"
135
+ end
136
+
137
+ validate_environments!
138
+ true
139
+ end
140
+
141
+ def inspect
142
+ masked_secret = user_hash_secret ? "[REDACTED]" : "nil"
143
+ "#<#{self.class.name} enabled=#{enabled.inspect} deployment_environment=#{deployment_environment.inspect} " \
144
+ "retention_period=#{retention_period.inspect} " \
145
+ "max_envelope_size=#{max_envelope_size.inspect} max_stack_frames=#{max_stack_frames.inspect} " \
146
+ "max_breadcrumbs=#{max_breadcrumbs.inspect} max_tags=#{max_tags.inspect} " \
147
+ "user_hash_secret=#{masked_secret} environments=#{environments.inspect}>"
148
+ end
149
+
150
+ private
151
+ def default_deployment_environment
152
+ if defined?(Rails) && Rails.respond_to?(:env) && !Rails.env.to_s.empty?
153
+ Rails.env.to_s
154
+ else
155
+ "local"
156
+ end
157
+ end
158
+ def validate_environments!
159
+ unless environments.is_a?(Hash) && environments.any?
160
+ raise ConfigurationError, "environments must be a non-empty Hash"
161
+ end
162
+
163
+ environments.each_value do |env_def|
164
+ case env_def.transport
165
+ when :local
166
+ next
167
+ when :http
168
+ validate_http_environment!(env_def)
169
+ else
170
+ raise ConfigurationError,
171
+ "environment #{env_def.name.inspect} has unsupported transport #{env_def.transport.inspect} (expected :local or :http)"
172
+ end
173
+ end
174
+ end
175
+
176
+ def validate_http_environment!(env_def)
177
+ unless env_def.timeout.is_a?(Numeric) && env_def.timeout.positive?
178
+ raise ConfigurationError, "environment #{env_def.name.inspect} timeout must be a positive number"
179
+ end
180
+
181
+ if env_def.url.nil? || env_def.url.to_s.strip.empty?
182
+ raise ConfigurationError, "environment #{env_def.name.inspect} requires a url for :http transport"
183
+ end
184
+
185
+ uri = URI.parse(env_def.url.to_s)
186
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty?
187
+ raise ConfigurationError, "environment #{env_def.name.inspect} url #{env_def.url.inspect} is invalid"
188
+ end
189
+
190
+ if uri.scheme != "https" && !LOOPBACK_HOSTS.include?(uri.host.downcase)
191
+ raise ConfigurationError,
192
+ "environment #{env_def.name.inspect} requires HTTPS for non-local host #{uri.host.inspect}"
193
+ end
194
+ rescue URI::InvalidURIError => e
195
+ raise ConfigurationError, "environment #{env_def.name.inspect} url is invalid: #{e.message}"
196
+ end
197
+ end
198
+ end
@@ -0,0 +1,123 @@
1
+ require "uri"
2
+
3
+ module Sentrace
4
+ class Dsn
5
+ SUPPORTED_SCHEMES = %w[http https].freeze
6
+
7
+ attr_reader :scheme, :public_key, :secret_key, :host, :port, :path_prefix, :project_id
8
+
9
+ class << self
10
+ def parse(raw_dsn)
11
+ if raw_dsn.nil? || raw_dsn.to_s.strip.empty?
12
+ raise InvalidDsnError, "DSN cannot be blank"
13
+ end
14
+
15
+ uri = URI.parse(raw_dsn.to_s.strip)
16
+ validate_uri!(uri)
17
+
18
+ segments = uri.path.to_s.split("/").reject(&:empty?)
19
+ if segments.empty?
20
+ raise InvalidDsnError, "DSN must include a trailing project identifier"
21
+ end
22
+
23
+ project_id = segments.pop
24
+ prefix = segments.empty? ? "" : "/#{segments.join("/")}"
25
+
26
+ new(
27
+ scheme: uri.scheme.downcase,
28
+ public_key: URI.decode_www_form_component(uri.user),
29
+ secret_key: uri.password ? URI.decode_www_form_component(uri.password) : nil,
30
+ host: uri.host,
31
+ port: uri.port,
32
+ path_prefix: prefix,
33
+ project_id: project_id
34
+ )
35
+ rescue URI::InvalidURIError
36
+ raise InvalidDsnError, "Malformed DSN URI"
37
+ end
38
+
39
+ def build(base_url:, public_key:, project_id:, secret_key: nil)
40
+ if base_url.nil? || base_url.to_s.strip.empty?
41
+ raise InvalidDsnError, "base_url cannot be blank"
42
+ end
43
+
44
+ uri = URI.parse(base_url.to_s.strip)
45
+ unless uri.is_a?(URI::HTTP) && uri.host && !uri.host.empty? && SUPPORTED_SCHEMES.include?(uri.scheme&.downcase)
46
+ raise InvalidDsnError, "base_url must be a valid HTTP or HTTPS URL"
47
+ end
48
+
49
+ prefix_segments = uri.path.to_s.split("/").reject(&:empty?)
50
+ prefix = prefix_segments.empty? ? "" : "/#{prefix_segments.join("/")}"
51
+
52
+ new(
53
+ scheme: uri.scheme.downcase,
54
+ public_key: public_key.to_s.strip,
55
+ secret_key: secret_key&.to_s,
56
+ host: uri.host,
57
+ port: uri.port,
58
+ path_prefix: prefix,
59
+ project_id: project_id.to_s.strip
60
+ )
61
+ rescue URI::InvalidURIError
62
+ raise InvalidDsnError, "Invalid base_url for DSN"
63
+ end
64
+
65
+ private
66
+ def validate_uri!(uri)
67
+ unless SUPPORTED_SCHEMES.include?(uri.scheme&.downcase)
68
+ raise InvalidDsnError, "DSN scheme must be http or https"
69
+ end
70
+
71
+ if uri.host.nil? || uri.host.empty?
72
+ raise InvalidDsnError, "DSN must include a host"
73
+ end
74
+
75
+ if uri.user.nil? || uri.user.empty?
76
+ raise InvalidDsnError, "DSN must include a public key in userinfo"
77
+ end
78
+ end
79
+ end
80
+
81
+ def initialize(scheme:, public_key:, host:, port:, path_prefix:, project_id:, secret_key: nil)
82
+ if public_key.nil? || public_key.empty?
83
+ raise InvalidDsnError, "DSN public_key cannot be blank"
84
+ end
85
+
86
+ if project_id.nil? || project_id.empty?
87
+ raise InvalidDsnError, "DSN project_id cannot be blank"
88
+ end
89
+
90
+ @scheme = scheme
91
+ @public_key = public_key
92
+ @secret_key = (secret_key && !secret_key.empty?) ? secret_key : nil
93
+ @host = host
94
+ @port = port
95
+ @path_prefix = path_prefix.to_s
96
+ @project_id = project_id
97
+ freeze
98
+ end
99
+
100
+ def to_s
101
+ userinfo = secret_key ? "#{public_key}:#{secret_key}" : public_key
102
+ "#{scheme}://#{userinfo}@#{authority_host}#{path_prefix}/#{project_id}"
103
+ end
104
+
105
+ def envelope_endpoint
106
+ "#{scheme}://#{authority_host}#{path_prefix}/api/#{project_id}/envelope/"
107
+ end
108
+
109
+ def inspect
110
+ masked = secret_key ? "[REDACTED]" : "nil"
111
+ "#<#{self.class.name} scheme=#{scheme.inspect} host=#{host.inspect} port=#{port.inspect} " \
112
+ "path_prefix=#{path_prefix.inspect} project_id=#{project_id.inspect} " \
113
+ "public_key=#{public_key.inspect} secret_key=#{masked}>"
114
+ end
115
+
116
+ private
117
+ def authority_host
118
+ default_port = (scheme == "https" && port == 443) || (scheme == "http" && port == 80)
119
+ formatted_host = host.include?(":") && !host.start_with?("[") ? "[#{host}]" : host
120
+ (port && !default_port) ? "#{formatted_host}:#{port}" : formatted_host
121
+ end
122
+ end
123
+ end
@@ -0,0 +1,10 @@
1
+ module Sentrace
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace Sentrace
4
+ config.generators.api_only = true
5
+
6
+ initializer "sentrace.filter_parameters" do |app|
7
+ app.config.filter_parameters += %i[sentry_secret]
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,20 @@
1
+ module Sentrace
2
+ class Error < StandardError; end
3
+ class ConfigurationError < Error; end
4
+ class InvalidDsnError < Error; end
5
+ class EnvelopeParseError < Error; end
6
+ class PayloadTooLargeError < Error; end
7
+
8
+ class McpError < Error; end
9
+ class McpInvalidParamsError < McpError; end
10
+ class McpNotFoundError < McpError; end
11
+ class McpRemoteError < McpError
12
+ attr_reader :environment, :category
13
+
14
+ def initialize(message, environment:, category:)
15
+ super(message)
16
+ @environment = environment.to_s
17
+ @category = category.to_s
18
+ end
19
+ end
20
+ end