connectrpc-prometheus 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 8a46a40d7a47d9aec4134a3d03aad002627ac785bc58a85ca5858c3ea09b446d
4
+ data.tar.gz: 34bea75221a8d5c11ee4949b3c0068042f6c93c1cc5361bfd7cdd41f68bf5c8d
5
+ SHA512:
6
+ metadata.gz: f5ace7278162ccaabafcf85551e66e47634e3e13c490b95039231bbc70a3c773840d35d36f67d5035f845f14b11b18cb87bac3a023bbe84e72e216c46697b02e
7
+ data.tar.gz: 7f4d1bc06469d7790fb5e388594901b25575914e5bf13afafc02b161ff46934f83555c1b2f42932d591afdfb68e69d92ea357ccd0f4084f4dec4182f5017a28e
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jim Myhrberg
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,222 @@
1
+ <div align="center">
2
+
3
+ <img height="128px" width="128px" src="../../img/connectrpc-ruby.svg" alt="connectrpc-ruby logo">
4
+
5
+ # connectrpc-prometheus
6
+
7
+ **Prometheus metrics for ConnectRPC clients and servers.**
8
+
9
+ [![RubyGems](https://img.shields.io/gem/v/connectrpc-prometheus?logo=rubygems&logoColor=white&label=RubyGems)](https://rubygems.org/gems/connectrpc-prometheus)
10
+ [![CI](https://img.shields.io/github/actions/workflow/status/jimeh/connectrpc-ruby/ci.yml?branch=main&logo=github&label=CI)](https://github.com/jimeh/connectrpc-ruby/actions/workflows/ci.yml)
11
+ [![Docs](https://img.shields.io/badge/Docs-guides-0969da?logo=markdown&logoColor=white)](https://github.com/jimeh/connectrpc-ruby/tree/main/docs)
12
+ [![License](https://img.shields.io/github/license/jimeh/connectrpc-ruby?label=License)](https://github.com/jimeh/connectrpc-ruby/blob/main/LICENSE)
13
+
14
+ </div>
15
+
16
+ `connectrpc-prometheus` records server, client and Async client connection
17
+ metrics for ConnectRPC in a `prometheus-client` registry: RPC counts by code,
18
+ latency, message counts and encoded sizes, server rejections and connection
19
+ health. Names and labels follow
20
+ [go-grpc-middleware `providers/prometheus`](https://github.com/grpc-ecosystem/go-grpc-middleware/tree/main/providers/prometheus),
21
+ so dashboards built on go-grpc-prometheus queries keep working. Use the
22
+ [Yabeda package](../connectrpc-yabeda/README.md) instead when your application
23
+ records metrics through Yabeda.
24
+
25
+ The package is experimental. See the [supported 0.x contract](../../docs/support.md)
26
+ for the target support profile, matched package versions, compatibility policy
27
+ and adoption gates.
28
+
29
+ ## Installation
30
+
31
+ ```ruby
32
+ gem "connectrpc-prometheus", "~> 0.1.0"
33
+ ```
34
+
35
+ The only runtime dependencies are `connectrpc ~> 0.1.0` and
36
+ `prometheus-client >= 5.0, < 6`. The shared, backend-neutral layer lives in core
37
+ as the optional `require "connectrpc/metrics"`. Core and the HTTP/framework
38
+ packages do not depend on Prometheus.
39
+
40
+ ## Usage
41
+
42
+ ```ruby
43
+ require "connectrpc/prometheus"
44
+
45
+ metrics = ConnectRPC::Prometheus::Metrics.new(registry: Prometheus::Client.registry, namespace: "grpc")
46
+ instrumentation = ConnectRPC::Instrumentation.new(
47
+ subscribers: [metrics.subscriber], on_error: ->(error) { application_logger.warn(error.class.name) }
48
+ )
49
+ # Pass instrumentation: instrumentation to ConnectRPC::Server.new and ConnectRPC::Client.new.
50
+ ```
51
+
52
+ `Metrics.new` registers every instrument once. Constructing a second `Metrics`
53
+ with the same namespace on one registry raises the registry's
54
+ `AlreadyRegisteredError`; build one per process and share it. The keywords are
55
+ `registry:` (default `Prometheus::Client.registry`), `namespace:` (default
56
+ `"grpc"`, matching `/\A[a-z_][a-z0-9_]*\z/`), `duration_buckets:` and
57
+ `size_buckets:` (strictly increasing positive numbers). Exported names are
58
+ `<namespace>_<name>[_<unit>]`.
59
+
60
+ For the Async HTTP/2 client transport, add a connection observer with an
61
+ application-chosen transport name, unique per process:
62
+
63
+ ```ruby
64
+ transport = ConnectRPC::Async::Transport.new(
65
+ origin: "https://billing.internal:8443",
66
+ connection_observer: metrics.connection_observer(transport: "billing")
67
+ )
68
+ ```
69
+
70
+ Transport names match `/\A[a-z0-9_]{1,64}\z/`. Asking one `Metrics` for a second
71
+ observer with the same name raises `ArgumentError`.
72
+
73
+ Subscribers and observers run synchronously on the RPC's thread or reactor,
74
+ possibly from separate read and write fibers. prometheus-client's stores are
75
+ thread safe. A failing recorder call is reported through the instrumentation's
76
+ `on_error` and does not change the RPC. Async swallows connection observer
77
+ `StandardError`s, so connection metric failures are not reported through
78
+ `on_error`.
79
+
80
+ ## Exposing metrics per host
81
+
82
+ Requiring `connectrpc/prometheus` does not mount an endpoint. Use
83
+ `Prometheus::Middleware::Exporter` (from `prometheus/middleware/exporter`) or
84
+ any other exporter over the same registry.
85
+
86
+ - **Rack** (`connectrpc-rack`): mount the exporter beside the RPC app.
87
+
88
+ ```ruby
89
+ require "prometheus/middleware/exporter"
90
+ use Prometheus::Middleware::Exporter # serves /metrics
91
+ run ConnectRPC::Rack.new(rails_or_other_app, server: connect_server)
92
+ ```
93
+
94
+ - **Rails** (`connectrpc-on-rails`): mount the exporter middleware (or use
95
+ yabeda-rails with yabeda-prometheus through the Yabeda package). Native
96
+ controllers return the instrumentation from the private
97
+ `connect_instrumentation` method, separately from `connect_limits`.
98
+ - **Falcon** (`connectrpc-falcon`): serve the exporter through the `rack_app`
99
+ fallback. RPC traffic bypasses it; the fallback receives `/metrics`.
100
+ - **Async standalone `Host`**: `Host` has no fallback application. Run a separate
101
+ metrics listener on its own port in the same process, for example a small
102
+ Rack server with the exporter, or `Async::HTTP::Server` serving
103
+ `Prometheus::Client::Formats::Text.marshal(registry)`. Adding a `fallback:` to
104
+ `Host` is a possible follow-up, not part of this package.
105
+
106
+ ## Multi-process
107
+
108
+ The default in-memory store is correct for one process with any number of
109
+ threads: Puma single mode, one Falcon worker, or an Async `Host`. Scrape each
110
+ pod or process on its own and sum in PromQL.
111
+
112
+ `DirectFileStore` is only for forked workers that share one `/metrics`
113
+ endpoint, where a scrape would otherwise see one random worker. It costs a file
114
+ write per observation, so do not use it otherwise.
115
+
116
+ - **Puma cluster / Unicorn**: set
117
+ `Prometheus::Client.config.data_store = Prometheus::Client::DataStores::DirectFileStore.new(dir:)`
118
+ before constructing `Metrics`, clear that directory in the master before
119
+ forking, and serve `Prometheus::Middleware::Exporter`.
120
+ - **Falcon with several workers** (it forks one per CPU by default): use the
121
+ same store and construct `Metrics` per worker after fork, consistent with the
122
+ worker-local `prepare!`. Serve the exporter through the `rack_app` fallback.
123
+
124
+ Under `DirectFileStore`, the connection state gauge is declared with
125
+ `aggregation: :sum`, so each state sums to the number of workers in it. The
126
+ default store rejects store settings, so other stores get none. Dead workers
127
+ keep their last counter and gauge values until the directory is cleared.
128
+
129
+ Build connection observers per worker after fork. An observer built in the Puma
130
+ or Unicorn master before fork, including one passed to a `ThreadedTransport`
131
+ created there, writes the master's `idle` 1 to the store, and the summed state
132
+ gauge keeps counting that entry.
133
+
134
+ ## Metrics
135
+
136
+ Base labels `B` are `grpc_type`, `grpc_service`, `grpc_method` and
137
+ `rpc_protocol`. Names below use the default `grpc` namespace.
138
+
139
+ | Metric | Type | Labels | Recorded |
140
+ | --- | --- | --- | --- |
141
+ | `grpc_{server,client}_started_total` | counter | B | lifecycle start |
142
+ | `grpc_{server,client}_handled_total` | counter | B, `grpc_code` | lifecycle finish, see below |
143
+ | `grpc_{server,client}_handling_seconds` | histogram | B | with handled, processing duration |
144
+ | `grpc_{server,client}_msg_received_total`, `_msg_sent_total` | counter | B | per message, live |
145
+ | `grpc_{server,client}_msg_received_bytes`, `_msg_sent_bytes` | histogram | B | per message |
146
+ | `grpc_server_rejected_total` | counter | B, `reason` | lifecycle finish, see below |
147
+ | `grpc_server_delivery_aborted_total` | counter | B | handled and delivery aborted |
148
+ | `grpc_client_connection_attempts_total` | counter | `transport`, `outcome` | Async attempt finished |
149
+ | `grpc_client_connection_attempt_seconds` | histogram | `transport` | Async attempt finished |
150
+ | `grpc_client_connection_state_changes_total` | counter | `transport`, `state` | Async state change |
151
+ | `grpc_client_connection_state` | gauge | `transport`, `state` | 1 for the current state, starts `idle` |
152
+ | `grpc_client_admission_rejected_total` | counter | `transport` | Async admission rejection |
153
+
154
+ Classification at finish, with `code` from the outcome's code or its normalized
155
+ error's code:
156
+
157
+ | Condition | Result |
158
+ | --- | --- |
159
+ | decision `admission_rejected` or `host_rejected` | `rejected_total{reason=<decision>}` |
160
+ | processed with a code | `handled_total{grpc_code=<Go name>}` |
161
+ | processed without a code but with an error (escaping exception, empty 429) | `handled_total{grpc_code="Unknown"}` |
162
+ | processed without an outcome, or a code-less outcome without error (native preflight, HTTP/1 505, Web preflight) | `rejected_total{reason="unprocessed"}` |
163
+ | client without a code | `handled_total{grpc_code="Unknown"}` |
164
+
165
+ In flight is `started - handled - rejected`: observed lifecycles not yet
166
+ finished, including delivery waits such as a held Rack body. It holds only when
167
+ no recorder call failed. There is no in-flight gauge and no per-stream message
168
+ histogram; average messages per stream is `msg_*_total / handled_total`.
169
+
170
+ - `grpc_type` is `unary`, `client_stream`, `server_stream` or `bidi_stream`.
171
+ Service and method come only from the declared method. Undeclared paths use
172
+ `grpc_service="_OTHER"`, `grpc_method="_OTHER"` and `grpc_type="unknown"`.
173
+ - `rpc_protocol` is `connect`, `grpc` or `grpc_web`.
174
+ - `grpc_code` uses Go `codes.Code` strings (`OK`, `Canceled`, `InvalidArgument`,
175
+ ..., `Unauthenticated`); anything else is `Unknown`.
176
+ - There are no peer, address, path, metadata or error-text labels.
177
+ - Message sizes are encoded payload bytes as framed: after compression,
178
+ excluding the 5-byte envelope prefix, end-stream and trailer frames, gRPC-Web
179
+ text base64 and GET query expansion. Receive counts after a successful decode.
180
+ A send counts after local frame emission; it is not evidence of peer receipt.
181
+ Discarded or undecodable messages are not counted.
182
+ - Durations use `[0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]`
183
+ seconds (Go's defaults; also connection attempts). Sizes use
184
+ `[64, 256, 1024, 4096, 16384, 65536, 262144, 1048576, 4194304]` bytes.
185
+
186
+ ### Compatibility with go-grpc-prometheus
187
+
188
+ Names, help text, label names and code strings match go-grpc-middleware
189
+ `providers/prometheus`. `namespace:` swaps the `grpc` prefix. The compatibility
190
+ promise covers queries that aggregate by or without labels, the common
191
+ dashboard form. `rpc_protocol` adds a label, so recording rules that match exact
192
+ label sets need `sum without (rpc_protocol) (...)`. The byte histograms,
193
+ rejection, delivery and connection metrics are additions.
194
+
195
+ ## Development
196
+
197
+ From the repository root use `mise run prometheus:setup`, `prometheus:test`,
198
+ `prometheus:check`, `prometheus:build`, `prometheus:package`,
199
+ `prometheus:example`, and `prometheus:verify`. The independent development
200
+ bundle resolves the newest allowed versions and includes the local Rack, Async, Falcon and testing packages
201
+ for real-host specs. Caches and archives are in `vendor/prometheus`, and coverage
202
+ is in `coverage/prometheus/<Ruby>/`. Both pinned Ruby 3.4.12 and 4.0.9 CI leaves
203
+ run `prometheus:verify`. `scripts/integration.rb` is also a runnable generated
204
+ example that checks the text exposition.
205
+
206
+ `floors:prometheus` repeats specs and package checks with every runtime
207
+ dependency at its gemspec floor, including prometheus-client 5.0.0. That floor
208
+ changes only Ruby support versus 4.2.5, whose `DirectFileStore` calls
209
+ `CGI.parse`, which Ruby 4.0 removed.
210
+
211
+ ## Static signatures
212
+
213
+ This package owns `sig/` and its discovery manifest. Add
214
+ `library "connectrpc-prometheus"` to a strict Steep target with this gem
215
+ installed. The registry is typed through narrow structural capabilities. See the
216
+ [RBS guide](../../docs/rbs.md) for supported APIs and extension contracts.
217
+
218
+ ## License
219
+
220
+ Original project work is [MIT licensed](LICENSE), copyright 2026 Jim Myhrberg.
221
+ All package archives pin `allowed_push_host=https://rubygems.org`; these checks
222
+ never publish or release a gem.
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Prometheus
5
+ # Registers the fixed ConnectRPC metric set in one prometheus-client registry.
6
+ class Metrics
7
+ attr_reader :definitions, :registry, :subscriber
8
+
9
+ def initialize(registry: ::Prometheus::Client.registry, namespace: "grpc",
10
+ duration_buckets: ::ConnectRPC::Metrics::Definitions::DURATION_BUCKETS,
11
+ size_buckets: ::ConnectRPC::Metrics::Definitions::SIZE_BUCKETS)
12
+ @definitions = ::ConnectRPC::Metrics::Definitions.new(namespace: namespace, duration_buckets: duration_buckets,
13
+ size_buckets: size_buckets)
14
+ @registry = registry
15
+ @recorder = Recorder.new(@definitions.instruments.transform_values { |instrument| register(instrument) })
16
+ @subscriber = ::ConnectRPC::Metrics::Subscriber.new(recorder: @recorder, definitions: @definitions)
17
+ @transports = {}
18
+ @mutex = Mutex.new
19
+ end
20
+
21
+ # One observer per transport name; a repeated name would merge two transports' states.
22
+ def connection_observer(transport:)
23
+ @mutex.synchronize do
24
+ raise ArgumentError, "transport #{transport.inspect} already has an observer" if @transports.key?(transport)
25
+
26
+ observer = ::ConnectRPC::Metrics::ConnectionObserver.new(recorder: @recorder, definitions: @definitions,
27
+ transport: transport)
28
+ observer.publish_state
29
+ @transports[transport] = observer
30
+ end
31
+ end
32
+
33
+ private
34
+
35
+ def register(instrument)
36
+ name = @definitions.full_name(instrument).to_sym
37
+ options = { docstring: instrument.help, labels: instrument.labels }
38
+ case instrument.kind
39
+ when :counter then @registry.counter(name, **options)
40
+ when :histogram then @registry.histogram(name, **options, buckets: instrument.buckets)
41
+ else @registry.gauge(name, **options, store_settings: gauge_settings)
42
+ end
43
+ end
44
+
45
+ # The default stores reject settings; forked DirectFileStore workers sum their state gauges.
46
+ def gauge_settings
47
+ store = ::Prometheus::Client.config.data_store
48
+ return {} unless defined?(::Prometheus::Client::DataStores::DirectFileStore) &&
49
+ store.is_a?(::Prometheus::Client::DataStores::DirectFileStore)
50
+
51
+ { aggregation: :sum }
52
+ end
53
+
54
+ # The neutral recorder SPI over registered prometheus-client metrics.
55
+ class Recorder
56
+ def initialize(metrics)
57
+ @metrics = metrics.freeze
58
+ end
59
+
60
+ def increment(key, labels, by) = @metrics.fetch(key).increment(by: by, labels: labels)
61
+ def observe(key, labels, value) = @metrics.fetch(key).observe(value, labels: labels)
62
+ def set(key, labels, value) = @metrics.fetch(key).set(value, labels: labels)
63
+ end
64
+ private_constant :Recorder
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Prometheus
5
+ VERSION = "0.1.1" # x-release-please-version
6
+ end
7
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "connectrpc/metrics"
4
+ require_relative "prometheus/version"
5
+ require "prometheus/client"
6
+ require_relative "prometheus/metrics"
@@ -0,0 +1,28 @@
1
+ module ConnectRPC
2
+ module Prometheus
3
+ VERSION: String
4
+ # The prometheus-client registry and metric capabilities this adapter uses.
5
+ interface _Counter
6
+ def increment: (by: Integer, labels: ::ConnectRPC::Metrics::labels) -> untyped
7
+ end
8
+ interface _Histogram
9
+ def observe: (Numeric, labels: ::ConnectRPC::Metrics::labels) -> untyped
10
+ end
11
+ interface _Gauge
12
+ def set: (Numeric, labels: ::ConnectRPC::Metrics::labels) -> untyped
13
+ end
14
+ interface _Registry
15
+ def counter: (Symbol, docstring: String, labels: Array[Symbol]) -> _Counter
16
+ def histogram: (Symbol, docstring: String, labels: Array[Symbol], buckets: Array[Numeric]) -> _Histogram
17
+ def gauge: (Symbol, docstring: String, labels: Array[Symbol], store_settings: Hash[Symbol, Symbol]) -> _Gauge
18
+ end
19
+ class Metrics
20
+ def initialize: (?registry: _Registry, ?namespace: String | Symbol, ?duration_buckets: Array[Numeric], ?size_buckets: Array[Numeric]) -> void
21
+ attr_reader definitions: ::ConnectRPC::Metrics::Definitions
22
+ attr_reader registry: _Registry
23
+ attr_reader subscriber: ::ConnectRPC::Metrics::Subscriber
24
+ # Raises ArgumentError when this Metrics already has an observer for the transport name.
25
+ def connection_observer: (transport: String) -> ::ConnectRPC::Metrics::ConnectionObserver
26
+ end
27
+ end
28
+ end
data/sig/manifest.yaml ADDED
@@ -0,0 +1,2 @@
1
+ dependencies:
2
+ - name: connectrpc
metadata ADDED
@@ -0,0 +1,83 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: connectrpc-prometheus
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - jimeh
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-11-16 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: connectrpc
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.1.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.1.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: prometheus-client
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: '5.0'
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '6'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: '5.0'
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '6'
46
+ description: go-grpc-prometheus compatible RPC and connection metrics in a prometheus-client
47
+ registry. Experimental.
48
+ executables: []
49
+ extensions: []
50
+ extra_rdoc_files: []
51
+ files:
52
+ - LICENSE
53
+ - README.md
54
+ - lib/connectrpc/prometheus.rb
55
+ - lib/connectrpc/prometheus/metrics.rb
56
+ - lib/connectrpc/prometheus/version.rb
57
+ - sig/connectrpc-prometheus.rbs
58
+ - sig/manifest.yaml
59
+ homepage: https://github.com/jimeh/connectrpc-ruby
60
+ licenses:
61
+ - MIT
62
+ metadata:
63
+ allowed_push_host: https://rubygems.org
64
+ rubygems_mfa_required: 'true'
65
+ source_code_uri: https://github.com/jimeh/connectrpc-ruby
66
+ rdoc_options: []
67
+ require_paths:
68
+ - lib
69
+ required_ruby_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '3.4'
74
+ required_rubygems_version: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '0'
79
+ requirements: []
80
+ rubygems_version: 3.6.9
81
+ specification_version: 4
82
+ summary: Optional Prometheus metrics for ConnectRPC servers and clients
83
+ test_files: []