mirror of
https://github.com/superseriousbusiness/gotosocial.git
synced 2025-10-28 11:22:25 -05:00
Compare commits
2 commits
e81bcb5171
...
82216281ce
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
82216281ce | ||
|
|
6607e1c944 |
45 changed files with 2762 additions and 4942 deletions
|
|
@ -1,32 +1,89 @@
|
|||
# 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
|
||||
* Gin (HTTP) metrics
|
||||
* Gin (HTTP server) 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
|
||||
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
|
||||
|
||||
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
|
||||
metrics-auth-enabled: true
|
||||
metrics-auth-username: some_username
|
||||
metrics-auth-password: some_password
|
||||
You can do this by configuring your reverse proxy to require basic authentication for access to `/metrics`.
|
||||
|
||||
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.
|
||||
|
||||
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
|
||||
- job_name: gotosocial
|
||||
|
|
@ -40,18 +97,12 @@ You can scrape that endpoint with a Prometheus instance using the following conf
|
|||
- 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:
|
||||
|
||||
```nginx
|
||||
location /metrics {
|
||||
return 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.
|
||||
|
||||
[otel]: https://opentelemetry.io/
|
||||
[prom]: https://prometheus.io/docs/instrumenting/exposition_formats/
|
||||
[obs]: ../configuration/observability.md
|
||||
[obs]: ../configuration/observability_and_metrics.md
|
||||
|
|
|
|||
|
|
@ -16,7 +16,7 @@ tracing-insecure-transport: true
|
|||
```
|
||||
|
||||
[otel]: https://opentelemetry.io/
|
||||
[obs]: ../configuration/observability.md
|
||||
[obs]: ../configuration/observability_and_metrics.md
|
||||
[tempo]: https://grafana.com/oss/tempo/
|
||||
[grafana]: https://grafana.com/oss/grafana/
|
||||
[ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing
|
||||
|
|
|
|||
|
|
@ -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
|
||||
```
|
||||
63
docs/configuration/observability_and_metrics.md
Normal file
63
docs/configuration/observability_and_metrics.md
Normal 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
|
||||
```
|
||||
|
|
@ -54,4 +54,4 @@ location /metrics {
|
|||
|
||||
[otel]: https://opentelemetry.io/
|
||||
[prom]: https://prometheus.io/docs/instrumenting/exposition_formats/
|
||||
[obs]: ../configuration/observability.md
|
||||
[obs]: ../configuration/observability_and_metrics.md
|
||||
|
|
@ -16,7 +16,7 @@ tracing-insecure-transport: true
|
|||
```
|
||||
|
||||
[otel]: https://opentelemetry.io/
|
||||
[obs]: ../configuration/observability.md
|
||||
[obs]: ../configuration/observability_and_metrics.md
|
||||
[tempo]: https://grafana.com/oss/tempo/
|
||||
[grafana]: https://grafana.com/oss/grafana/
|
||||
[ext]: https://codeberg.org/superseriousbusiness/gotosocial/tree/main/example/tracing
|
||||
|
|
|
|||
|
|
@ -62,7 +62,7 @@ nav:
|
|||
- "configuration/syslog.md"
|
||||
- "configuration/httpclient.md"
|
||||
- "configuration/advanced.md"
|
||||
- "configuration/observability.md"
|
||||
- "configuration/observability_and_metrics.md"
|
||||
- "进阶":
|
||||
- "概述": "advanced/index.md"
|
||||
- "advanced/host-account-domain.md"
|
||||
|
|
|
|||
|
|
@ -12,4 +12,8 @@ When enabled, the RSS feed for your account will be available at `https://[your-
|
|||
|
||||
## Which posts are shared via RSS?
|
||||
|
||||
Only your latest 20 Public posts are shared via RSS. Replies and reblogs/boosts are not included. Unlisted posts are not included. In other words, the only posts visible via RSS will be the same ones that are visible when you open your profile in a browser.
|
||||
Only your latest 20 Public posts are shared via RSS by default. Replies and reblogs/boosts are not included. Unlisted posts are not included. In other words, the only posts visible via RSS will be the same ones that are visible when you open your profile in a browser.
|
||||
|
||||
If you want to see more posts, you can provide our standard set of timeline paging parameters ([as per our swagger documentation](https://docs.gotosocial.org/en/latest/api/swagger)) to see beyond the first page.
|
||||
|
||||
You can also access Atom and JSON feeds from this same endpoint, but providing the appropriate request content-type header. i.e. `application/atom+xml` for an Atom feed, or `application/feed+json` for a JSON feed.
|
||||
|
|
|
|||
|
|
@ -1076,20 +1076,50 @@ syslog-protocol: "udp"
|
|||
# Default: "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
|
||||
# loadbalancer or proxy.
|
||||
# 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_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
|
||||
metrics-enabled: false
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
#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
|
||||
ExecStart=/gotosocial/gotosocial --config-path config.yaml server start
|
||||
WorkingDirectory=/gotosocial
|
||||
|
|
|
|||
1980
example/metrics/gotosocial_grafana_dashboard.json
Normal file
1980
example/metrics/gotosocial_grafana_dashboard.json
Normal file
File diff suppressed because it is too large
Load diff
2
go.mod
2
go.mod
|
|
@ -13,7 +13,6 @@ require (
|
|||
code.superseriousbusiness.org/exif-terminator v0.11.0
|
||||
code.superseriousbusiness.org/httpsig v1.4.0
|
||||
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-byteutil v1.3.0
|
||||
codeberg.org/gruf/go-cache/v3 v3.6.1
|
||||
|
|
@ -64,7 +63,6 @@ require (
|
|||
github.com/spf13/viper v1.21.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
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/tetratelabs/wazero v1.9.0
|
||||
github.com/tomnomnom/linkheader v0.0.0-20250811210735-e5fe3b51442e
|
||||
|
|
|
|||
4
go.sum
generated
4
go.sum
generated
|
|
@ -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/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=
|
||||
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/go.mod h1:n/GU8HzL9f3UNp/mUKyr1qVmTlj7+xacpp0OHfkvLPs=
|
||||
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/test v1.0.11 h1:FdLbwQVHxqG16SlkGveC0JVyrJN62COWTRyUFzfbtBE=
|
||||
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/go.mod h1:+1AmkuG3IYkh1kv0d2qEB9Le88ehNO0zwOr3ujewlOo=
|
||||
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
|
||||
|
|
|
|||
|
|
@ -26,6 +26,8 @@ const (
|
|||
appXMLText = `text/xml` // AppXML is only *recommended* in RFC7303
|
||||
AppXMLXRD = `application/xrd+xml`
|
||||
AppRSSXML = `application/rss+xml`
|
||||
AppAtomXML = `application/atom+xml`
|
||||
AppFeedJSON = `application/feed+json`
|
||||
AppActivityJSON = `application/activity+json`
|
||||
appActivityLDJSON = `application/ld+json` // without profile
|
||||
AppActivityLDJSON = appActivityLDJSON + `; profile="https://www.w3.org/ns/activitystreams"`
|
||||
|
|
|
|||
|
|
@ -71,6 +71,18 @@ func JSONType(c *gin.Context, code int, contentType string, data any) {
|
|||
EncodeJSONResponse(c.Writer, c.Request, code, contentType, data)
|
||||
}
|
||||
|
||||
// XML calls EncodeJSONResponse() using gin.Context{}, with content-type = AppXML,
|
||||
// This function handles the case of XML unmarshal errors and pools read buffers.
|
||||
func XML(c *gin.Context, code int, data any) {
|
||||
EncodeXMLResponse(c.Writer, c.Request, code, AppXML, data)
|
||||
}
|
||||
|
||||
// XML calls EncodeXMLResponse() using gin.Context{}, with given content-type.
|
||||
// This function handles the case of XML unmarshal errors and pools read buffers.
|
||||
func XMLType(c *gin.Context, code int, contentType string, data any) {
|
||||
EncodeXMLResponse(c.Writer, c.Request, code, contentType, data)
|
||||
}
|
||||
|
||||
// Data calls WriteResponseBytes() using gin.Context{}, with given content-type.
|
||||
func Data(c *gin.Context, code int, contentType string, data []byte) {
|
||||
WriteResponseBytes(c.Writer, c.Request, code, contentType, data)
|
||||
|
|
@ -230,6 +242,7 @@ func EncodeCSVResponse(
|
|||
|
||||
// Write all the records to the buffer.
|
||||
if err := csvWriter.WriteAll(records); err == nil {
|
||||
|
||||
// Respond with the now-known
|
||||
// size byte slice within buf.
|
||||
WriteResponseBytes(rw, r,
|
||||
|
|
|
|||
|
|
@ -121,7 +121,7 @@ type Account interface {
|
|||
// returning statuses that should be visible via the web view of a *LOCAL* account.
|
||||
//
|
||||
// In the case of no statuses, this function will return db.ErrNoEntries.
|
||||
GetAccountWebStatuses(ctx context.Context, account *gtsmodel.Account, mediaOnly bool, limit int, maxID string) ([]*gtsmodel.Status, error)
|
||||
GetAccountWebStatuses(ctx context.Context, account *gtsmodel.Account, page *paging.Page, mediaOnly bool) ([]*gtsmodel.Status, error)
|
||||
|
||||
// GetInstanceAccount returns the instance account for the given domain.
|
||||
// If domain is empty, this instance account will be returned.
|
||||
|
|
|
|||
|
|
@ -900,7 +900,7 @@ func (a *accountDB) GetAccountFaves(ctx context.Context, accountID string) ([]*g
|
|||
return *faves, nil
|
||||
}
|
||||
|
||||
func qMediaOnly(q *bun.SelectQuery) *bun.SelectQuery {
|
||||
func selectOnlyWithMedia(q *bun.SelectQuery) *bun.SelectQuery {
|
||||
// Attachments are stored as a json object; this
|
||||
// implementation differs between SQLite and Postgres,
|
||||
// so we have to be thorough to cover all eventualities
|
||||
|
|
@ -908,14 +908,14 @@ func qMediaOnly(q *bun.SelectQuery) *bun.SelectQuery {
|
|||
switch d := q.Dialect().Name(); d {
|
||||
case dialect.PG:
|
||||
return q.
|
||||
Where("? IS NOT NULL", bun.Ident("status.attachments")).
|
||||
Where("? != '{}'", bun.Ident("status.attachments"))
|
||||
Where("? IS NOT NULL", bun.Ident("attachments")).
|
||||
Where("? != '{}'", bun.Ident("attachments"))
|
||||
|
||||
case dialect.SQLite:
|
||||
return q.
|
||||
Where("? IS NOT NULL", bun.Ident("status.attachments")).
|
||||
Where("? != 'null'", bun.Ident("status.attachments")).
|
||||
Where("? != '[]'", bun.Ident("status.attachments"))
|
||||
Where("? IS NOT NULL", bun.Ident("attachments")).
|
||||
Where("? != 'null'", bun.Ident("attachments")).
|
||||
Where("? != '[]'", bun.Ident("attachments"))
|
||||
|
||||
default:
|
||||
panic("dialect " + d.String() + " was neither pg nor sqlite")
|
||||
|
|
@ -963,9 +963,9 @@ func (a *accountDB) GetAccountStatuses(ctx context.Context, accountID string, li
|
|||
q = q.Where("? IS NULL", bun.Ident("status.boost_of_id"))
|
||||
}
|
||||
|
||||
// Respect media-only preference.
|
||||
if mediaOnly {
|
||||
q = qMediaOnly(q)
|
||||
// Respect mediaOnly pref.
|
||||
q = selectOnlyWithMedia(q)
|
||||
}
|
||||
|
||||
if publicOnly {
|
||||
|
|
@ -1041,12 +1041,16 @@ func (a *accountDB) GetAccountPinnedStatuses(ctx context.Context, accountID stri
|
|||
return a.state.DB.GetStatusesByIDs(ctx, statusIDs)
|
||||
}
|
||||
|
||||
var webStatusVisibilities = bun.In([]gtsmodel.Visibility{
|
||||
gtsmodel.VisibilityPublic,
|
||||
gtsmodel.VisibilityUnlocked,
|
||||
})
|
||||
|
||||
func (a *accountDB) GetAccountWebStatuses(
|
||||
ctx context.Context,
|
||||
account *gtsmodel.Account,
|
||||
page *paging.Page,
|
||||
mediaOnly bool,
|
||||
limit int,
|
||||
maxID string,
|
||||
) ([]*gtsmodel.Status, error) {
|
||||
if account.Username == config.GetHost() {
|
||||
// Instance account
|
||||
|
|
@ -1071,74 +1075,35 @@ func (a *accountDB) GetAccountWebStatuses(
|
|||
return nil, nil
|
||||
}
|
||||
|
||||
// Ensure reasonable
|
||||
if limit < 0 {
|
||||
limit = 0
|
||||
}
|
||||
return loadStatusTimelinePage(ctx, a.db, a.state,
|
||||
|
||||
// Make educated guess for slice size
|
||||
statusIDs := make([]string, 0, limit)
|
||||
// Paging
|
||||
// params.
|
||||
page,
|
||||
|
||||
q := a.db.
|
||||
NewSelect().
|
||||
TableExpr("? AS ?", bun.Ident("statuses"), bun.Ident("status")).
|
||||
// Select only IDs from table
|
||||
Column("status.id").
|
||||
Where("? = ?", bun.Ident("status.account_id"), account.ID)
|
||||
// The actual meat of the account web statuses query.
|
||||
func(q *bun.SelectQuery) (*bun.SelectQuery, error) {
|
||||
q = q.Where("? = ?", bun.Ident("account_id"), account.ID)
|
||||
|
||||
// Select statuses according to
|
||||
// account's web visibility prefs.
|
||||
if publicOnly {
|
||||
// Only Public statuses.
|
||||
q = q.Where("? = ?", bun.Ident("status.visibility"), gtsmodel.VisibilityPublic)
|
||||
} else {
|
||||
// Public or Unlocked.
|
||||
visis := []gtsmodel.Visibility{
|
||||
gtsmodel.VisibilityPublic,
|
||||
gtsmodel.VisibilityUnlocked,
|
||||
}
|
||||
q = q.Where("? IN (?)", bun.Ident("status.visibility"), bun.In(visis))
|
||||
}
|
||||
if publicOnly {
|
||||
q = q.Where("? = ?", bun.Ident("visibility"), gtsmodel.VisibilityPublic)
|
||||
} else {
|
||||
q = q.Where("? IN (?)", bun.Ident("visibility"), webStatusVisibilities)
|
||||
}
|
||||
|
||||
// Don't show replies, boosts, or
|
||||
// local-only statuses on the web view.
|
||||
q = q.
|
||||
Where("? IS NULL", bun.Ident("status.in_reply_to_uri")).
|
||||
Where("? IS NULL", bun.Ident("status.boost_of_id")).
|
||||
Where("? = ?", bun.Ident("status.federated"), true)
|
||||
// Don't show replies, boosts, or local-only in web view.
|
||||
q = q.Where("? IS NULL", bun.Ident("in_reply_to_uri")).
|
||||
Where("? IS NULL", bun.Ident("boost_of_id")).
|
||||
Where("? = ?", bun.Ident("federated"), true)
|
||||
|
||||
// Respect media-only preference.
|
||||
if mediaOnly {
|
||||
q = qMediaOnly(q)
|
||||
}
|
||||
if mediaOnly {
|
||||
// Respect mediaOnly pref.
|
||||
q = selectOnlyWithMedia(q)
|
||||
}
|
||||
|
||||
// Return only statuses LOWER (ie., older) than maxID
|
||||
if maxID == "" {
|
||||
maxID = id.Highest
|
||||
}
|
||||
q = q.Where("? < ?", bun.Ident("status.id"), maxID)
|
||||
|
||||
if limit > 0 {
|
||||
// limit amount of statuses returned
|
||||
q = q.Limit(limit)
|
||||
}
|
||||
|
||||
if limit > 0 {
|
||||
// limit amount of statuses returned
|
||||
q = q.Limit(limit)
|
||||
}
|
||||
|
||||
q = q.Order("status.id DESC")
|
||||
|
||||
if err := q.Scan(ctx, &statusIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if len(statusIDs) == 0 {
|
||||
return nil, db.ErrNoEntries
|
||||
}
|
||||
|
||||
return a.state.DB.GetStatusesByIDs(ctx, statusIDs)
|
||||
return q, nil
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
func (a *accountDB) GetAccountSettings(
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ func (suite *AccountTestSuite) TestGetAccountStatuses() {
|
|||
}
|
||||
|
||||
func (suite *AccountTestSuite) TestGetAccountWebStatusesMediaOnly() {
|
||||
statuses, err := suite.db.GetAccountWebStatuses(suite.T().Context(), suite.testAccounts["local_account_3"], true, 20, "")
|
||||
statuses, err := suite.db.GetAccountWebStatuses(suite.T().Context(), suite.testAccounts["local_account_3"], &paging.Page{Limit: 20}, true)
|
||||
suite.NoError(err)
|
||||
suite.Len(statuses, 2)
|
||||
}
|
||||
|
|
|
|||
154
internal/observability/gin.go
Normal file
154
internal/observability/gin.go
Normal 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
|
||||
}
|
||||
|
|
@ -27,7 +27,6 @@ import (
|
|||
"code.superseriousbusiness.org/gotosocial/internal/state"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/technologize/otel-go-contrib/otelginmetrics"
|
||||
"go.opentelemetry.io/contrib/exporters/autoexport"
|
||||
"go.opentelemetry.io/contrib/instrumentation/runtime"
|
||||
"go.opentelemetry.io/otel"
|
||||
|
|
@ -266,5 +265,5 @@ func InitializeMetrics(ctx context.Context, state *state.State) error {
|
|||
}
|
||||
|
||||
func MetricsMiddleware() gin.HandlerFunc {
|
||||
return otelginmetrics.Middleware(serviceName)
|
||||
return ginMiddleware()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -20,21 +20,19 @@ package account
|
|||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"code.superseriousbusiness.org/gotosocial/internal/config"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/db"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/gtserror"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/gtsmodel"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/paging"
|
||||
"github.com/gorilla/feeds"
|
||||
)
|
||||
|
||||
const (
|
||||
rssFeedLength = 20
|
||||
)
|
||||
var never time.Time
|
||||
|
||||
type GetRSSFeed func() (string, gtserror.WithCode)
|
||||
type GetRSSFeed func() (*feeds.Feed, gtserror.WithCode)
|
||||
|
||||
// GetRSSFeedForUsername returns a function to return the RSS feed of a local account
|
||||
// with the given username, and the last-modified time (time that the account last
|
||||
|
|
@ -45,33 +43,30 @@ type GetRSSFeed func() (string, gtserror.WithCode)
|
|||
//
|
||||
// If the account has not yet posted an RSS-eligible status, the returned last-modified
|
||||
// time will be zero, and the GetRSSFeed func will return a valid RSS xml with no items.
|
||||
func (p *Processor) GetRSSFeedForUsername(ctx context.Context, username string) (GetRSSFeed, time.Time, gtserror.WithCode) {
|
||||
var (
|
||||
never = time.Time{}
|
||||
)
|
||||
func (p *Processor) GetRSSFeedForUsername(ctx context.Context, username string, page *paging.Page) (GetRSSFeed, time.Time, gtserror.WithCode) {
|
||||
|
||||
// Fetch local (i.e. empty domain) account from database by username.
|
||||
account, err := p.state.DB.GetAccountByUsernameDomain(ctx, username, "")
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNoEntries) {
|
||||
// Simply no account with this username.
|
||||
err = gtserror.New("account not found")
|
||||
return nil, never, gtserror.NewErrorNotFound(err)
|
||||
}
|
||||
|
||||
// Real db error.
|
||||
err = gtserror.Newf("db error getting account %s: %w", username, err)
|
||||
err := gtserror.Newf("db error getting account %s: %w", username, err)
|
||||
return nil, never, gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
// Check if exists.
|
||||
if account == nil {
|
||||
err := gtserror.New("account not found")
|
||||
return nil, never, gtserror.NewErrorNotFound(err)
|
||||
}
|
||||
|
||||
// Ensure account has rss feed enabled.
|
||||
if !*account.Settings.EnableRSS {
|
||||
err = gtserror.New("account RSS feed not enabled")
|
||||
err := gtserror.New("account RSS feed not enabled")
|
||||
return nil, never, gtserror.NewErrorNotFound(err)
|
||||
}
|
||||
|
||||
// Ensure account stats populated.
|
||||
// Ensure account stats populated for last status fetch information.
|
||||
if err := p.state.DB.PopulateAccountStats(ctx, account); err != nil {
|
||||
err = gtserror.Newf("db error getting account stats %s: %w", username, err)
|
||||
err := gtserror.Newf("db error getting account stats %s: %w", username, err)
|
||||
return nil, never, gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
|
|
@ -80,14 +75,14 @@ func (p *Processor) GetRSSFeedForUsername(ctx context.Context, username string)
|
|||
// eligible to appear in the RSS feed; that's fine.
|
||||
lastPostAt := account.Stats.LastStatusAt
|
||||
|
||||
return func() (string, gtserror.WithCode) {
|
||||
return func() (*feeds.Feed, gtserror.WithCode) {
|
||||
// Assemble author namestring once only.
|
||||
author := "@" + account.Username + "@" + config.GetAccountDomain()
|
||||
|
||||
// Derive image/thumbnail for this account (may be nil).
|
||||
// Derive image/thumbnail for this account (may be nil if no media).
|
||||
image, errWithCode := p.rssImageForAccount(ctx, account, author)
|
||||
if errWithCode != nil {
|
||||
return "", errWithCode
|
||||
return nil, errWithCode
|
||||
}
|
||||
|
||||
feed := &feeds.Feed{
|
||||
|
|
@ -106,7 +101,7 @@ func (p *Processor) GetRSSFeedForUsername(ctx context.Context, username string)
|
|||
// since we already know there's no eligible statuses.
|
||||
if lastPostAt.IsZero() {
|
||||
feed.Updated = account.CreatedAt
|
||||
return stringifyFeed(feed)
|
||||
return feed, nil
|
||||
}
|
||||
|
||||
// Account has posted at least one status that's
|
||||
|
|
@ -120,32 +115,30 @@ func (p *Processor) GetRSSFeedForUsername(ctx context.Context, username string)
|
|||
//
|
||||
// Take into account whether the user wants
|
||||
// their web view laid out in gallery mode.
|
||||
mediaOnly := account.Settings != nil &&
|
||||
account.Settings.WebLayout == gtsmodel.WebLayoutGallery
|
||||
mediaOnly := (account.Settings != nil &&
|
||||
account.Settings.WebLayout == gtsmodel.WebLayoutGallery)
|
||||
statuses, err := p.state.DB.GetAccountWebStatuses(
|
||||
ctx,
|
||||
account,
|
||||
page,
|
||||
mediaOnly,
|
||||
rssFeedLength,
|
||||
"", // Latest posts from the top.
|
||||
)
|
||||
if err != nil && !errors.Is(err, db.ErrNoEntries) {
|
||||
err = fmt.Errorf("db error getting account web statuses: %w", err)
|
||||
return "", gtserror.NewErrorInternalError(err)
|
||||
err := gtserror.Newf("db error getting account web statuses: %w", err)
|
||||
return nil, gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
// Add each status to the rss feed.
|
||||
for _, status := range statuses {
|
||||
item, err := p.converter.StatusToRSSItem(ctx, status)
|
||||
if err != nil {
|
||||
err = gtserror.Newf("error converting status to feed item: %w", err)
|
||||
return "", gtserror.NewErrorInternalError(err)
|
||||
err := gtserror.Newf("error converting status to feed item: %w", err)
|
||||
return nil, gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
feed.Add(item)
|
||||
}
|
||||
|
||||
return stringifyFeed(feed)
|
||||
return feed, nil
|
||||
}, lastPostAt, nil
|
||||
}
|
||||
|
||||
|
|
@ -177,15 +170,3 @@ func (p *Processor) rssImageForAccount(ctx context.Context, account *gtsmodel.Ac
|
|||
Link: account.URL,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func stringifyFeed(feed *feeds.Feed) (string, gtserror.WithCode) {
|
||||
// Stringify the feed. Even with no statuses,
|
||||
// this will still produce valid rss xml.
|
||||
rss, err := feed.ToRss()
|
||||
if err != nil {
|
||||
err := gtserror.Newf("error converting feed to rss string: %w", err)
|
||||
return "", gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
return rss, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,7 +19,10 @@ package account_test
|
|||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"code.superseriousbusiness.org/gotosocial/internal/paging"
|
||||
"github.com/gorilla/feeds"
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
|
|
@ -28,13 +31,8 @@ type GetRSSTestSuite struct {
|
|||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountRSSAdmin() {
|
||||
getFeed, lastModified, err := suite.accountProcessor.GetRSSFeedForUsername(suite.T().Context(), "admin")
|
||||
suite.NoError(err)
|
||||
suite.EqualValues(1634726497, lastModified.Unix())
|
||||
|
||||
feed, err := getFeed()
|
||||
suite.NoError(err)
|
||||
suite.Equal(`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
suite.testGetFeedSerializedAs("admin", &paging.Page{Limit: 20}, (*feeds.Feed).ToRss, 1634726497,
|
||||
`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<title>Posts from @admin@localhost:8080</title>
|
||||
<link>http://localhost:8080/@admin</link>
|
||||
|
|
@ -63,17 +61,94 @@ func (suite *GetRSSTestSuite) TestGetAccountRSSAdmin() {
|
|||
<source>http://localhost:8080/@admin/feed.rss</source>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>`, feed)
|
||||
</rss>`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountAtomAdmin() {
|
||||
suite.testGetFeedSerializedAs("admin", &paging.Page{Limit: 20}, (*feeds.Feed).ToAtom, 1634726497,
|
||||
`<?xml version="1.0" encoding="UTF-8"?><feed xmlns="http://www.w3.org/2005/Atom">
|
||||
<title>Posts from @admin@localhost:8080</title>
|
||||
<id>http://localhost:8080/@admin</id>
|
||||
<updated>2021-10-20T10:41:37Z</updated>
|
||||
<subtitle>Posts from @admin@localhost:8080</subtitle>
|
||||
<link href="http://localhost:8080/@admin"></link>
|
||||
<entry>
|
||||
<title>open to see some <strong>puppies</strong></title>
|
||||
<updated>2021-10-20T12:36:45Z</updated>
|
||||
<id>http://localhost:8080/@admin/statuses/01F8MHAAY43M6RJ473VQFCVH37</id>
|
||||
<content type="html"><p>🐕🐕🐕🐕🐕</p></content>
|
||||
<link href="http://localhost:8080/@admin/statuses/01F8MHAAY43M6RJ473VQFCVH37" rel="alternate"></link>
|
||||
<link href="" rel="enclosure"></link>
|
||||
<summary type="html">@admin@localhost:8080 made a new post: "🐕🐕🐕🐕🐕"</summary>
|
||||
<author>
|
||||
<name>@admin@localhost:8080</name>
|
||||
</author>
|
||||
</entry>
|
||||
<entry>
|
||||
<title>hello world! #welcome ! first post on the instance :rainbow: !</title>
|
||||
<updated>2021-10-20T11:36:45Z</updated>
|
||||
<id>http://localhost:8080/@admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R</id>
|
||||
<content type="html"><p>hello world! <a href="http://localhost:8080/tags/welcome" class="mention hashtag" rel="tag nofollow noreferrer noopener" target="_blank">#<span>welcome</span></a> ! first post on the instance <img src="http://localhost:8080/fileserver/01AY6P665V14JJR0AFVRT7311Y/emoji/original/01F8MH9H8E4VG3KDYJR9EGPXCQ.png" title=":rainbow:" alt=":rainbow:" width="25" height="25" /> !</p></content>
|
||||
<link href="http://localhost:8080/@admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R" rel="alternate"></link>
|
||||
<link href="http://localhost:8080/fileserver/01F8MH17FWEB39HZJ76B6VXSKF/attachment/original/01F8MH6NEM8D7527KZAECTCR76.jpg" rel="enclosure" type="image/jpeg" length="62529"></link>
|
||||
<summary type="html">@admin@localhost:8080 posted 1 attachment: "hello world! #welcome ! first post on the instance :rainbow: !"</summary>
|
||||
<author>
|
||||
<name>@admin@localhost:8080</name>
|
||||
</author>
|
||||
</entry>
|
||||
</feed>`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountJSONAdmin() {
|
||||
suite.testGetFeedSerializedAs("admin", &paging.Page{Limit: 20}, (*feeds.Feed).ToJSON, 1634726497,
|
||||
`{
|
||||
"version": "https://jsonfeed.org/version/1.1",
|
||||
"title": "Posts from @admin@localhost:8080",
|
||||
"home_page_url": "http://localhost:8080/@admin",
|
||||
"description": "Posts from @admin@localhost:8080",
|
||||
"items": [
|
||||
{
|
||||
"id": "http://localhost:8080/@admin/statuses/01F8MHAAY43M6RJ473VQFCVH37",
|
||||
"url": "http://localhost:8080/@admin/statuses/01F8MHAAY43M6RJ473VQFCVH37",
|
||||
"external_url": "http://localhost:8080/@admin/feed.rss",
|
||||
"title": "open to see some \u003cstrong\u003epuppies\u003c/strong\u003e",
|
||||
"content_html": "\u003cp\u003e🐕🐕🐕🐕🐕\u003c/p\u003e",
|
||||
"summary": "@admin@localhost:8080 made a new post: \"🐕🐕🐕🐕🐕\"",
|
||||
"date_published": "2021-10-20T12:36:45Z",
|
||||
"author": {
|
||||
"name": "@admin@localhost:8080"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "@admin@localhost:8080"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "http://localhost:8080/@admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R",
|
||||
"url": "http://localhost:8080/@admin/statuses/01F8MH75CBF9JFX4ZAD54N0W0R",
|
||||
"external_url": "http://localhost:8080/@admin/feed.rss",
|
||||
"title": "hello world! #welcome ! first post on the instance :rainbow: !",
|
||||
"content_html": "\u003cp\u003ehello world! \u003ca href=\"http://localhost:8080/tags/welcome\" class=\"mention hashtag\" rel=\"tag nofollow noreferrer noopener\" target=\"_blank\"\u003e#\u003cspan\u003ewelcome\u003c/span\u003e\u003c/a\u003e ! first post on the instance \u003cimg src=\"http://localhost:8080/fileserver/01AY6P665V14JJR0AFVRT7311Y/emoji/original/01F8MH9H8E4VG3KDYJR9EGPXCQ.png\" title=\":rainbow:\" alt=\":rainbow:\" width=\"25\" height=\"25\" /\u003e !\u003c/p\u003e",
|
||||
"summary": "@admin@localhost:8080 posted 1 attachment: \"hello world! #welcome ! first post on the instance :rainbow: !\"",
|
||||
"image": "http://localhost:8080/fileserver/01F8MH17FWEB39HZJ76B6VXSKF/attachment/original/01F8MH6NEM8D7527KZAECTCR76.jpg",
|
||||
"date_published": "2021-10-20T11:36:45Z",
|
||||
"author": {
|
||||
"name": "@admin@localhost:8080"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "@admin@localhost:8080"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountRSSZork() {
|
||||
getFeed, lastModified, err := suite.accountProcessor.GetRSSFeedForUsername(suite.T().Context(), "the_mighty_zork")
|
||||
suite.NoError(err)
|
||||
suite.EqualValues(1730451600, lastModified.Unix())
|
||||
|
||||
feed, err := getFeed()
|
||||
suite.NoError(err)
|
||||
suite.Equal(`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
suite.testGetFeedSerializedAs("the_mighty_zork", &paging.Page{Limit: 20}, (*feeds.Feed).ToRss, 1730451600,
|
||||
`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<title>Posts from @the_mighty_zork@localhost:8080</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork</link>
|
||||
|
|
@ -151,7 +226,154 @@ func (suite *GetRSSTestSuite) TestGetAccountRSSZork() {
|
|||
<source>http://localhost:8080/@the_mighty_zork/feed.rss</source>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>`, feed)
|
||||
</rss>`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountAtomZork() {
|
||||
suite.testGetFeedSerializedAs("the_mighty_zork", &paging.Page{Limit: 20}, (*feeds.Feed).ToRss, 1730451600,
|
||||
`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<title>Posts from @the_mighty_zork@localhost:8080</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork</link>
|
||||
<description>Posts from @the_mighty_zork@localhost:8080</description>
|
||||
<pubDate>Fri, 01 Nov 2024 09:00:00 +0000</pubDate>
|
||||
<lastBuildDate>Fri, 01 Nov 2024 09:00:00 +0000</lastBuildDate>
|
||||
<image>
|
||||
<url>http://localhost:8080/fileserver/01F8MH1H7YV1Z7D2C8K2730QBF/avatar/small/01F8MH58A357CV5K7R7TJMSH6S.webp</url>
|
||||
<title>Avatar for @the_mighty_zork@localhost:8080</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork</link>
|
||||
</image>
|
||||
<item>
|
||||
<title>edited status</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork/statuses/01JDPZC707CKDN8N4QVWM4Z1NR</link>
|
||||
<description>@the_mighty_zork@localhost:8080 made a new post: "this is the latest revision of the status, with a content-warning"</description>
|
||||
<content:encoded><![CDATA[<p>this is the latest revision of the status, with a content-warning</p>]]></content:encoded>
|
||||
<author>@the_mighty_zork@localhost:8080</author>
|
||||
<guid isPermaLink="true">http://localhost:8080/@the_mighty_zork/statuses/01JDPZC707CKDN8N4QVWM4Z1NR</guid>
|
||||
<pubDate>Fri, 01 Nov 2024 09:00:00 +0000</pubDate>
|
||||
<source>http://localhost:8080/@the_mighty_zork/feed.rss</source>
|
||||
</item>
|
||||
<item>
|
||||
<title>HTML in post</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork/statuses/01HH9KYNQPA416TNJ53NSATP40</link>
|
||||
<description>@the_mighty_zork@localhost:8080 made a new post: "Here's a bunch of HTML, read it and weep, weep then!

`+"```"+`html
<section class="about-user">
 <div class="col-header">
 <h2>About</h2>
 </div> 
 <div class="fields">
 <h3 class="sr-only">Fields</h3>
 <dl>
...</description>
|
||||
<content:encoded><![CDATA[<p>Here's a bunch of HTML, read it and weep, weep then!</p><pre><code class="language-html"><section class="about-user">
|
||||
<div class="col-header">
|
||||
<h2>About</h2>
|
||||
</div>
|
||||
<div class="fields">
|
||||
<h3 class="sr-only">Fields</h3>
|
||||
<dl>
|
||||
<div class="field">
|
||||
<dt>should you follow me?</dt>
|
||||
<dd>maybe!</dd>
|
||||
</div>
|
||||
<div class="field">
|
||||
<dt>age</dt>
|
||||
<dd>120</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
<div class="bio">
|
||||
<h3 class="sr-only">Bio</h3>
|
||||
<p>i post about things that concern me</p>
|
||||
</div>
|
||||
<div class="sr-only" role="group">
|
||||
<h3 class="sr-only">Stats</h3>
|
||||
<span>Joined in Jun, 2022.</span>
|
||||
<span>8 posts.</span>
|
||||
<span>Followed by 1.</span>
|
||||
<span>Following 1.</span>
|
||||
</div>
|
||||
<div class="accountstats" aria-hidden="true">
|
||||
<b>Joined</b><time datetime="2022-06-04T13:12:00.000Z">Jun, 2022</time>
|
||||
<b>Posts</b><span>8</span>
|
||||
<b>Followed by</b><span>1</span>
|
||||
<b>Following</b><span>1</span>
|
||||
</div>
|
||||
</section>
|
||||
</code></pre><p>There, hope you liked that!</p>]]></content:encoded>
|
||||
<author>@the_mighty_zork@localhost:8080</author>
|
||||
<guid isPermaLink="true">http://localhost:8080/@the_mighty_zork/statuses/01HH9KYNQPA416TNJ53NSATP40</guid>
|
||||
<pubDate>Sun, 10 Dec 2023 09:24:00 +0000</pubDate>
|
||||
<source>http://localhost:8080/@the_mighty_zork/feed.rss</source>
|
||||
</item>
|
||||
<item>
|
||||
<title>introduction post</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork/statuses/01F8MHAMCHF6Y650WCRSCP4WMY</link>
|
||||
<description>@the_mighty_zork@localhost:8080 made a new post: "hello everyone!"</description>
|
||||
<content:encoded><![CDATA[<p>hello everyone!</p>]]></content:encoded>
|
||||
<author>@the_mighty_zork@localhost:8080</author>
|
||||
<guid isPermaLink="true">http://localhost:8080/@the_mighty_zork/statuses/01F8MHAMCHF6Y650WCRSCP4WMY</guid>
|
||||
<pubDate>Wed, 20 Oct 2021 10:40:37 +0000</pubDate>
|
||||
<source>http://localhost:8080/@the_mighty_zork/feed.rss</source>
|
||||
</item>
|
||||
</channel>
|
||||
</rss>`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountJSONZork() {
|
||||
suite.testGetFeedSerializedAs("the_mighty_zork", &paging.Page{Limit: 20}, (*feeds.Feed).ToJSON, 1730451600,
|
||||
`{
|
||||
"version": "https://jsonfeed.org/version/1.1",
|
||||
"title": "Posts from @the_mighty_zork@localhost:8080",
|
||||
"home_page_url": "http://localhost:8080/@the_mighty_zork",
|
||||
"description": "Posts from @the_mighty_zork@localhost:8080",
|
||||
"items": [
|
||||
{
|
||||
"id": "http://localhost:8080/@the_mighty_zork/statuses/01JDPZC707CKDN8N4QVWM4Z1NR",
|
||||
"url": "http://localhost:8080/@the_mighty_zork/statuses/01JDPZC707CKDN8N4QVWM4Z1NR",
|
||||
"external_url": "http://localhost:8080/@the_mighty_zork/feed.rss",
|
||||
"title": "edited status",
|
||||
"content_html": "\u003cp\u003ethis is the latest revision of the status, with a content-warning\u003c/p\u003e",
|
||||
"summary": "@the_mighty_zork@localhost:8080 made a new post: \"this is the latest revision of the status, with a content-warning\"",
|
||||
"date_published": "2024-11-01T09:00:00Z",
|
||||
"date_modified": "2024-11-01T09:02:00Z",
|
||||
"author": {
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "http://localhost:8080/@the_mighty_zork/statuses/01HH9KYNQPA416TNJ53NSATP40",
|
||||
"url": "http://localhost:8080/@the_mighty_zork/statuses/01HH9KYNQPA416TNJ53NSATP40",
|
||||
"external_url": "http://localhost:8080/@the_mighty_zork/feed.rss",
|
||||
"title": "HTML in post",
|
||||
"content_html": "\u003cp\u003eHere's a bunch of HTML, read it and weep, weep then!\u003c/p\u003e\u003cpre\u003e\u003ccode class=\"language-html\"\u003e\u0026lt;section class=\u0026#34;about-user\u0026#34;\u0026gt;\n \u0026lt;div class=\u0026#34;col-header\u0026#34;\u0026gt;\n \u0026lt;h2\u0026gt;About\u0026lt;/h2\u0026gt;\n \u0026lt;/div\u0026gt; \n \u0026lt;div class=\u0026#34;fields\u0026#34;\u0026gt;\n \u0026lt;h3 class=\u0026#34;sr-only\u0026#34;\u0026gt;Fields\u0026lt;/h3\u0026gt;\n \u0026lt;dl\u0026gt;\n \u0026lt;div class=\u0026#34;field\u0026#34;\u0026gt;\n \u0026lt;dt\u0026gt;should you follow me?\u0026lt;/dt\u0026gt;\n \u0026lt;dd\u0026gt;maybe!\u0026lt;/dd\u0026gt;\n \u0026lt;/div\u0026gt;\n \u0026lt;div class=\u0026#34;field\u0026#34;\u0026gt;\n \u0026lt;dt\u0026gt;age\u0026lt;/dt\u0026gt;\n \u0026lt;dd\u0026gt;120\u0026lt;/dd\u0026gt;\n \u0026lt;/div\u0026gt;\n \u0026lt;/dl\u0026gt;\n \u0026lt;/div\u0026gt;\n \u0026lt;div class=\u0026#34;bio\u0026#34;\u0026gt;\n \u0026lt;h3 class=\u0026#34;sr-only\u0026#34;\u0026gt;Bio\u0026lt;/h3\u0026gt;\n \u0026lt;p\u0026gt;i post about things that concern me\u0026lt;/p\u0026gt;\n \u0026lt;/div\u0026gt;\n \u0026lt;div class=\u0026#34;sr-only\u0026#34; role=\u0026#34;group\u0026#34;\u0026gt;\n \u0026lt;h3 class=\u0026#34;sr-only\u0026#34;\u0026gt;Stats\u0026lt;/h3\u0026gt;\n \u0026lt;span\u0026gt;Joined in Jun, 2022.\u0026lt;/span\u0026gt;\n \u0026lt;span\u0026gt;8 posts.\u0026lt;/span\u0026gt;\n \u0026lt;span\u0026gt;Followed by 1.\u0026lt;/span\u0026gt;\n \u0026lt;span\u0026gt;Following 1.\u0026lt;/span\u0026gt;\n \u0026lt;/div\u0026gt;\n \u0026lt;div class=\u0026#34;accountstats\u0026#34; aria-hidden=\u0026#34;true\u0026#34;\u0026gt;\n \u0026lt;b\u0026gt;Joined\u0026lt;/b\u0026gt;\u0026lt;time datetime=\u0026#34;2022-06-04T13:12:00.000Z\u0026#34;\u0026gt;Jun, 2022\u0026lt;/time\u0026gt;\n \u0026lt;b\u0026gt;Posts\u0026lt;/b\u0026gt;\u0026lt;span\u0026gt;8\u0026lt;/span\u0026gt;\n \u0026lt;b\u0026gt;Followed by\u0026lt;/b\u0026gt;\u0026lt;span\u0026gt;1\u0026lt;/span\u0026gt;\n \u0026lt;b\u0026gt;Following\u0026lt;/b\u0026gt;\u0026lt;span\u0026gt;1\u0026lt;/span\u0026gt;\n \u0026lt;/div\u0026gt;\n\u0026lt;/section\u0026gt;\n\u003c/code\u003e\u003c/pre\u003e\u003cp\u003eThere, hope you liked that!\u003c/p\u003e",
|
||||
"summary": "@the_mighty_zork@localhost:8080 made a new post: \"Here's a bunch of HTML, read it and weep, weep then!\n\n`+"```"+`html\n\u003csection class=\"about-user\"\u003e\n \u003cdiv class=\"col-header\"\u003e\n \u003ch2\u003eAbout\u003c/h2\u003e\n \u003c/div\u003e \n \u003cdiv class=\"fields\"\u003e\n \u003ch3 class=\"sr-only\"\u003eFields\u003c/h3\u003e\n \u003cdl\u003e\n...",
|
||||
"date_published": "2023-12-10T09:24:00Z",
|
||||
"author": {
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "http://localhost:8080/@the_mighty_zork/statuses/01F8MHAMCHF6Y650WCRSCP4WMY",
|
||||
"url": "http://localhost:8080/@the_mighty_zork/statuses/01F8MHAMCHF6Y650WCRSCP4WMY",
|
||||
"external_url": "http://localhost:8080/@the_mighty_zork/feed.rss",
|
||||
"title": "introduction post",
|
||||
"content_html": "\u003cp\u003ehello everyone!\u003c/p\u003e",
|
||||
"summary": "@the_mighty_zork@localhost:8080 made a new post: \"hello everyone!\"",
|
||||
"date_published": "2021-10-20T10:40:37Z",
|
||||
"author": {
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
},
|
||||
"authors": [
|
||||
{
|
||||
"name": "@the_mighty_zork@localhost:8080"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}`)
|
||||
}
|
||||
|
||||
func (suite *GetRSSTestSuite) TestGetAccountRSSZorkNoPosts() {
|
||||
|
|
@ -170,13 +392,10 @@ func (suite *GetRSSTestSuite) TestGetAccountRSSZorkNoPosts() {
|
|||
}
|
||||
}
|
||||
|
||||
getFeed, lastModified, err := suite.accountProcessor.GetRSSFeedForUsername(ctx, "the_mighty_zork")
|
||||
suite.NoError(err)
|
||||
suite.Empty(lastModified)
|
||||
var zeroTime time.Time
|
||||
|
||||
feed, err := getFeed()
|
||||
suite.NoError(err)
|
||||
suite.Equal(`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
suite.testGetFeedSerializedAs("the_mighty_zork", &paging.Page{Limit: 20}, (*feeds.Feed).ToRss, zeroTime.Unix(),
|
||||
`<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
|
||||
<channel>
|
||||
<title>Posts from @the_mighty_zork@localhost:8080</title>
|
||||
<link>http://localhost:8080/@the_mighty_zork</link>
|
||||
|
|
@ -189,7 +408,33 @@ func (suite *GetRSSTestSuite) TestGetAccountRSSZorkNoPosts() {
|
|||
<link>http://localhost:8080/@the_mighty_zork</link>
|
||||
</image>
|
||||
</channel>
|
||||
</rss>`, feed)
|
||||
</rss>`)
|
||||
}
|
||||
|
||||
// func (suite *GetRSSTestSuite) testGetAccountRSSPaging(username string, page *paging.Page, expectIDs []string) {
|
||||
// ctx := suite.T().Context()
|
||||
|
||||
// getFeed, _, errWithCode := suite.accountProcessor.GetRSSFeedForUsername(ctx, username, page)
|
||||
// suite.NoError(errWithCode)
|
||||
|
||||
// feed, errWithCode := getFeed()
|
||||
// suite.NoError(errWithCode)
|
||||
|
||||
// }
|
||||
|
||||
func (suite *GetRSSTestSuite) testGetFeedSerializedAs(username string, page *paging.Page, serialize func(*feeds.Feed) (string, error), expectLastMod int64, expectSerialized string) {
|
||||
ctx := suite.T().Context()
|
||||
|
||||
getFeed, lastMod, errWithCode := suite.accountProcessor.GetRSSFeedForUsername(ctx, username, page)
|
||||
suite.NoError(errWithCode)
|
||||
suite.Equal(expectLastMod, lastMod.Unix())
|
||||
|
||||
feed, errWithCode := getFeed()
|
||||
suite.NoError(errWithCode)
|
||||
|
||||
feedStr, err := serialize(feed)
|
||||
suite.NoError(err)
|
||||
suite.Equal(expectSerialized, feedStr)
|
||||
}
|
||||
|
||||
func TestGetRSSTestSuite(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import (
|
|||
"code.superseriousbusiness.org/gotosocial/internal/gtserror"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/gtsmodel"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/log"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/paging"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/util"
|
||||
)
|
||||
|
||||
|
|
@ -156,9 +157,8 @@ func (p *Processor) StatusesGet(
|
|||
func (p *Processor) WebStatusesGet(
|
||||
ctx context.Context,
|
||||
targetAccountID string,
|
||||
page *paging.Page,
|
||||
mediaOnly bool,
|
||||
limit int,
|
||||
maxID string,
|
||||
) (*apimodel.PageableResponse, gtserror.WithCode) {
|
||||
account, err := p.state.DB.GetAccountByID(ctx, targetAccountID)
|
||||
if err != nil {
|
||||
|
|
@ -174,14 +174,13 @@ func (p *Processor) WebStatusesGet(
|
|||
return nil, gtserror.NewErrorNotFound(err)
|
||||
}
|
||||
|
||||
statuses, err := p.state.DB.GetAccountWebStatuses(
|
||||
ctx,
|
||||
statuses, err := p.state.DB.GetAccountWebStatuses(ctx,
|
||||
account,
|
||||
page,
|
||||
mediaOnly,
|
||||
limit,
|
||||
maxID,
|
||||
)
|
||||
if err != nil && !errors.Is(err, db.ErrNoEntries) {
|
||||
err := gtserror.Newf("db error getting statuses: %w", err)
|
||||
return nil, gtserror.NewErrorInternalError(err)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -82,7 +82,7 @@ func getAssetETag(
|
|||
return cachedETag.eTag, nil
|
||||
}
|
||||
|
||||
eTag, err := generateEtag(file)
|
||||
eTag, err := generateETag(file)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error generating etag: %s", err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import (
|
|||
"code.superseriousbusiness.org/gotosocial/internal/log"
|
||||
|
||||
"codeberg.org/gruf/go-cache/v3"
|
||||
"codeberg.org/gruf/go-fastcopy"
|
||||
)
|
||||
|
||||
type withETagCache interface {
|
||||
|
|
@ -47,13 +48,19 @@ type eTagCacheEntry struct {
|
|||
lastModified time.Time
|
||||
}
|
||||
|
||||
// generateEtag generates a strong (byte-for-byte) etag using
|
||||
// the entirety of the provided reader.
|
||||
func generateEtag(r io.Reader) (string, error) {
|
||||
// nolint:gosec
|
||||
hash := sha1.New()
|
||||
// generateEtag generates a strong (byte-for-byte) etag
|
||||
// using the entirety of the provided reader.
|
||||
func generateETag(r io.Reader) (string, error) {
|
||||
return generateETagFrom(func(w io.Writer) error {
|
||||
_, err := fastcopy.Copy(w, r)
|
||||
return err
|
||||
})
|
||||
}
|
||||
|
||||
if _, err := io.Copy(hash, r); err != nil {
|
||||
func generateETagFrom(writeTo func(io.Writer) error) (string, error) {
|
||||
hash := sha1.New() // nolint:gosec
|
||||
|
||||
if err := writeTo(hash); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ import (
|
|||
apiutil "code.superseriousbusiness.org/gotosocial/internal/api/util"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/gtserror"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/log"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/paging"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
|
|
@ -122,14 +123,15 @@ func (m *Module) prepareProfile(c *gin.Context) *profile {
|
|||
|
||||
// Check if paging.
|
||||
maxStatusID := apiutil.ParseMaxID(c.Query(apiutil.MaxIDKey), "")
|
||||
paging := maxStatusID != ""
|
||||
doPaging := (maxStatusID != "")
|
||||
|
||||
// If not paging, load pinned statuses.
|
||||
var (
|
||||
mediaOnly = account.WebLayout == "gallery"
|
||||
pinnedStatuses []*apimodel.WebStatus
|
||||
)
|
||||
if !paging {
|
||||
|
||||
if !doPaging {
|
||||
// If not paging, load pinned statuses.
|
||||
var errWithCode gtserror.WithCode
|
||||
pinnedStatuses, errWithCode = m.processor.Account().WebStatusesGetPinned(
|
||||
ctx,
|
||||
|
|
@ -156,9 +158,8 @@ func (m *Module) prepareProfile(c *gin.Context) *profile {
|
|||
statusResp, errWithCode := m.processor.Account().WebStatusesGet(
|
||||
ctx,
|
||||
account.ID,
|
||||
&paging.Page{Max: paging.MaxID(maxStatusID), Limit: limit},
|
||||
mediaOnly,
|
||||
limit,
|
||||
maxStatusID,
|
||||
)
|
||||
if errWithCode != nil {
|
||||
apiutil.WebErrorHandler(c, errWithCode, instanceGet)
|
||||
|
|
@ -172,7 +173,7 @@ func (m *Module) prepareProfile(c *gin.Context) *profile {
|
|||
robotsMeta: robotsMeta,
|
||||
pinnedStatuses: pinnedStatuses,
|
||||
statusResp: statusResp,
|
||||
paging: paging,
|
||||
paging: doPaging,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,6 @@
|
|||
package web
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
|
@ -26,13 +25,26 @@ import (
|
|||
apiutil "code.superseriousbusiness.org/gotosocial/internal/api/util"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/gtserror"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/log"
|
||||
"code.superseriousbusiness.org/gotosocial/internal/paging"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/feeds"
|
||||
)
|
||||
|
||||
const appRSSUTF8 = string(apiutil.AppRSSXML) + "; charset=utf-8"
|
||||
const (
|
||||
charsetUTF8 = "; charset=utf-8"
|
||||
appRSSUTF8 = string(apiutil.AppRSSXML) + charsetUTF8
|
||||
appAtomUTF8 = string(apiutil.AppAtomXML) + charsetUTF8
|
||||
appJSONUTF8 = string(apiutil.AppFeedJSON) + charsetUTF8
|
||||
)
|
||||
|
||||
func (m *Module) rssFeedGETHandler(c *gin.Context) {
|
||||
if _, err := apiutil.NegotiateAccept(c, apiutil.AppRSSXML); err != nil {
|
||||
contentType, err := apiutil.NegotiateAccept(c,
|
||||
apiutil.AppRSSXML,
|
||||
apiutil.AppAtomXML,
|
||||
apiutil.AppFeedJSON,
|
||||
apiutil.AppJSON,
|
||||
)
|
||||
if err != nil {
|
||||
apiutil.WebErrorHandler(c, gtserror.NewErrorNotAcceptable(err, err.Error()), m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
|
|
@ -49,21 +61,34 @@ func (m *Module) rssFeedGETHandler(c *gin.Context) {
|
|||
// todo: https://codeberg.org/superseriousbusiness/gotosocial/issues/1813
|
||||
username = strings.ToLower(username)
|
||||
|
||||
// Retrieve the getRSSFeed function from the processor.
|
||||
// We'll only call the function if we need to, to save db calls.
|
||||
// lastPostAt may be a zero time if account has never posted.
|
||||
getRSSFeed, lastPostAt, errWithCode := m.processor.Account().GetRSSFeedForUsername(c.Request.Context(), username)
|
||||
// Parse paging parameters from request.
|
||||
page, errWithCode := paging.ParseIDPage(c,
|
||||
1, // min limit
|
||||
40, // max limit
|
||||
20, // default limit
|
||||
)
|
||||
if errWithCode != nil {
|
||||
apiutil.ErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
|
||||
getFunc, lastPostAt, errWithCode := m.processor.Account().GetRSSFeedForUsername(
|
||||
c.Request.Context(),
|
||||
username,
|
||||
page,
|
||||
)
|
||||
if errWithCode != nil {
|
||||
apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
rssFeed string // Stringified rss feed.
|
||||
var feed *feeds.Feed
|
||||
|
||||
cacheKey = c.Request.URL.Path
|
||||
cacheEntry, wasCached = m.eTagCache.Get(cacheKey)
|
||||
)
|
||||
// Key to use in etag cache (note content-type suffix).
|
||||
cacheKey := c.Request.URL.Path + "#" + contentType
|
||||
|
||||
// Check etag cache for an existing entry under key.
|
||||
cacheEntry, wasCached := m.eTagCache.Get(cacheKey)
|
||||
|
||||
if !wasCached || unixAfter(lastPostAt, cacheEntry.lastModified) {
|
||||
// We either have no ETag cache entry for this account's feed,
|
||||
|
|
@ -72,15 +97,16 @@ func (m *Module) rssFeedGETHandler(c *gin.Context) {
|
|||
//
|
||||
// As such, we need to generate a new ETag, and for that we need
|
||||
// the string representation of the RSS feed.
|
||||
rssFeed, errWithCode = getRSSFeed()
|
||||
feed, errWithCode = getFunc()
|
||||
if errWithCode != nil {
|
||||
apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
|
||||
eTag, err := generateEtag(bytes.NewBufferString(rssFeed))
|
||||
etag, err := generateFeedETag(feed, contentType)
|
||||
if err != nil {
|
||||
apiutil.WebErrorHandler(c, gtserror.NewErrorInternalError(err), m.processor.InstanceGetV1)
|
||||
errWithCode := gtserror.NewErrorInternalError(err)
|
||||
apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -96,7 +122,7 @@ func (m *Module) rssFeedGETHandler(c *gin.Context) {
|
|||
|
||||
// Store the new cache entry.
|
||||
cacheEntry = eTagCacheEntry{
|
||||
eTag: eTag,
|
||||
eTag: etag,
|
||||
lastModified: lastModified,
|
||||
}
|
||||
m.eTagCache.Set(cacheKey, cacheEntry)
|
||||
|
|
@ -149,15 +175,37 @@ func (m *Module) rssFeedGETHandler(c *gin.Context) {
|
|||
// If we had a cache hit earlier, we may not have called the
|
||||
// getRSSFeed function yet; if that's the case then do call it
|
||||
// now because we definitely need it.
|
||||
if rssFeed == "" {
|
||||
rssFeed, errWithCode = getRSSFeed()
|
||||
if feed == nil {
|
||||
feed, errWithCode = getFunc()
|
||||
if errWithCode != nil {
|
||||
apiutil.WebErrorHandler(c, errWithCode, m.processor.InstanceGetV1)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, appRSSUTF8, []byte(rssFeed))
|
||||
// Encode response.
|
||||
switch contentType {
|
||||
case apiutil.AppRSSXML:
|
||||
apiutil.XMLType(c, http.StatusOK, appRSSUTF8, &feeds.Rss{feed})
|
||||
case apiutil.AppAtomXML:
|
||||
apiutil.XMLType(c, http.StatusOK, appAtomUTF8, &feeds.Atom{feed})
|
||||
case apiutil.AppFeedJSON, apiutil.AppJSON:
|
||||
apiutil.JSONType(c, http.StatusOK, appJSONUTF8, (&feeds.JSON{feed}).JSONFeed())
|
||||
}
|
||||
}
|
||||
|
||||
// generateFeedETag generates feed etag for appropriate content-type encoding.
|
||||
func generateFeedETag(feed *feeds.Feed, contentType string) (string, error) {
|
||||
switch contentType {
|
||||
case apiutil.AppRSSXML:
|
||||
return generateETagFrom(feed.WriteRss)
|
||||
case apiutil.AppAtomXML:
|
||||
return generateETagFrom(feed.WriteAtom)
|
||||
case apiutil.AppFeedJSON, apiutil.AppJSON:
|
||||
return generateETagFrom(feed.WriteJSON)
|
||||
default:
|
||||
panic("unreachable")
|
||||
}
|
||||
}
|
||||
|
||||
// unixAfter returns true if the unix value of t1
|
||||
|
|
|
|||
|
|
@ -113,7 +113,7 @@ nav:
|
|||
- "configuration/syslog.md"
|
||||
- "configuration/httpclient.md"
|
||||
- "configuration/advanced.md"
|
||||
- "configuration/observability.md"
|
||||
- "configuration/observability_and_metrics.md"
|
||||
- "Advanced":
|
||||
- "Overview": "advanced/index.md"
|
||||
- "advanced/host-account-domain.md"
|
||||
|
|
|
|||
9
vendor/codeberg.org/gruf/go-bitutil/LICENSE
generated
vendored
9
vendor/codeberg.org/gruf/go-bitutil/LICENSE
generated
vendored
|
|
@ -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.
|
||||
3
vendor/codeberg.org/gruf/go-bitutil/README.md
generated
vendored
3
vendor/codeberg.org/gruf/go-bitutil/README.md
generated
vendored
|
|
@ -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.
|
||||
29
vendor/codeberg.org/gruf/go-bitutil/abs.go
generated
vendored
29
vendor/codeberg.org/gruf/go-bitutil/abs.go
generated
vendored
|
|
@ -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)
|
||||
}
|
||||
3744
vendor/codeberg.org/gruf/go-bitutil/flag.go
generated
vendored
3744
vendor/codeberg.org/gruf/go-bitutil/flag.go
generated
vendored
File diff suppressed because it is too large
Load diff
117
vendor/codeberg.org/gruf/go-bitutil/flag.tpl
generated
vendored
117
vendor/codeberg.org/gruf/go-bitutil/flag.tpl
generated
vendored
|
|
@ -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"
|
||||
}
|
||||
98
vendor/codeberg.org/gruf/go-bitutil/flag_test.tpl
generated
vendored
98
vendor/codeberg.org/gruf/go-bitutil/flag_test.tpl
generated
vendored
|
|
@ -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 }}
|
||||
85
vendor/codeberg.org/gruf/go-bitutil/pack.go
generated
vendored
85
vendor/codeberg.org/gruf/go-bitutil/pack.go
generated
vendored
|
|
@ -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)
|
||||
}
|
||||
60
vendor/codeberg.org/gruf/go-bitutil/test.tpl
generated
vendored
60
vendor/codeberg.org/gruf/go-bitutil/test.tpl
generated
vendored
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
201
vendor/github.com/technologize/otel-go-contrib/LICENSE
generated
vendored
201
vendor/github.com/technologize/otel-go-contrib/LICENSE
generated
vendored
|
|
@ -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.
|
||||
45
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/config.go
generated
vendored
45
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/config.go
generated
vendored
|
|
@ -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
|
||||
}
|
||||
94
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/middleware.go
generated
vendored
94
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/middleware.go
generated
vendored
|
|
@ -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)
|
||||
}
|
||||
74
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/option.go
generated
vendored
74
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/option.go
generated
vendored
|
|
@ -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
|
||||
})
|
||||
}
|
||||
70
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/otelrecorder.go
generated
vendored
70
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/otelrecorder.go
generated
vendored
|
|
@ -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...))
|
||||
}
|
||||
25
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/recorder.go
generated
vendored
25
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/recorder.go
generated
vendored
|
|
@ -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)
|
||||
}
|
||||
11
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/version.go
generated
vendored
11
vendor/github.com/technologize/otel-go-contrib/otelginmetrics/version.go
generated
vendored
|
|
@ -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
6
vendor/modules.txt
vendored
|
|
@ -221,9 +221,6 @@ code.superseriousbusiness.org/oauth2/v4/generates
|
|||
code.superseriousbusiness.org/oauth2/v4/manage
|
||||
code.superseriousbusiness.org/oauth2/v4/models
|
||||
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
|
||||
## explicit; go 1.17
|
||||
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/html
|
||||
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
|
||||
## explicit; go 1.11
|
||||
github.com/temoto/robotstxt
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue