[chore/docs] Fix Prometheus metric names for Gin, include example Grafana dash, update docs (#4443)

# Description

> If this is a code change, please include a summary of what you've coded, and link to the issue(s) it closes/implements.
>
> If this is a documentation change, please briefly describe what you've changed and why.

This pull request updates some of our inconsistent metric naming, and adds an example Grafana dashboard using all the most up-to-date metrics names, and updates our docs to describe the latest way of setting up metrics.

Closes https://codeberg.org/superseriousbusiness/gotosocial/issues/4362
Closes https://codeberg.org/superseriousbusiness/gotosocial/issues/4055

## Checklist

Please put an x inside each checkbox to indicate that you've read and followed it: `[ ]` -> `[x]`

If this is a documentation change, only the first checkbox must be filled (you can delete the others if you want).

- [x] I/we have read the [GoToSocial contribution guidelines](https://codeberg.org/superseriousbusiness/gotosocial/src/branch/main/CONTRIBUTING.md).
- [x] I/we have discussed the proposed changes already, either in an issue on the repository, or in the Matrix chat.
- [x] I/we have not leveraged AI to create the proposed changes.
- [x] I/we have performed a self-review of added code.
- [x] I/we have written code that is legible and maintainable by others.
- [x] I/we have commented the added code, particularly in hard-to-understand areas.
- [x] I/we have made any necessary changes to documentation.
- [ ] I/we have added tests that cover new code.
- [x] I/we have run tests and they pass locally with the changes.
- [x] I/we have run `go fmt ./...` and `golangci-lint run`.

Co-authored-by: kim <grufwub@gmail.com>
Reviewed-on: https://codeberg.org/superseriousbusiness/gotosocial/pulls/4443
Reviewed-by: kim <gruf@noreply.codeberg.org>
Co-authored-by: tobi <tobi.smethurst@protonmail.com>
Co-committed-by: tobi <tobi.smethurst@protonmail.com>
This commit is contained in:
tobi 2025-09-18 16:48:45 +02:00 committed by tobi
commit 82216281ce
32 changed files with 2315 additions and 4760 deletions

View file

@ -1,32 +1,89 @@
# Metrics # Metrics
GoToSocial comes with [OpenTelemetry][otel] based metrics. The metrics are exposed using the [Prometheus exposition format][prom] on the `/metrics` path. The configuration settings are documented in the [Observability configuration reference][obs]. GoToSocial uses the [OpenTelemetry][otel] Go SDK to enable instance admins to expose runtime metrics in the Prometheus metrics format.
Currently the following metrics are collected: Currently, the following metrics are collected:
* Go performance and runtime metrics * Go performance and runtime metrics
* Gin (HTTP) metrics * Gin (HTTP server) metrics
* Bun (database) metrics * Bun (database) metrics
Metrics can be enable with the following configuration: ## Enabling metrics
To enable metrics, first set the `metrics-enabled` configuration value to `true` in your config.yaml file:
```yaml ```yaml
metrics-enabled: true metrics-enabled: true
``` ```
Though metrics do not contain anything privacy sensitive, you may not want to allow just anyone to view and scrape operational metrics of your instance. Then, you will need to set some additional environment variables on the GoToSocial process in order to configure OpenTelemetry to expose metrics in the Prometheus format:
```env
OTEL_METRICS_PRODUCERS=prometheus
OTEL_METRICS_EXPORTER=prometheus
```
By default, this configuration will instantiate an additional HTTP server running alongside the standard GoToSocial HTTP server, which exposes a Prometheus metrics endpoint at `localhost:9464/metrics`.
!!! tip
If you are running GoToSocial using the [example systemd service definition](../../example/gotosocial.service), you can easily set these environment variables by uncommenting the relevant two lines in that file, and reloading + restarting the service.
If you wish, you can further customize this metrics HTTP server by using the following environment variables to change the host and port:
```env
OTEL_EXPORTER_PROMETHEUS_HOST=example.org
OTEL_EXPORTER_PROMETHEUS_PORT=9999
```
## Serving metrics to the outside world
If you have deployed GoToSocial in a "bare-metal" fashion without a reverse proxy, you can expose the metrics endpoint to the outside world by setting `OTEL_EXPORTER_PROMETHEUS_HOST` to your host value. For example, if your GtS instance `host` configuration value is set to `example.org`, you should set `OTEL_EXPORTER_PROMETHEUS_HOST=example.org`. You should then be able to access your metrics at `http://example.org:9464/metrics`. GoToSocial running in this fashion will not serve LetsEncrypt certificates at the metrics endpoint, so you will be limited to using HTTP rather than HTTPS.
If you are using a reverse proxy like Nginx, you can expose the metrics endpoint to the outside world with HTTPS certificates, by putting an additional location stanza in your Nginx configuration above the catch-all `location /` stanza:
```nginx
location /metrics {
proxy_pass http://127.0.0.1:9464;
}
```
This will instruct Nginx to forward requests to `example.org/metrics` to the separate Prometheus server running on port 9464.
## Enabling basic authentication ## Enabling basic authentication
You can enable basic authentication for the metrics endpoint. On the GoToSocial, side you'll need the following configuration: Although there is no sensitive data contained in the OTEL runtime statistics exported by Prometheus, you may nevertheless wish to gate access to the `/metrics` endpoint behind some kind of authentication, to prevent every Tom, Dick, and Harry from looking at your runtime stats.
```yaml You can do this by configuring your reverse proxy to require basic authentication for access to `/metrics`.
metrics-auth-enabled: true
metrics-auth-username: some_username In Nginx, for example, you could do this by creating an `htpasswd` file alongside your site in the `sites-available` directory of Nginx, and instructing Nginx to use that file to gate access.
metrics-auth-password: some_password
Assuming you followed the [guide for setting up Nginx as your reverse proxy](../getting_started/reverse_proxy/nginx.md), you will already have a file for your Nginx service definition at `/etc/nginx/sites-available/example.org`, where `example.org` is the hostname of your instance.
You can create an `htpasswd` file alongside this file using the following command:
```bash
htpasswd -c /etc/nginx/sites-available/example.org.htpasswd username
``` ```
You can scrape that endpoint with a Prometheus instance using the following configuration in your `scrape_configs`: In the command, be sure to replace `example.org` with your hostname, and `username` with whatever username you want to use.
Now, edit `/etc/nginx/sites-available/example.org` and update your `/metrics` stanza to use the `httpasswd` file. After editing it should look something like this:
```nginx
location /metrics {
proxy_pass http://127.0.0.1:9464;
auth_basic "Metrics";
auth_basic_user_file /etc/nginx/sites-available/example.org.htpasswd;
}
```
Again, replace `example.org` in that snippet with your instance hostname.
When you're finished editing, reload + restart Nginx, and you should see a basic authentication prompt when visiting the `/metrics` endpoint of your instance in your browser.
## Prometheus scrape configuration
You can scrape your `/metrics` endpoint with a Prometheus instance using the following configuration in your `scrape_configs`:
```yaml ```yaml
- job_name: gotosocial - job_name: gotosocial
@ -40,18 +97,12 @@ You can scrape that endpoint with a Prometheus instance using the following conf
- example.org - example.org
``` ```
## Blocking external scraping Change `example.org` to your hostname in the above snippet. If you are not using HTTPS, change the `scheme` value to `http`. If you are not using basic authentication, you can remove the `basic_auth` section. If you are not using a reverse proxy, and metrics are exposed on port 9464, add the port to the host (eg., `example.org` -> `example.org:9464`).
When running with a reverse proxy you can use it to block external access to metrics. You can use this approach if your Prometheus scraper runs on the same machine as your GoToSocial instance and can thus access it internally. ## Viewing metrics on Grafana
For example with nginx, block the `/metrics` endpoint by returning a 404: Instructions on how to set up Grafana are beyond the scope of this document. However, once you have set up a Grafana to pull from your Prometheus instance, you can import the [example Grafana dashboard](https://codeberg.org/superseriousbusiness/gotosocial/raw/branch/main/example/metrics/gotosocial_grafana_dashboard.json) into your Grafana frontend to easily view GoToSocial Go runtime and HTTP metrics.
```nginx
location /metrics {
return 404;
}
```
[otel]: https://opentelemetry.io/ [otel]: https://opentelemetry.io/
[prom]: https://prometheus.io/docs/instrumenting/exposition_formats/ [prom]: https://prometheus.io/docs/instrumenting/exposition_formats/
[obs]: ../configuration/observability.md [obs]: ../configuration/observability_and_metrics.md

View file

@ -16,7 +16,7 @@ tracing-insecure-transport: true
``` ```
[otel]: https://opentelemetry.io/ [otel]: https://opentelemetry.io/
[obs]: ../configuration/observability.md [obs]: ../configuration/observability_and_metrics.md
[tempo]: https://grafana.com/oss/tempo/ [tempo]: https://grafana.com/oss/tempo/
[grafana]: https://grafana.com/oss/grafana/ [grafana]: https://grafana.com/oss/grafana/
[ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing [ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing

View file

@ -1,50 +0,0 @@
# Observability
These settings let you tune and configure certain observability related behaviours.
GoToSocial uses OpenTelemetry. The metrics and trace exporters can be configured using the standard OpenTelemetry SDK environment variables. For a full reference, see [the OpenTelemetry docs](https://opentelemetry.io/docs/languages/sdk-configuration/).
## Metrics
Before enabling metrics, [read the guide](../advanced/metrics.md) and ensure you've taken the appropriate security measures for your setup.
### Tracing
To enable tracing, set `tracing-enabled` to `true`.
Valid values for `OTEL_TRACES_EXPORTER` are [documented here](https://opentelemetry.io/docs/languages/sdk-configuration/general/#otel_traces_exporter).
### Metrics
To enable metrics, set `metrics-enabled` to `true`. By default this'll use OTLP to push metrics to an OpenTelemetry receiver.
Valid values for `OTEL_METRICS_EXPORTER` are [documented here](https://opentelemetry.io/docs/languages/sdk-configuration/general/#otel_metrics_exporter)
For Prometheus, set `OTEL_METRICS_EXPORTER` to `prometheus`. This will start a **second** HTTP server, bound for `localhost:9464` with the OpenTelemetry metrics. You can change this using:
* `OTEL_EXPORTER_PROMETHEUS_HOST`
* `OTEL_EXPORTER_PROMETHEUS_PORT`
### Authentication
If you want to expose the metrics with authentication, you'll need a reverse proxy. You can configure it to proxy to `http://localhost:9464/metrics` and handle authentication in your reverse proxy however you like.
## Settings
```yaml
##################################
##### OBSERVABILITY SETTINGS #####
##################################
# String. Header name to use to extract a request or trace ID from. Typically set by a
# loadbalancer or proxy.
# Default: "X-Request-Id"
request-id-header: "X-Request-Id"
# Bool. Enable OpenTelemetry based tracing support.
# Default: false
tracing-enabled: false
# Bool. Enable OpenTelemetry based metrics support.
# Default: false
metrics-enabled: false
```

View file

@ -0,0 +1,63 @@
# Observability and Metrics
These settings let you tune and configure certain observability related behaviours.
GoToSocial uses OpenTelemetry. The metrics and trace exporters can be configured using the standard OpenTelemetry SDK environment variables. For a full reference, see [the OpenTelemetry docs](https://opentelemetry.io/docs/languages/sdk-configuration/).
## Metrics
Before enabling metrics, [read the guide](../advanced/metrics.md) and ensure you've taken the appropriate security measures for your setup.
If you want to expose metrics with (basic) authentication, you'll need to do this with a reverse proxy.
For more information and examples, see the [GtS metrics documentation](https://docs.gotosocial.org/en/latest/advanced/metrics/).
## Settings
```yaml
##############################################
##### OBSERVABILITY AND METRICS SETTINGS #####
##############################################
# String. Header name to use to extract a request or
# trace ID from. Typically set by a loadbalancer or proxy.
#
# Default: "X-Request-Id"
request-id-header: "X-Request-Id"
# Bool. Enable OpenTelemetry based tracing support.
#
# When enabling tracing, you must also configure a traces
# exporter using the OTEL environment variable documented here:
#
# https://opentelemetry.io/docs/languages/sdk-configuration/general/#otel_traces_exporter
#
# Default: false
tracing-enabled: false
# Bool. Enable OpenTelemetry based metrics support.
#
# To expose Prometheus metrics, you must configure a metrics producer and
# a metrics exporter, using the OTEL environment variables documented here:
#
# https://pkg.go.dev/go.opentelemetry.io/contrib/exporters/autoexport#NewMetricReader
#
# Typically, you will want to set the following environment variables
# (take note of the plural "producers" and singular "exporter"):
#
# - OTEL_METRICS_PRODUCERS=prometheus
# - OTEL_METRICS_EXPORTER=prometheus
#
# With these variables set, a Prometheus metrics endpoint will be exposed at
# localhost:9464/metrics. This can be further configured using the variables:
#
# - OTEL_EXPORTER_PROMETHEUS_HOST
# - OTEL_EXPORTER_PROMETHEUS_PORT
#
# For more information, see the GtS metrics documentation here:
#
# https://docs.gotosocial.org/en/latest/advanced/metrics/
#
# Default: false
metrics-enabled: false
```

View file

@ -54,4 +54,4 @@ location /metrics {
[otel]: https://opentelemetry.io/ [otel]: https://opentelemetry.io/
[prom]: https://prometheus.io/docs/instrumenting/exposition_formats/ [prom]: https://prometheus.io/docs/instrumenting/exposition_formats/
[obs]: ../configuration/observability.md [obs]: ../configuration/observability_and_metrics.md

View file

@ -16,7 +16,7 @@ tracing-insecure-transport: true
``` ```
[otel]: https://opentelemetry.io/ [otel]: https://opentelemetry.io/
[obs]: ../configuration/observability.md [obs]: ../configuration/observability_and_metrics.md
[tempo]: https://grafana.com/oss/tempo/ [tempo]: https://grafana.com/oss/tempo/
[grafana]: https://grafana.com/oss/grafana/ [grafana]: https://grafana.com/oss/grafana/
[ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing [ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing

View file

@ -62,7 +62,7 @@ nav:
- "configuration/syslog.md" - "configuration/syslog.md"
- "configuration/httpclient.md" - "configuration/httpclient.md"
- "configuration/advanced.md" - "configuration/advanced.md"
- "configuration/observability.md" - "configuration/observability_and_metrics.md"
- "进阶": - "进阶":
- "概述": "advanced/index.md" - "概述": "advanced/index.md"
- "advanced/host-account-domain.md" - "advanced/host-account-domain.md"

View file

@ -1076,20 +1076,50 @@ syslog-protocol: "udp"
# Default: "localhost:514" # Default: "localhost:514"
syslog-address: "localhost:514" syslog-address: "localhost:514"
################################## ##############################################
##### OBSERVABILITY SETTINGS ##### ##### OBSERVABILITY AND METRICS SETTINGS #####
################################## ##############################################
# String. Header name to use to extract a request or trace ID from. Typically set by a # String. Header name to use to extract a request or
# loadbalancer or proxy. # trace ID from. Typically set by a loadbalancer or proxy.
#
# Default: "X-Request-Id" # Default: "X-Request-Id"
request-id-header: "X-Request-Id" request-id-header: "X-Request-Id"
# Bool. Enable OpenTelemetry based tracing support. # Bool. Enable OpenTelemetry based tracing support.
#
# When enabling tracing, you must also configure a traces
# exporter using the OTEL environment variable documented here:
#
# https://opentelemetry.io/docs/languages/sdk-configuration/general/#otel_traces_exporter
#
# Default: false # Default: false
tracing-enabled: false tracing-enabled: false
# Bool. Enable OpenTelemetry based metrics support. # Bool. Enable OpenTelemetry based metrics support.
#
# To expose Prometheus metrics, you must configure a metrics producer and
# a metrics exporter, using the OTEL environment variables documented here:
#
# https://pkg.go.dev/go.opentelemetry.io/contrib/exporters/autoexport#NewMetricReader
#
# Typically, you will want to set the following environment variables
# (take note of the plural "producers" and singular "exporter"):
#
# - OTEL_METRICS_PRODUCERS=prometheus
# - OTEL_METRICS_EXPORTER=prometheus
#
# With these variables set, a Prometheus metrics endpoint will be exposed at
# localhost:9464/metrics. This can be further configured using the variables:
#
# - OTEL_EXPORTER_OTLP_METRICS_PROTOCOL
# - OTEL_EXPORTER_PROMETHEUS_HOST
# - OTEL_EXPORTER_PROMETHEUS_PORT
#
# For more information, see the GtS metrics documentation here:
#
# https://docs.gotosocial.org/en/latest/advanced/metrics/
#
# Default: false # Default: false
metrics-enabled: false metrics-enabled: false

View file

@ -22,6 +22,11 @@ Restart=on-failure
# Whatever you do, make sure the dir exists and that the gotosocial user has permission to write + read from it. # Whatever you do, make sure the dir exists and that the gotosocial user has permission to write + read from it.
#Environment="GTS_WAZERO_COMPILATION_CACHE=/gotosocial/.cache" #Environment="GTS_WAZERO_COMPILATION_CACHE=/gotosocial/.cache"
# If you have set `metrics-enabled` to `true` in your GoToSocial config file, and you want
# to expose Prometheus metrics at localhost:9464/metrics, uncomment the following two lines:
#Environment="OTEL_METRICS_EXPORTER=prometheus"
#Environment="OTEL_METRICS_PRODUCERS=prometheus"
# change if your path to the GoToSocial binary is different # change if your path to the GoToSocial binary is different
ExecStart=/gotosocial/gotosocial --config-path config.yaml server start ExecStart=/gotosocial/gotosocial --config-path config.yaml server start
WorkingDirectory=/gotosocial WorkingDirectory=/gotosocial

File diff suppressed because it is too large Load diff

2
go.mod
View file

@ -13,7 +13,6 @@ require (
code.superseriousbusiness.org/exif-terminator v0.11.0 code.superseriousbusiness.org/exif-terminator v0.11.0
code.superseriousbusiness.org/httpsig v1.4.0 code.superseriousbusiness.org/httpsig v1.4.0
code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384 code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384
codeberg.org/gruf/go-bitutil v1.1.0
codeberg.org/gruf/go-bytesize v1.0.4 codeberg.org/gruf/go-bytesize v1.0.4
codeberg.org/gruf/go-byteutil v1.3.0 codeberg.org/gruf/go-byteutil v1.3.0
codeberg.org/gruf/go-cache/v3 v3.6.1 codeberg.org/gruf/go-cache/v3 v3.6.1
@ -64,7 +63,6 @@ require (
github.com/spf13/viper v1.21.0 github.com/spf13/viper v1.21.0
github.com/stretchr/testify v1.11.1 github.com/stretchr/testify v1.11.1
github.com/tdewolff/minify/v2 v2.24.3 github.com/tdewolff/minify/v2 v2.24.3
github.com/technologize/otel-go-contrib v1.1.1
github.com/temoto/robotstxt v1.1.2 github.com/temoto/robotstxt v1.1.2
github.com/tetratelabs/wazero v1.9.0 github.com/tetratelabs/wazero v1.9.0
github.com/tomnomnom/linkheader v0.0.0-20250811210735-e5fe3b51442e github.com/tomnomnom/linkheader v0.0.0-20250811210735-e5fe3b51442e

4
go.sum generated
View file

@ -10,8 +10,6 @@ code.superseriousbusiness.org/httpsig v1.4.0 h1:g9+KQMoTG0oR0II5gYb5pVVdNjbc7Cii
code.superseriousbusiness.org/httpsig v1.4.0/go.mod h1:i2AKpj/WbA/o/UTvia9TAREzt0jP1AH3T1Uxjyhdzlw= code.superseriousbusiness.org/httpsig v1.4.0/go.mod h1:i2AKpj/WbA/o/UTvia9TAREzt0jP1AH3T1Uxjyhdzlw=
code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384 h1:eJzULGUyhHGk2DdQxX/jbH9FKZOyoIF90p3dzukCfLA= code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384 h1:eJzULGUyhHGk2DdQxX/jbH9FKZOyoIF90p3dzukCfLA=
code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384/go.mod h1:4x61i4C725jkXOpnUPFNfmiEthF6FZc/byADbalp+F8= code.superseriousbusiness.org/oauth2/v4 v4.5.4-0.20250812115401-3961e46a7384/go.mod h1:4x61i4C725jkXOpnUPFNfmiEthF6FZc/byADbalp+F8=
codeberg.org/gruf/go-bitutil v1.1.0 h1:U1Q+A1mtnPk+npqYrlRBc9ar2C5hYiBd17l1Wrp2Bt8=
codeberg.org/gruf/go-bitutil v1.1.0/go.mod h1:rGibFevYTQfYKcPv0Df5KpG8n5xC3AfD4d/UgYeoNy0=
codeberg.org/gruf/go-bytesize v1.0.4 h1:LEojK46lUoE748Om7yldx6kLe6jCCuiytz5IZ8vH35g= codeberg.org/gruf/go-bytesize v1.0.4 h1:LEojK46lUoE748Om7yldx6kLe6jCCuiytz5IZ8vH35g=
codeberg.org/gruf/go-bytesize v1.0.4/go.mod h1:n/GU8HzL9f3UNp/mUKyr1qVmTlj7+xacpp0OHfkvLPs= codeberg.org/gruf/go-bytesize v1.0.4/go.mod h1:n/GU8HzL9f3UNp/mUKyr1qVmTlj7+xacpp0OHfkvLPs=
codeberg.org/gruf/go-byteutil v1.3.0 h1:nRqJnCcRQ7xbfU6azw7zOzJrSMDIJHBqX6FL9vEMYmU= codeberg.org/gruf/go-byteutil v1.3.0 h1:nRqJnCcRQ7xbfU6azw7zOzJrSMDIJHBqX6FL9vEMYmU=
@ -437,8 +435,6 @@ github.com/tdewolff/parse/v2 v2.8.3 h1:5VbvtJ83cfb289A1HzRA9sf02iT8YyUwN84ezjkdY
github.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo= github.com/tdewolff/parse/v2 v2.8.3/go.mod h1:Hwlni2tiVNKyzR1o6nUs4FOF07URA+JLBLd6dlIXYqo=
github.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE= github.com/tdewolff/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE=
github.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8= github.com/tdewolff/test v1.0.11/go.mod h1:XPuWBzvdUzhCuxWO1ojpXsyzsA5bFoS3tO/Q3kFuTG8=
github.com/technologize/otel-go-contrib v1.1.1 h1:wZH9aSPNWZWIkEh3vfaKfMb15AJ80jJ1aVj/4GZdqIw=
github.com/technologize/otel-go-contrib v1.1.1/go.mod h1:dCN/wj2WyUO8aFZFdIN+6tfJHImjTML/8r2YVYAy3So=
github.com/temoto/robotstxt v1.1.2 h1:W2pOjSJ6SWvldyEuiFXNxz3xZ8aiWX5LbfDiOFd7Fxg= github.com/temoto/robotstxt v1.1.2 h1:W2pOjSJ6SWvldyEuiFXNxz3xZ8aiWX5LbfDiOFd7Fxg=
github.com/temoto/robotstxt v1.1.2/go.mod h1:+1AmkuG3IYkh1kv0d2qEB9Le88ehNO0zwOr3ujewlOo= github.com/temoto/robotstxt v1.1.2/go.mod h1:+1AmkuG3IYkh1kv0d2qEB9Le88ehNO0zwOr3ujewlOo=
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I= github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=

View file

@ -0,0 +1,154 @@
// GoToSocial
// Copyright (C) GoToSocial Authors admin@gotosocial.org
// SPDX-License-Identifier: AGPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//go:build !nootel
package observability
import (
"net/http"
"slices"
"time"
"code.superseriousbusiness.org/gotosocial/internal/config"
"github.com/gin-gonic/gin"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
)
// ginMiddleware returns a middleware that
// records metrics for incoming requests.
func ginMiddleware() gin.HandlerFunc {
meter := otel.Meter("gin", metric.WithInstrumentationVersion(config.GetSoftwareVersion()))
activeReqs, _ := meter.Int64UpDownCounter(
"http.server.requests_active",
metric.WithDescription("Number of requests currently active"),
)
totalReqs, _ := meter.Int64Counter(
"http.server.requests",
metric.WithDescription("Total number of requests served"),
)
reqSize, _ := meter.Int64Histogram(
"http.server.request_size",
metric.WithDescription("Request content length (approximate)"),
metric.WithUnit("bytes"),
)
respSize, _ := meter.Int64Histogram(
"http.server.response_size",
metric.WithDescription("Response content length"),
metric.WithUnit("bytes"),
)
duration, _ := meter.Int64Histogram(
"http.server.duration",
metric.WithDescription("Duration of request -> response"),
metric.WithUnit("ms"),
)
return func(c *gin.Context) {
ctx := c.Request.Context()
route := c.FullPath()
start := time.Now()
// Generate request attributes.
reqAttributes := []attribute.KeyValue{
semconv.HTTPServerNameKey.String("GoToSocial"),
semconv.HTTPMethodKey.String(c.Request.Method),
semconv.HTTPRouteKey.String(route),
}
// Increment active request count,
// decrement again when we're finished.
activeReqs.Add(ctx, 1, metric.WithAttributes(reqAttributes...))
defer activeReqs.Add(ctx, -1, metric.WithAttributes(reqAttributes...))
// Process request so we can
// record response metrics.
c.Next()
// Add HTTP response code to request
// attributes to create response attributes.
respAttributes := slices.Clone(reqAttributes)
respAttributes = append(
respAttributes,
semconv.HTTPStatusCodeKey.Int(c.Writer.Status()),
)
// Increment total requests.
totalReqs.Add(ctx, 1, metric.WithAttributes(respAttributes...))
// Record request size.
reqSize.Record(
ctx,
computeApproximateRequestSize(c.Request),
metric.WithAttributes(respAttributes...),
)
// Record response size.
respSize.Record(
ctx,
int64(c.Writer.Size()),
metric.WithAttributes(respAttributes...),
)
// Record req + resp duration.
duration.Record(
ctx,
time.Since(start).Milliseconds(),
metric.WithAttributes(respAttributes...),
)
}
}
func computeApproximateRequestSize(r *http.Request) (sz int64) {
len := func(s string) int64 { return int64(len(s)) }
// First line
sz += len(r.Method)
if r.URL != nil {
sz += len(r.URL.Path)
sz++ // for '?'
sz += len(r.URL.RawQuery)
sz += len(r.URL.RawFragment)
}
sz += len(r.Proto)
sz += 2 // for '\r\n'
// Next are lines for request headers.
for name, values := range r.Header {
// Each value on its own line.
for _, value := range values {
sz += len(name)
sz += len(value)
sz += 2 // for '\r\n'
}
}
// Finally, any request body (if set),
// this includes (multipart) form data.
sz += max(r.ContentLength, 0)
return
}

View file

@ -27,7 +27,6 @@ import (
"code.superseriousbusiness.org/gotosocial/internal/state" "code.superseriousbusiness.org/gotosocial/internal/state"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/technologize/otel-go-contrib/otelginmetrics"
"go.opentelemetry.io/contrib/exporters/autoexport" "go.opentelemetry.io/contrib/exporters/autoexport"
"go.opentelemetry.io/contrib/instrumentation/runtime" "go.opentelemetry.io/contrib/instrumentation/runtime"
"go.opentelemetry.io/otel" "go.opentelemetry.io/otel"
@ -266,5 +265,5 @@ func InitializeMetrics(ctx context.Context, state *state.State) error {
} }
func MetricsMiddleware() gin.HandlerFunc { func MetricsMiddleware() gin.HandlerFunc {
return otelginmetrics.Middleware(serviceName) return ginMiddleware()
} }

View file

@ -113,7 +113,7 @@ nav:
- "configuration/syslog.md" - "configuration/syslog.md"
- "configuration/httpclient.md" - "configuration/httpclient.md"
- "configuration/advanced.md" - "configuration/advanced.md"
- "configuration/observability.md" - "configuration/observability_and_metrics.md"
- "Advanced": - "Advanced":
- "Overview": "advanced/index.md" - "Overview": "advanced/index.md"
- "advanced/host-account-domain.md" - "advanced/host-account-domain.md"

View file

@ -1,9 +0,0 @@
MIT License
Copyright (c) 2022 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,3 +0,0 @@
# go-bitutil
This library provides helpful methods and types for performing typical bitwise operations on integers, e.g. packing/unpacking, bit flags.

View file

@ -1,29 +0,0 @@
package bitutil
// Abs8 returns the absolute value of i (calculated without branching).
func Abs8(i int8) int8 {
const bits = 8
u := uint64(i >> (bits - 1))
return (i ^ int8(u)) + int8(u&1)
}
// Abs16 returns the absolute value of i (calculated without branching).
func Abs16(i int16) int16 {
const bits = 16
u := uint64(i >> (bits - 1))
return (i ^ int16(u)) + int16(u&1)
}
// Abs32 returns the absolute value of i (calculated without branching).
func Abs32(i int32) int32 {
const bits = 32
u := uint64(i >> (bits - 1))
return (i ^ int32(u)) + int32(u&1)
}
// Abs64 returns the absolute value of i (calculated without branching).
func Abs64(i int64) int64 {
const bits = 64
u := uint64(i >> (bits - 1))
return (i ^ int64(u)) + int64(u&1)
}

File diff suppressed because it is too large Load diff

View file

@ -1,117 +0,0 @@
package bitutil
import (
"strings"
"unsafe"
)
{{ range $idx, $size := . }}
// Flags{{ $size.Size }} is a type-casted unsigned integer with helper
// methods for easily managing up to {{ $size.Size }} bit-flags.
type Flags{{ $size.Size }} uint{{ $size.Size }}
// Get will fetch the flag bit value at index 'bit'.
func (f Flags{{ $size.Size }}) Get(bit uint8) bool {
mask := Flags{{ $size.Size }}(1) << bit
return (f & mask != 0)
}
// Set will set the flag bit value at index 'bit'.
func (f Flags{{ $size.Size }}) Set(bit uint8) Flags{{ $size.Size }} {
mask := Flags{{ $size.Size }}(1) << bit
return f | mask
}
// Unset will unset the flag bit value at index 'bit'.
func (f Flags{{ $size.Size }}) Unset(bit uint8) Flags{{ $size.Size }} {
mask := Flags{{ $size.Size }}(1) << bit
return f & ^mask
}
{{ range $idx := $size.Bits }}
// Get{{ $idx }} will fetch the flag bit value at index {{ $idx }}.
func (f Flags{{ $size.Size }}) Get{{ $idx }}() bool {
const mask = Flags{{ $size.Size }}(1) << {{ $idx }}
return (f & mask != 0)
}
// Set{{ $idx }} will set the flag bit value at index {{ $idx }}.
func (f Flags{{ $size.Size }}) Set{{ $idx }}() Flags{{ $size.Size }} {
const mask = Flags{{ $size.Size }}(1) << {{ $idx }}
return f | mask
}
// Unset{{ $idx }} will unset the flag bit value at index {{ $idx }}.
func (f Flags{{ $size.Size }}) Unset{{ $idx }}() Flags{{ $size.Size }} {
const mask = Flags{{ $size.Size }}(1) << {{ $idx }}
return f & ^mask
}
{{ end }}
// String returns a human readable representation of Flags{{ $size.Size }}.
func (f Flags{{ $size.Size }}) String() string {
var (
i int
val bool
buf []byte
)
// Make a prealloc est. based on longest-possible value
const prealloc = 1+(len("false ")*{{ $size.Size }})-1+1
buf = make([]byte, prealloc)
buf[i] = '{'
i++
{{ range $idx := .Bits }}
val = f.Get{{ $idx }}()
i += copy(buf[i:], bool2str(val))
buf[i] = ' '
i++
{{ end }}
buf[i-1] = '}'
buf = buf[:i]
return *(*string)(unsafe.Pointer(&buf))
}
// GoString returns a more verbose human readable representation of Flags{{ $size.Size }}.
func (f Flags{{ $size.Size }})GoString() string {
var (
i int
val bool
buf []byte
)
// Make a prealloc est. based on longest-possible value
const prealloc = len("bitutil.Flags{{ $size.Size }}{")+(len("{{ sub $size.Size 1 }}=false ")*{{ $size.Size }})-1+1
buf = make([]byte, prealloc)
i += copy(buf[i:], "bitutil.Flags{{ $size.Size }}{")
{{ range $idx := .Bits }}
val = f.Get{{ $idx }}()
i += copy(buf[i:], "{{ $idx }}=")
i += copy(buf[i:], bool2str(val))
buf[i] = ' '
i++
{{ end }}
buf[i-1] = '}'
buf = buf[:i]
return *(*string)(unsafe.Pointer(&buf))
}
{{ end }}
func bool2str(b bool) string {
if b {
return "true"
}
return "false"
}

View file

@ -1,98 +0,0 @@
package bitutil_test
import (
"strings"
"testing"
"codeberg.org/gruf/go-bytes"
)
{{ range $idx, $size := . }}
func TestFlags{{ $size.Size }}Get(t *testing.T) {
var mask, flags bitutil.Flags{{ $size.Size }}
{{ range $idx := $size.Bits }}
mask = bitutil.Flags{{ $size.Size }}(1) << {{ $idx }}
flags = 0
flags |= mask
if !flags.Get({{ $idx }}) {
t.Error("failed .Get() set Flags{{ $size.Size }} bit at index {{ $idx }}")
}
flags = ^bitutil.Flags{{ $size.Size }}(0)
flags &= ^mask
if flags.Get({{ $idx }}) {
t.Error("failed .Get() unset Flags{{ $size.Size }} bit at index {{ $idx }}")
}
flags = 0
flags |= mask
if !flags.Get{{ $idx }}() {
t.Error("failed .Get{{ $idx }}() set Flags{{ $size.Size }} bit at index {{ $idx }}")
}
flags = ^bitutil.Flags{{ $size.Size }}(0)
flags &= ^mask
if flags.Get{{ $idx }}() {
t.Error("failed .Get{{ $idx }}() unset Flags{{ $size.Size }} bit at index {{ $idx }}")
}
{{ end }}
}
func TestFlags{{ $size.Size }}Set(t *testing.T) {
var mask, flags bitutil.Flags{{ $size.Size }}
{{ range $idx := $size.Bits }}
mask = bitutil.Flags{{ $size.Size }}(1) << {{ $idx }}
flags = 0
flags = flags.Set({{ $idx }})
if flags & mask == 0 {
t.Error("failed .Set() Flags{{ $size.Size }} bit at index {{ $idx }}")
}
flags = 0
flags = flags.Set{{ $idx }}()
if flags & mask == 0 {
t.Error("failed .Set{{ $idx }}() Flags{{ $size.Size }} bit at index {{ $idx }}")
}
{{ end }}
}
func TestFlags{{ $size.Size }}Unset(t *testing.T) {
var mask, flags bitutil.Flags{{ $size.Size }}
{{ range $idx := $size.Bits }}
mask = bitutil.Flags{{ $size.Size }}(1) << {{ $idx }}
flags = ^bitutil.Flags{{ $size.Size }}(0)
flags = flags.Unset({{ $idx }})
if flags & mask != 0 {
t.Error("failed .Unset() Flags{{ $size.Size }} bit at index {{ $idx }}")
}
flags = ^bitutil.Flags{{ $size.Size }}(0)
flags = flags.Unset{{ $idx }}()
if flags & mask != 0 {
t.Error("failed .Unset{{ $idx }}() Flags{{ $size.Size }} bit at index {{ $idx }}")
}
{{ end }}
}
{{ end }}

View file

@ -1,85 +0,0 @@
package bitutil
// PackInt8s will pack two signed 8bit integers into an unsigned 16bit integer.
func PackInt8s(i1, i2 int8) uint16 {
const bits = 8
const mask = (1 << bits) - 1
return uint16(i1)<<bits | uint16(i2)&mask
}
// UnpackInt8s will unpack two signed 8bit integers from an unsigned 16bit integer.
func UnpackInt8s(i uint16) (int8, int8) {
const bits = 8
const mask = (1 << bits) - 1
return int8(i >> bits), int8(i & mask)
}
// PackInt16s will pack two signed 16bit integers into an unsigned 32bit integer.
func PackInt16s(i1, i2 int16) uint32 {
const bits = 16
const mask = (1 << bits) - 1
return uint32(i1)<<bits | uint32(i2)&mask
}
// UnpackInt16s will unpack two signed 16bit integers from an unsigned 32bit integer.
func UnpackInt16s(i uint32) (int16, int16) {
const bits = 16
const mask = (1 << bits) - 1
return int16(i >> bits), int16(i & mask)
}
// PackInt32s will pack two signed 32bit integers into an unsigned 64bit integer.
func PackInt32s(i1, i2 int32) uint64 {
const bits = 32
const mask = (1 << bits) - 1
return uint64(i1)<<bits | uint64(i2)&mask
}
// UnpackInt32s will unpack two signed 32bit integers from an unsigned 64bit integer.
func UnpackInt32s(i uint64) (int32, int32) {
const bits = 32
const mask = (1 << bits) - 1
return int32(i >> bits), int32(i & mask)
}
// PackUint8s will pack two unsigned 8bit integers into an unsigned 16bit integer.
func PackUint8s(u1, u2 uint8) uint16 {
const bits = 8
const mask = (1 << bits) - 1
return uint16(u1)<<bits | uint16(u2)&mask
}
// UnpackUint8s will unpack two unsigned 8bit integers from an unsigned 16bit integer.
func UnpackUint8s(u uint16) (uint8, uint8) {
const bits = 8
const mask = (1 << bits) - 1
return uint8(u >> bits), uint8(u & mask)
}
// PackUint16s will pack two unsigned 16bit integers into an unsigned 32bit integer.
func PackUint16s(u1, u2 uint16) uint32 {
const bits = 16
const mask = (1 << bits) - 1
return uint32(u1)<<bits | uint32(u2)&mask
}
// UnpackUint16s will unpack two unsigned 16bit integers from an unsigned 32bit integer.
func UnpackUint16s(u uint32) (uint16, uint16) {
const bits = 16
const mask = (1 << bits) - 1
return uint16(u >> bits), uint16(u & mask)
}
// PackUint32s will pack two unsigned 32bit integers into an unsigned 64bit integer.
func PackUint32s(u1, u2 uint32) uint64 {
const bits = 32
const mask = (1 << bits) - 1
return uint64(u1)<<bits | uint64(u2)&mask
}
// UnpackUint32s will unpack two unsigned 32bit integers from an unsigned 64bit integer.
func UnpackUint32s(u uint64) (uint32, uint32) {
const bits = 32
const mask = (1 << bits) - 1
return uint32(u >> bits), uint32(u & mask)
}

View file

@ -1,60 +0,0 @@
package atomics_test
import (
"atomic"
"unsafe"
"testing"
"codeberg.org/gruf/go-atomics"
)
func Test{{ .Name }}StoreLoad(t *testing.T) {
for _, test := range {{ .Name }}Tests {
val := atomics.New{{ .Name }}()
val.Store(test.V1)
if !({{ call .Compare "val.Load()" "test.V1" }}) {
t.Fatalf("failed testing .Store and .Load: expect=%v actual=%v", val.Load(), test.V1)
}
val.Store(test.V2)
if !({{ call .Compare "val.Load()" "test.V2" }}) {
t.Fatalf("failed testing .Store and .Load: expect=%v actual=%v", val.Load(), test.V2)
}
}
}
func Test{{ .Name }}CAS(t *testing.T) {
for _, test := range {{ .Name }}Tests {
val := atomics.New{{ .Name }}()
val.Store(test.V1)
if val.CAS(test.V2, test.V1) {
t.Fatalf("failed testing negative .CAS: test=%+v state=%v", test, val.Load())
}
if !val.CAS(test.V1, test.V2) {
t.Fatalf("failed testing positive .CAS: test=%+v state=%v", test, val.Load())
}
}
}
func Test{{ .Name }}Swap(t *testing.T) {
for _, test := range {{ .Name }}Tests {
val := atomics.New{{ .Name }}()
val.Store(test.V1)
if !({{ call .Compare "val.Swap(test.V2)" "test.V1" }}) {
t.Fatal("failed testing .Swap")
}
if !({{ call .Compare "val.Swap(test.V1)" "test.V2" }}) {
t.Fatal("failed testing .Swap")
}
}
}

View file

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -1,45 +0,0 @@
package otelginmetrics
import (
"net/http"
"go.opentelemetry.io/otel/attribute"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
)
type config struct {
recordInFlight bool
recordSize bool
recordDuration bool
groupedStatus bool
recorder Recorder
attributes func(serverName, route string, request *http.Request) []attribute.KeyValue
shouldRecord func(serverName, route string, request *http.Request) bool
}
func defaultConfig() *config {
return &config{
recordInFlight: true,
recordDuration: true,
recordSize: true,
groupedStatus: true,
attributes: DefaultAttributes,
shouldRecord: func(_, _ string, _ *http.Request) bool {
return true
},
}
}
var DefaultAttributes = func(serverName, route string, request *http.Request) []attribute.KeyValue {
attrs := []attribute.KeyValue{
semconv.HTTPMethodKey.String(request.Method),
}
if serverName != "" {
attrs = append(attrs, semconv.HTTPServerNameKey.String(serverName))
}
if route != "" {
attrs = append(attrs, semconv.HTTPRouteKey.String(route))
}
return attrs
}

View file

@ -1,94 +0,0 @@
package otelginmetrics
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
semconv "go.opentelemetry.io/otel/semconv/v1.7.0"
)
// Middleware returns middleware that will trace incoming requests.
// The service parameter should describe the name of the (virtual)
// server handling the request.
func Middleware(service string, options ...Option) gin.HandlerFunc {
cfg := defaultConfig()
for _, option := range options {
option.apply(cfg)
}
recorder := cfg.recorder
if recorder == nil {
recorder = GetRecorder("")
}
return func(ginCtx *gin.Context) {
ctx := ginCtx.Request.Context()
route := ginCtx.FullPath()
if len(route) <= 0 {
route = "nonconfigured"
}
if !cfg.shouldRecord(service, route, ginCtx.Request) {
ginCtx.Next()
return
}
start := time.Now()
reqAttributes := cfg.attributes(service, route, ginCtx.Request)
if cfg.recordInFlight {
recorder.AddInflightRequests(ctx, 1, reqAttributes)
defer recorder.AddInflightRequests(ctx, -1, reqAttributes)
}
defer func() {
resAttributes := append(reqAttributes[0:0], reqAttributes...)
if cfg.groupedStatus {
code := int(ginCtx.Writer.Status()/100) * 100
resAttributes = append(resAttributes, semconv.HTTPStatusCodeKey.Int(code))
} else {
resAttributes = append(resAttributes, semconv.HTTPAttributesFromHTTPStatusCode(ginCtx.Writer.Status())...)
}
recorder.AddRequests(ctx, 1, resAttributes)
if cfg.recordSize {
requestSize := computeApproximateRequestSize(ginCtx.Request)
recorder.ObserveHTTPRequestSize(ctx, requestSize, resAttributes)
recorder.ObserveHTTPResponseSize(ctx, int64(ginCtx.Writer.Size()), resAttributes)
}
if cfg.recordDuration {
recorder.ObserveHTTPRequestDuration(ctx, time.Since(start), resAttributes)
}
}()
ginCtx.Next()
}
}
func computeApproximateRequestSize(r *http.Request) int64 {
s := 0
if r.URL != nil {
s = len(r.URL.Path)
}
s += len(r.Method)
s += len(r.Proto)
for name, values := range r.Header {
s += len(name)
for _, value := range values {
s += len(value)
}
}
s += len(r.Host)
// N.B. r.Form and r.MultipartForm are assumed to be included in r.URL.
if r.ContentLength != -1 {
s += int(r.ContentLength)
}
return int64(s)
}

View file

@ -1,74 +0,0 @@
package otelginmetrics
import (
"net/http"
"go.opentelemetry.io/otel/attribute"
)
// Option applies a configuration to the given config
type Option interface {
apply(cfg *config)
}
type optionFunc func(cfg *config)
func (fn optionFunc) apply(cfg *config) {
fn(cfg)
}
// WithAttributes sets a func using which what attributes to be recorded can be specified.
// By default the DefaultAttributes is used
func WithAttributes(attributes func(serverName, route string, request *http.Request) []attribute.KeyValue) Option {
return optionFunc(func(cfg *config) {
cfg.attributes = attributes
})
}
// WithRecordInFlight determines whether to record In Flight Requests or not
// By default the recordInFlight is true
func WithRecordInFlightDisabled() Option {
return optionFunc(func(cfg *config) {
cfg.recordInFlight = false
})
}
// WithRecordDuration determines whether to record Duration of Requests or not
// By default the recordDuration is true
func WithRecordDurationDisabled() Option {
return optionFunc(func(cfg *config) {
cfg.recordDuration = false
})
}
// WithRecordSize determines whether to record Size of Requests and Responses or not
// By default the recordSize is true
func WithRecordSizeDisabled() Option {
return optionFunc(func(cfg *config) {
cfg.recordSize = false
})
}
// WithGroupedStatus determines whether to group the response status codes or not. If true 2xx, 3xx will be stored
// By default the groupedStatus is true
func WithGroupedStatusDisabled() Option {
return optionFunc(func(cfg *config) {
cfg.groupedStatus = false
})
}
// WithRecorder sets a recorder for recording requests
// By default the open telemetry recorder is used
func WithRecorder(recorder Recorder) Option {
return optionFunc(func(cfg *config) {
cfg.recorder = recorder
})
}
// WithShouldRecordFunc sets a func using which whether a record should be recorded
// By default the all api calls are recorded
func WithShouldRecordFunc(shouldRecord func(serverName, route string, request *http.Request) bool) Option {
return optionFunc(func(cfg *config) {
cfg.shouldRecord = shouldRecord
})
}

View file

@ -1,70 +0,0 @@
package otelginmetrics
import (
"context"
"time"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/metric"
)
const instrumentationName = "github.com/technologize/otel-go-contrib/otelginmetrics"
// Recorder knows how to record and measure the metrics. This
// has the required methods to be used with the HTTP
// middlewares.
type otelRecorder struct {
attemptsCounter metric.Int64UpDownCounter
totalDuration metric.Int64Histogram
activeRequestsCounter metric.Int64UpDownCounter
requestSize metric.Int64Histogram
responseSize metric.Int64Histogram
}
func GetRecorder(metricsPrefix string) Recorder {
metricName := func(metricName string) string {
if len(metricsPrefix) > 0 {
return metricsPrefix + "." + metricName
}
return metricName
}
meter := otel.Meter(instrumentationName, metric.WithInstrumentationVersion(SemVersion()))
attemptsCounter, _ := meter.Int64UpDownCounter(metricName("http.server.request_count"), metric.WithDescription("Number of Requests"), metric.WithUnit("Count"))
totalDuration, _ := meter.Int64Histogram(metricName("http.server.duration"), metric.WithDescription("Time Taken by request"), metric.WithUnit("Milliseconds"))
activeRequestsCounter, _ := meter.Int64UpDownCounter(metricName("http.server.active_requests"), metric.WithDescription("Number of requests inflight"), metric.WithUnit("Count"))
requestSize, _ := meter.Int64Histogram(metricName("http.server.request_content_length"), metric.WithDescription("Request Size"), metric.WithUnit("Bytes"))
responseSize, _ := meter.Int64Histogram(metricName("http.server.response_content_length"), metric.WithDescription("Response Size"), metric.WithUnit("Bytes"))
return &otelRecorder{
attemptsCounter: attemptsCounter,
totalDuration: totalDuration,
activeRequestsCounter: activeRequestsCounter,
requestSize: requestSize,
responseSize: responseSize,
}
}
// AddRequests increments the number of requests being processed.
func (r *otelRecorder) AddRequests(ctx context.Context, quantity int64, attributes []attribute.KeyValue) {
r.attemptsCounter.Add(ctx, quantity, metric.WithAttributes(attributes...))
}
// ObserveHTTPRequestDuration measures the duration of an HTTP request.
func (r *otelRecorder) ObserveHTTPRequestDuration(ctx context.Context, duration time.Duration, attributes []attribute.KeyValue) {
r.totalDuration.Record(ctx, int64(duration/time.Millisecond), metric.WithAttributes(attributes...))
}
// ObserveHTTPRequestSize measures the size of an HTTP request in bytes.
func (r *otelRecorder) ObserveHTTPRequestSize(ctx context.Context, sizeBytes int64, attributes []attribute.KeyValue) {
r.requestSize.Record(ctx, sizeBytes, metric.WithAttributes(attributes...))
}
// ObserveHTTPResponseSize measures the size of an HTTP response in bytes.
func (r *otelRecorder) ObserveHTTPResponseSize(ctx context.Context, sizeBytes int64, attributes []attribute.KeyValue) {
r.responseSize.Record(ctx, sizeBytes, metric.WithAttributes(attributes...))
}
// AddInflightRequests increments and decrements the number of inflight request being processed.
func (r *otelRecorder) AddInflightRequests(ctx context.Context, quantity int64, attributes []attribute.KeyValue) {
r.activeRequestsCounter.Add(ctx, quantity, metric.WithAttributes(attributes...))
}

View file

@ -1,25 +0,0 @@
package otelginmetrics
import (
"context"
"time"
"go.opentelemetry.io/otel/attribute"
)
type Recorder interface {
// AddRequests increments the number of requests being processed.
AddRequests(ctx context.Context, quantity int64, attributes []attribute.KeyValue)
// ObserveHTTPRequestDuration measures the duration of an HTTP request.
ObserveHTTPRequestDuration(ctx context.Context, duration time.Duration, attributes []attribute.KeyValue)
// ObserveHTTPRequestSize measures the size of an HTTP request in bytes.
ObserveHTTPRequestSize(ctx context.Context, sizeBytes int64, attributes []attribute.KeyValue)
// ObserveHTTPResponseSize measures the size of an HTTP response in bytes.
ObserveHTTPResponseSize(ctx context.Context, sizeBytes int64, attributes []attribute.KeyValue)
// AddInflightRequests increments and decrements the number of inflight request being processed.
AddInflightRequests(ctx context.Context, quantity int64, attributes []attribute.KeyValue)
}

View file

@ -1,11 +0,0 @@
package otelginmetrics
// Version is the current release version of the gin instrumentation.
func Version() string {
return "1.0.0"
}
// SemVersion is the semantic version to be supplied to tracer/meter creation.
func SemVersion() string {
return "semver:" + Version()
}

6
vendor/modules.txt vendored
View file

@ -221,9 +221,6 @@ code.superseriousbusiness.org/oauth2/v4/generates
code.superseriousbusiness.org/oauth2/v4/manage code.superseriousbusiness.org/oauth2/v4/manage
code.superseriousbusiness.org/oauth2/v4/models code.superseriousbusiness.org/oauth2/v4/models
code.superseriousbusiness.org/oauth2/v4/server code.superseriousbusiness.org/oauth2/v4/server
# codeberg.org/gruf/go-bitutil v1.1.0
## explicit; go 1.19
codeberg.org/gruf/go-bitutil
# codeberg.org/gruf/go-bytesize v1.0.4 # codeberg.org/gruf/go-bytesize v1.0.4
## explicit; go 1.17 ## explicit; go 1.17
codeberg.org/gruf/go-bytesize codeberg.org/gruf/go-bytesize
@ -870,9 +867,6 @@ github.com/tdewolff/parse/v2
github.com/tdewolff/parse/v2/buffer github.com/tdewolff/parse/v2/buffer
github.com/tdewolff/parse/v2/html github.com/tdewolff/parse/v2/html
github.com/tdewolff/parse/v2/strconv github.com/tdewolff/parse/v2/strconv
# github.com/technologize/otel-go-contrib v1.1.1
## explicit; go 1.17
github.com/technologize/otel-go-contrib/otelginmetrics
# github.com/temoto/robotstxt v1.1.2 # github.com/temoto/robotstxt v1.1.2
## explicit; go 1.11 ## explicit; go 1.11
github.com/temoto/robotstxt github.com/temoto/robotstxt