Skip to content

The only tool you need to know what is happening and how to fix it.

fix: consistent middleware.RejectBindError usage + minor bugs

narrow-adventure95a65d245261
diff --git a/.github/workflows/backend-vulncheck.yml b/.github/workflows/backend-vulncheck.yml
index dc7defad..f3a45575 100644
--- a/.github/workflows/backend-vulncheck.yml
+++ b/.github/workflows/backend-vulncheck.yml
@@ -69,9 +69,9 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
- # setup-go@v5 honors the `toolchain` directive in go.mod, so this installs
- # go1.26.6 -- the same version release-traceway.yml builds the runner
- # with. The Docker images are not covered by that: the official golang
+ # setup-go@v5 reads the `go` line of go.mod; Go's own GOTOOLCHAIN=auto
+ # then downloads the `toolchain` version, so the scan runs on the same
+ # release release-traceway.yml builds the runner with. The Docker images are not covered by that: the official golang
# bases set GOTOOLCHAIN=local, so they build with whatever the floating
# golang:1.26-* tag ships, which is >= what is scanned here. One setup-go
# cache shared by the three rows is fine here, unlike backend.yml: with
diff --git a/.github/workflows/cli.yml b/.github/workflows/cli.yml
index 80cc6a67..a515c5e1 100644
--- a/.github/workflows/cli.yml
+++ b/.github/workflows/cli.yml
@@ -35,9 +35,7 @@ jobs:
uses: actions/setup-go@v5
with:
go-version-file: cli/go.mod
- cache-dependency-path: |
- cli/go.sum
- cli/test/contract/go.sum
+ cache-dependency-path: cli/go.sum
- name: Build
run: go build ./...
@@ -45,10 +43,6 @@ jobs:
- name: Test
run: go test ./...
- - name: Contract tests
- run: go test ./...
- working-directory: cli/test/contract
-
- name: Skill drift check
run: |
go run ./tools/skillgen
diff --git a/.gitignore b/.gitignore
index 67d51988..21641f10 100644
--- a/.gitignore
+++ b/.gitignore
@@ -45,6 +45,7 @@ backend/static/dist/
/backend/storage/recordings
/backend/storage
/docs/.wrangler
+/examples/devtesting-embedded/devtesting-embedded
/examples/devtesting-embedded/frontend/node_modules
/examples/devtesting-embedded/storage
/examples/express-otel/node_modules
diff --git a/CLAUDE.md b/CLAUDE.md
index 7bc2308f..25574974 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -35,9 +35,9 @@ Traceway is an error tracking and monitoring platform consisting of:
| CLI | `cd cli && just smoke-test` | Live E2E (needs `TRACEWAY_SMOKE_*` env vars) |
| Any | `nix develop` (or direnv via `.envrc`) | Dev shell with the Go and Node versions read from `backend/go.mod` and `frontend/package.json`, plus `just`, `golangci-lint`, `govulncheck` (`flake.nix`; shells `default`, `backend`, `frontend`, `oxc`). Put `JWT_SECRET` in the gitignored `.envrc.local` |
-Set `JWT_SECRET` (min 32 characters) before running the backend — it is the one variable with no default. `SQLITE_PATH` sets the database location, defaulting to `./traceway.db` in the working directory.
+Set `JWT_SECRET` (min 32 characters) before running the backend — it is the one variable with no default in the standalone binary (the all-in-one Docker image bakes a public one in via `backend/.env.docker`, which must be overridden in production). `SQLITE_PATH` sets the database location, defaulting to `./traceway.db` in the working directory.
-CI on pull requests is opt-in. `backend.yml`, `backend-vulncheck.yml`, `cli.yml`, `cli-lint.yml` and `cli-contract.yml` listen for `pull_request: types: [labeled]` and every job is gated on `github.event.label.name == 'ci'`, so a PR runs nothing until a maintainer applies the `ci` label (only collaborators can), and applying any other label runs nothing either. Each application validates the PR as it is at that moment: to validate later pushes, remove and re-add the label. The same workflows still run on every push to `main`, on their daily schedules (the two vulnchecks), and from the Actions tab via `workflow_dispatch`.
+CI on pull requests is opt-in. `backend.yml`, `backend-vulncheck.yml`, `cli.yml`, `cli-lint.yml` and `cli-contract.yml` listen for `pull_request: types: [labeled]` and every job is gated on `github.event.label.name == 'ci'`, so a PR runs nothing until a maintainer applies the `ci` label (only collaborators can), and applying any other label runs nothing either. Each application validates the PR as it is at that moment: to validate later pushes, remove and re-add the label. The same workflows still run on pushes to `main` that touch their paths (`backend/**`, `cli/**`, their own workflow file), on their daily schedules (the two vulnchecks), and from the Actions tab via `workflow_dispatch`.
### Tech Stack
- **Frontend**: SvelteKit 2.49, Svelte 5.45, Tailwind CSS v4, shadcn-svelte, Vite 7
@@ -125,7 +125,7 @@ func (c *AuthController) Register(ctx *gin.Context) {
- Commits on status codes: 200, 201, 303
- Rolls back on all other status codes or panics
-**Body buffering:** `Transactional` reads the request body into memory (cap `maxTransactionalBodyBytes`, 8MB) before it calls `db.DB.Begin()`, answering 413/408/400 without a transaction when that fails; the handler's later bind is served from memory. This is what keeps a slow-drip body from holding the single SQLite main-DB connection, and it covers every transactional route without each one remembering a special middleware. Routes that want a tighter cap put `middleware.BufferAuthBody` (64KB) in front of `Transactional`, which then skips the body it finds already buffered; the anonymous auth endpoints do this. The self-transacting OAuth routes (`/auth/device/*`, `/auth/token`, `/auth/logout`) use `BufferAuthBody` on its own for the same cap. Every other bind failure that is really a body problem goes through `middleware.RejectBindError`, which maps `MaxBytesError` to 413 and the guard's deadline errors to 408 with fixed messages (the deadline error is a `*net.OpError` naming the listener address, so it is never echoed).
+**Body buffering:** `Transactional` reads the request body into memory (cap `maxTransactionalBodyBytes`, 8MB) before it calls `db.DB.Begin()`, answering 413/408/400 without a transaction when that fails; the handler's later bind is served from memory. This is what keeps a slow-drip body from holding the single SQLite main-DB connection, and it covers every transactional route without each one remembering a special middleware. Routes that want a tighter cap put `middleware.BufferAuthBody` (64KB) in front of `Transactional`, which then skips the body it finds already buffered; the anonymous auth endpoints do this. The self-transacting OAuth routes (`/auth/device/*`, `/auth/token`, `/auth/logout`) use `BufferAuthBody` on its own for the same cap. Every plain JSON bind site in the controllers answers through `middleware.RejectBindError(c, err, fallback)`, which maps `MaxBytesError` to 413 and the body guard's timeout to 408 with fixed messages and otherwise returns 400 with the fallback; the guard itself swaps the raw deadline error (a `*net.OpError` naming the listener address) for `middleware.ErrBodyTimedOut` before it leaves `Read`, so no handler can echo the address.
**Preference:** For CRUD controller methods, always prefer using `middleware.Transactional` in the route + `db.GetTx(ctx)` in the controller over `pgdb.ExecuteTransaction`. The middleware approach keeps controllers flat, avoids nested closures, and follows the established pattern. (The tx getter lives in the `db` package: `db.GetTx(ctx)`, not `middleware.GetTx`.)
@@ -248,12 +248,12 @@ if err != nil {
### Environment Variables (Backend)
```
-JWT_SECRET=<min 32 char secret for JWT signing> # the only variable with no default. There is deliberately no fallback: a key committed to the repo would be identical in every clone. Unset or under 32 chars exits 1 with an actionable message rather than a panic.
+JWT_SECRET=<min 32 char secret for JWT signing> # the only variable with no default in the standalone binary. There is deliberately no fallback in the code: a key committed to the repo would be identical in every clone. The all-in-one Docker image is the exception, it copies `backend/.env.docker` with a public key that must be overridden in production. Unset or under 32 chars exits 1 with an actionable message rather than a panic.
DB_TYPE= # sqlite | postgres. Defaults to sqlite in every build EXCEPT -tags transactional_pg, where an empty value still selects PostgreSQL. Without that tag SQLite is the only supported main DB (the migration runner applies SQLite-dialect migrations unconditionally), so the default is set once in config.defaultDBType rather than at each DBType call site.
PORTS=80,8082 # comma-separated HTTP listen ports. Every port is bound up front; a port that fails to bind (typically :80 as a non-root user) logs a warning (and reports via CaptureException when monitoring is configured), and startup only fails if NO port binds. Order is not significant: a listener that later stops serving takes the process down whichever position it holds.
SQLITE_PATH= # main DB path, defaults to ./traceway.db in the working directory. The telemetry DB derives from it (_telemetry.db, or _telemetry.duckdb under -tags telemetry_duckdb).
APP_BASE_URL= # public origin of this server (e.g. https://traceway.example.com). Used as the OAuth issuer / device verification URL and SSO redirect base. If unset, the device-auth + well-known endpoints derive it per-request from the Host / X-Forwarded-* headers; set it explicitly behind a proxy that doesn't forward Host.
-TRUSTED_PROXIES= # comma-separated IPs/CIDRs whose X-Forwarded-For/X-Real-IP gin trusts for c.ClientIP() (every per-IP rate limiter keys on it, and `/api/report` stores it on every session as `client.ip`). Unset = loopback only, so no peer can spoof its IP. Private ranges are deliberately NOT trusted by default: on a Docker/k8s network every peer has a private address, the clients included when the port is published directly, so trusting RFC1918 would let any of them forge XFF past every per-IP limiter. Set it to the CIDRs of whatever sits in front (a proxy container's compose network, the ingress pod range, the CDN ranges); otherwise every visitor shares one rate-limit bucket keyed on the proxy. The value REPLACES the default, so it must name every hop in the chain, not just the outermost (a CDN-only list leaves a private ingress untrusted and disables XFF entirely); `*` trusts every peer. A malformed entry panics at startup (`configureClientIP`, cmd/run.go). The first request carrying X-Forwarded-For/X-Real-IP from a peer outside the list logs a one-time warning naming that peer (`warnOnUntrustedForwardedFor`, cmd/run.go), which is how a forgotten proxy hop shows up. Parsing lives in `Cfg.TrustedProxyList` (config.go), covered by config_test.go.
+TRUSTED_PROXIES= # comma-separated IPs/CIDRs whose X-Forwarded-For/X-Real-IP gin trusts for c.ClientIP() (every per-IP rate limiter keys on it, and `/api/report` stores it on every session as `client.ip`). Unset = loopback only, so no peer can spoof its IP. Private ranges are deliberately NOT trusted by default: on a Docker/k8s network every peer has a private address, the clients included when the port is published directly, so trusting RFC1918 would let any of them forge XFF past every per-IP limiter. Set it to the CIDRs of whatever sits in front (a proxy container's compose network, the ingress pod range, the CDN ranges); otherwise every visitor shares one rate-limit bucket keyed on the proxy. The value REPLACES the default, so it must name every hop in the chain, not just the outermost (a CDN-only list leaves a private ingress untrusted and disables XFF entirely); `*` trusts every peer. A malformed entry exits 1 at startup with a FATAL message, before the database is opened (`trustedProxyNets`, cmd/run.go). The first request carrying X-Forwarded-For/X-Real-IP from a peer outside the list logs a one-time warning naming that peer (`warnOnUntrustedForwardedFor`, cmd/run.go), which is how a forgotten proxy hop shows up. Parsing lives in `Cfg.TrustedProxyList` (config.go), covered by config_test.go.
TRUSTED_PROXY_HEADER= # optional header taken verbatim as the client IP on every request (gin TrustedPlatform: X-Real-IP behind ingress-nginx, CF-Connecting-IP behind Cloudflare); it wins over TRUSTED_PROXIES and turns the untrusted-forwarder warning off. Only safe when every request provably passes through a proxy that overwrites the header.
UPLOAD_MAX_CONCURRENT=4 # concurrent /api/sourcemaps/upload + /api/symbols/upload requests; excess waits 30s then gets 503. Separate from INGEST_MAX_CONCURRENT so a CI upload burst cannot starve telemetry ingest. Each upload holds a whole file in memory while parsing, so this bounds peak upload memory at roughly concurrency x largest file. It is a count-based gate, not a memory budget: on a memory-capped container size it from the limit rather than trusting the default. Same gate and bounded waiting room as ingest, its own instance. The source-map warm-up that follows an upload (`services.GenerateTWArtifacts`) runs outside this gate on its own 2-worker pool with a 64-job queue: the stale `.tw` artifact is deleted and the cache invalidated inline, the rebuild is queued, identical pending jobs are coalesced, and a full queue drops the warm-up (rate-limited `CaptureException`) because lookups build a missing artifact on demand anyway.
REPORT_MAX_BODY_MB=64 # cap on the DECOMPRESSED /api/report and /api/profiles/ingest body (middleware.UseGzip bounds both the raw and gunzipped stream, so gzip cannot raise it). Deliberately far above the 10MB OTLP cap: session-replay frames carry rrweb segments and are a different size class, and the shipped browser SDKs re-queue a rejected batch forever, so a reachable cap is a permanent wedge rather than shed load. Overruns answer 413.
@@ -596,7 +596,7 @@ backend/
| Synthetic runner API | `UseRunnerAuth` only (shared SYNTHETICS_RUNNER_SECRET bearer + self-registration by X-Traceway-Runner-Name; no Transactional — poll holds the request up to 25s) |
| Public status page | `RateLimitPerIP` only |
-**Global middleware** (registered in `cmd/run.go` ahead of the routes): `middleware.GuardBodyReads` (every request body gets the progress guard, 30s idle / 10 min total / 1 KB/s floor after 20s, answering through `middleware.BodyReadError` as 408; routes with their own budget call `GuardBodyRead` again, which re-arms the same guard rather than wrapping twice, so uploads get 30s/30 min, `/api/report` 20s/5 min and OTLP 20s/2 min. The guard clears the socket read deadline the moment the body is complete: Go's background connection read would otherwise time out and cancel the request context of any handler that outlives the idle window. The `http.Server` `ReadTimeout` is a 1h backstop that only applies while a body is still arriving, `ReadHeaderTimeout` is 15s), `configureClientIP` (gin's trusted proxies from `Cfg.TrustedProxyList`, plus `TrustedPlatform` from `TRUSTED_PROXY_HEADER`; a malformed list panics), `warnOnUntrustedForwardedFor` (list mode only: one-time log when a forwarding header arrives from a peer outside `TRUSTED_PROXIES`), and `middleware.SecurityHeaders` (`X-Frame-Options: DENY`, CSP `frame-ancestors 'none'; base-uri 'self'; form-action 'self'`, `Referrer-Policy`, `nosniff`). The two frame headers are skipped for any `/status/*` or `/api/status/*` path so public status pages stay embeddable in an iframe. A status page served at the root of a custom domain is not exempt: the same root serves the logged-in dashboard on every hostname the backend answers on, so it must not be frameable there.
+**Global middleware** (registered in `cmd/run.go` ahead of the routes): `middleware.GuardBodyReads` (every request body gets the progress guard, 30s idle / 10 min total / 1 KB/s floor after 20s, answering through `middleware.BodyReadError` as 408; routes with their own budget call `GuardBodyRead` again, which re-arms the same guard rather than wrapping twice, so uploads get 30s/30 min, `/api/report` 20s/5 min and OTLP 20s/2 min. The guard clears the socket read deadline the moment the body is complete: Go's background connection read would otherwise time out and cancel the request context of any handler that outlives the idle window. The `http.Server` `ReadTimeout` is a 1h backstop that only applies while a body is still arriving (the guard lifts it for bodiless requests too, so a long-lived handler such as the MCP `GET /mcp` stream is not cancelled after an hour), `ReadHeaderTimeout` is 15s), `configureClientIP` (gin's trusted proxies from `Cfg.TrustedProxyList`, plus `TrustedPlatform` from `TRUSTED_PROXY_HEADER`; a malformed list panics), `warnOnUntrustedForwardedFor` (list mode only: one-time log when a forwarding header arrives from a peer outside `TRUSTED_PROXIES`), and `middleware.SecurityHeaders` (`X-Frame-Options: DENY`, CSP `frame-ancestors 'none'; base-uri 'self'; form-action 'self'`, `Referrer-Policy`, `nosniff`). The two frame headers are skipped for any `/status/*` or `/api/status/*` path so public status pages stay embeddable in an iframe. A status page served at the root of a custom domain is not exempt: the same root serves the logged-in dashboard on every hostname the backend answers on, so it must not be frameable there.
### API Endpoints
@@ -664,7 +664,7 @@ backend/
| GET | `/api/metrics/application` | App | Application metrics |
| GET | `/api/metrics/stats` | App | Stats metrics |
| GET | `/api/metrics/server` | App | Server metrics |
-| POST | `/api/metrics/query` | App | Custom metric queries. Bounded in `metric_query.controller.go`: 256KB body, max 50 queries and 20 tag filters each, range at most 731 days and `to > from` (422), buckets widened so no series exceeds 2000 points, at most 200 groups per query (the repositories return one extra so the result carries `truncatedGroups: true`), and a 30s deadline for the whole request that answers 504. The discovery endpoints validate their `from`/`to` the same way |
+| POST | `/api/metrics/query` | App | Custom metric queries. Bounded in `metric_query.controller.go`: 256KB body, max 50 queries and 20 tag filters each, range at most 731 days and `to > from` (422), buckets widened so no series exceeds 2000 points (the effective `intervalMinutes` is returned at the top level of the response), at most 200 groups per query (the repositories return one extra so the result carries `truncatedGroups: true`), and a 30s deadline for the whole request that answers 504. The discovery endpoints validate their `from`/`to` the same way |
| GET | `/api/metrics/discover` | App | Discover available metrics |
| GET | `/api/metrics/discover/tags` | App | Discover metric tags |
| GET | `/api/metrics/discover/instances` | App | Distinct `server_name` values in a range (dashboard instance filter) |
@@ -766,9 +766,9 @@ Org-wide read views that fan out over every project of the org, in `organization
| Method | Endpoint | Auth | Purpose |
|--------|----------|------|---------|
| GET | `/api/organizations/:organizationId/overview/servers` | Member | One row per `server_name` per project over the last 30 min: CPU/memory/disk/network + a CPU sparkline, plus host/os/cloud/k8s metadata lifted from metric tags. Reads OTel hostmetrics (`system.cpu.utilization` state=idle inverted, `system.memory.utilization` state=used, `system.filesystem.utilization` state=used, `system.network.io` by direction) and falls back to the legacy SDK names (`cpu.used_pcnt`, `mem.used`/`mem.total`). A project that fails to read sets `partial: true` instead of failing the request |
-| GET | `/api/organizations/:organizationId/overview/issues` | Member | Recently active issues across all projects, last 24h, max 50, plus the true `totalGroups` |
+| GET | `/api/organizations/:organizationId/overview/issues` | Member | Recently active issues across all projects, last 24h, max 50, plus the true `totalGroups`; a project that fails to read sets `partial: true` like the servers endpoint |
| GET | `/api/organizations/:organizationId/overview/pages` | Member | Active on-call pages across all projects + open-page and down-monitor counts |
-| GET | `/api/organizations/:organizationId/overview/monitors` | Member | Every synthetic check in the org with 30-day aggregates |
+| GET | `/api/organizations/:organizationId/overview/monitors` | Member | Every synthetic check in the org with 30-day aggregates; a project whose results fail to read sets `partial: true` like the servers endpoint |
Instance identity is the `server_name` tag, which comes from the OTLP `service.name` resource attribute; grouping by Kubernetes cluster keys off the `k8s.cluster.name` tag and the group selector only offers it when at least one instance carries one. Clicking a row opens `/dashboards?projectId=&server=&preset=30m` (plus `dashboard=` when the project has the `traceway-otel-agent` template applied); `server` scopes every widget query via `scopeTagFilters` in `widget-grid`/`widget-renderer`. Cluster-wide instrumentation manifests live in `examples/kubernetes/`, documented at `docs/pages/learn/kubernetes.mdx`.
diff --git a/backend/app/controllers/ai_trace.controller.go b/backend/app/controllers/ai_trace.controller.go
index 3f44d395..e6ec8e40 100644
--- a/backend/app/controllers/ai_trace.controller.go
+++ b/backend/app/controllers/ai_trace.controller.go
@@ -111,7 +111,7 @@ func (a aiTraceController) FindGroupedByTraceName(c *gin.Context) {
var request AiTraceSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -152,7 +152,7 @@ func (a aiTraceController) FindByTraceName(c *gin.Context) {
var request AiTraceInstancesRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -233,7 +233,7 @@ func (a aiTraceController) FindConversations(c *gin.Context) {
var request AiConversationSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -281,7 +281,7 @@ func (a aiTraceController) GetConversationDetail(c *gin.Context) {
var request AiConversationDetailRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ConversationId == "" {
@@ -347,7 +347,7 @@ func (a aiTraceController) FindAiUsers(c *gin.Context) {
var request AiUserSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.go
index 6e6dea6f..12a3c310 100644
--- a/backend/app/controllers/auth.controller.go
+++ b/backend/app/controllers/auth.controller.go
@@ -96,7 +96,7 @@ func (a authController) Register(c *gin.Context) {
var request models.RegisterRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(c, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/contact_method.controller.go b/backend/app/controllers/contact_method.controller.go
index 53fa7ccb..b7079ba8 100644
--- a/backend/app/controllers/contact_method.controller.go
+++ b/backend/app/controllers/contact_method.controller.go
@@ -154,7 +154,7 @@ func (c *contactMethodController) Create(ctx *gin.Context) {
var request contactMethodRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if smsUnavailable(request.MethodType) {
@@ -210,7 +210,7 @@ func (c *contactMethodController) Update(ctx *gin.Context) {
}
var request contactMethodRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if request.MethodType == "" {
@@ -280,7 +280,7 @@ func (c *contactMethodController) Verify(ctx *gin.Context) {
Code string `json:"code"`
}
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if method.Verified {
diff --git a/backend/app/controllers/dashboard_io.controller.go b/backend/app/controllers/dashboard_io.controller.go
index a0371fd4..321aeb4f 100644
--- a/backend/app/controllers/dashboard_io.controller.go
+++ b/backend/app/controllers/dashboard_io.controller.go
@@ -119,7 +119,7 @@ func (c *dashboardsController) Import(ctx *gin.Context) {
limitRequestBody(ctx)
var req ImportDashboardsRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if req.Mode == "" {
@@ -289,7 +289,7 @@ func (c *dashboardsController) ImportGrafana(ctx *gin.Context) {
limitRequestBody(ctx)
var req ImportGrafanaRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/dashboard_template.controller.go b/backend/app/controllers/dashboard_template.controller.go
index 4115e2d6..5cd83935 100644
--- a/backend/app/controllers/dashboard_template.controller.go
+++ b/backend/app/controllers/dashboard_template.controller.go
@@ -216,7 +216,7 @@ type InstallTemplateRequest struct {
func (c *dashboardTemplateController) Install(ctx *gin.Context) {
var req InstallTemplateRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/dashboard_widgets.controller.go b/backend/app/controllers/dashboard_widgets.controller.go
index d8ca4e45..2e02de63 100644
--- a/backend/app/controllers/dashboard_widgets.controller.go
+++ b/backend/app/controllers/dashboard_widgets.controller.go
@@ -28,7 +28,7 @@ func (c *dashboardsController) AddWidget(ctx *gin.Context) {
limitRequestBody(ctx)
var req AddWidgetRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -97,7 +97,7 @@ func (c *dashboardsController) UpdateWidget(ctx *gin.Context) {
limitRequestBody(ctx)
var req AddWidgetRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -191,7 +191,7 @@ type ReorderWidgetsRequest struct {
func (c *dashboardsController) ReorderWidgets(ctx *gin.Context) {
var req ReorderWidgetsRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -422,7 +422,7 @@ func (c *dashboardsController) ReorderStarred(ctx *gin.Context) {
var req ReorderStarredRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -488,7 +488,7 @@ func (c *dashboardsController) UpdateStarredLayout(ctx *gin.Context) {
var req UpdateStarredLayoutRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/dashboards.controller.go b/backend/app/controllers/dashboards.controller.go
index 2ddba543..842e4100 100644
--- a/backend/app/controllers/dashboards.controller.go
+++ b/backend/app/controllers/dashboards.controller.go
@@ -463,7 +463,7 @@ func (c *dashboardsController) Create(ctx *gin.Context) {
limitRequestBody(ctx)
var req CreateDashboardRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -615,7 +615,7 @@ func (c *dashboardsController) Update(ctx *gin.Context) {
limitRequestBody(ctx)
var req UpdateDashboardRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -749,7 +749,7 @@ type ApplyDashboardRequest struct {
func (c *dashboardsController) Apply(ctx *gin.Context) {
var req ApplyDashboardRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -847,7 +847,7 @@ type CopyDashboardRequest struct {
func (c *dashboardsController) Copy(ctx *gin.Context) {
var req CopyDashboardRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -934,7 +934,7 @@ func (c *dashboardsController) Reorder(ctx *gin.Context) {
var req ReorderDashboardsRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/endpoint.controller.go b/backend/app/controllers/endpoint.controller.go
index ae9c6bb7..737c5be9 100644
--- a/backend/app/controllers/endpoint.controller.go
+++ b/backend/app/controllers/endpoint.controller.go
@@ -77,7 +77,7 @@ func (e endpointController) FindAllEndpoints(c *gin.Context) {
var request EndpointSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -109,7 +109,7 @@ func (e endpointController) FindGroupedByEndpoint(c *gin.Context) {
var request EndpointSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -159,7 +159,7 @@ func (e endpointController) FindByEndpoint(c *gin.Context) {
var request EndpointInstancesRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -200,7 +200,7 @@ func (e endpointController) GetStackedChart(c *gin.Context) {
var request EndpointStackedChartRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -278,7 +278,7 @@ func (e endpointController) SetSlowEndpoint(c *gin.Context) {
var request SetSlowEndpointRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/escalation_policy.controller.go b/backend/app/controllers/escalation_policy.controller.go
index f35e449f..c51be11e 100644
--- a/backend/app/controllers/escalation_policy.controller.go
+++ b/backend/app/controllers/escalation_policy.controller.go
@@ -77,7 +77,7 @@ func (c *escalationPolicyController) Create(ctx *gin.Context) {
var request escalationPolicyRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
request.Name = strings.TrimSpace(request.Name)
@@ -133,7 +133,7 @@ func (c *escalationPolicyController) Update(ctx *gin.Context) {
}
var request escalationPolicyRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
request.Name = strings.TrimSpace(request.Name)
diff --git a/backend/app/controllers/exception_stack_trace.controller.go b/backend/app/controllers/exception_stack_trace.controller.go
index 741c919d..5f08369b 100644
--- a/backend/app/controllers/exception_stack_trace.controller.go
+++ b/backend/app/controllers/exception_stack_trace.controller.go
@@ -94,7 +94,7 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.C
var request ExceptionSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/incident.controller.go b/backend/app/controllers/incident.controller.go
index ba4f2630..9ee54388 100644
--- a/backend/app/controllers/incident.controller.go
+++ b/backend/app/controllers/incident.controller.go
@@ -224,7 +224,7 @@ func (ctrl *incidentController) Create(ctx *gin.Context) {
}
var req manualIncidentRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
@@ -328,7 +328,7 @@ func (ctrl *incidentController) Update(ctx *gin.Context) {
}
var req editIncidentRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
@@ -452,7 +452,7 @@ func (ctrl *incidentController) CreateUpdate(ctx *gin.Context) {
}
var req postIncidentUpdateRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
diff --git a/backend/app/controllers/invitation.controller.go b/backend/app/controllers/invitation.controller.go
index de8ca478..fbdb4609 100644
--- a/backend/app/controllers/invitation.controller.go
+++ b/backend/app/controllers/invitation.controller.go
@@ -29,7 +29,7 @@ func (c *invitationController) InviteUser(ctx *gin.Context) {
var request models.InviteUserRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -236,7 +236,7 @@ func (c *invitationController) AcceptInvitation(ctx *gin.Context) {
var request models.AcceptInvitationRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/log.controller.go b/backend/app/controllers/log.controller.go
index 1cc072f3..dfdad7ec 100644
--- a/backend/app/controllers/log.controller.go
+++ b/backend/app/controllers/log.controller.go
@@ -67,7 +67,7 @@ func (l logController) List(c *gin.Context) {
var request LogSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/member.controller.go b/backend/app/controllers/member.controller.go
index 695b2937..ba51a57a 100644
--- a/backend/app/controllers/member.controller.go
+++ b/backend/app/controllers/member.controller.go
@@ -30,7 +30,7 @@ func (c *memberController) UpdateRole(ctx *gin.Context) {
var request models.UpdateMemberRoleRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -176,7 +176,7 @@ func (c *memberController) UpdateProjectRole(ctx *gin.Context) {
var request models.UpdateProjectRoleRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/metric_query.controller.go b/backend/app/controllers/metric_query.controller.go
index 3fc50989..9afdc0de 100644
--- a/backend/app/controllers/metric_query.controller.go
+++ b/backend/app/controllers/metric_query.controller.go
@@ -106,7 +106,8 @@ type MetricQueryItem struct {
}
type MetricQueryResponse struct {
- Results []MetricQueryResult `json:"results"`
+ Results []MetricQueryResult `json:"results"`
+ IntervalMinutes int `json:"intervalMinutes"`
}
type MetricQueryResult struct {
@@ -194,7 +195,7 @@ func (c *metricQueryController) Query(ctx *gin.Context) {
})
}
- ctx.JSON(http.StatusOK, MetricQueryResponse{Results: results})
+ ctx.JSON(http.StatusOK, MetricQueryResponse{Results: results, IntervalMinutes: req.IntervalMinutes})
}
type DiscoverResponse struct {
@@ -415,7 +416,7 @@ func (c *metricQueryController) UpdateRegistry(ctx *gin.Context) {
Description string `json:"description"`
}
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/notification_channel.controller.go b/backend/app/controllers/notification_channel.controller.go
index 50669b21..416680ad 100644
--- a/backend/app/controllers/notification_channel.controller.go
+++ b/backend/app/controllers/notification_channel.controller.go
@@ -96,7 +96,7 @@ func (ctrl *notificationChannelController) Create(ctx *gin.Context) {
var req createChannelRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -167,7 +167,7 @@ func (ctrl *notificationChannelController) Update(ctx *gin.Context) {
var req createChannelRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/notification_history.controller.go b/backend/app/controllers/notification_history.controller.go
index 60cb7d88..5324e586 100644
--- a/backend/app/controllers/notification_history.controller.go
+++ b/backend/app/controllers/notification_history.controller.go
@@ -29,7 +29,7 @@ func (ctrl *notificationHistoryController) List(ctx *gin.Context) {
var request NotificationHistorySearchRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/notification_rule.controller.go b/backend/app/controllers/notification_rule.controller.go
index 6d355460..5cbfa3e7 100644
--- a/backend/app/controllers/notification_rule.controller.go
+++ b/backend/app/controllers/notification_rule.controller.go
@@ -83,7 +83,7 @@ func (ctrl *notificationRuleController) Create(ctx *gin.Context) {
var req createRuleRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -171,7 +171,7 @@ func (ctrl *notificationRuleController) Update(ctx *gin.Context) {
var req createRuleRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -326,7 +326,7 @@ func (ctrl *notificationRuleController) Snooze(ctx *gin.Context) {
var req snoozeRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.go
index d4ac8788..60b6dd89 100644
--- a/backend/app/controllers/oauth.controller.go
+++ b/backend/app/controllers/oauth.controller.go
@@ -213,7 +213,7 @@ func (a oauthController) findOrCreateUser(c *gin.Context, provider string, gothU
func (a oauthController) FinishSetup(c *gin.Context) {
var request finishOAuthSetupRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(c, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/oncall.controller.go b/backend/app/controllers/oncall.controller.go
index a238ed1f..be3b8cd8 100644
--- a/backend/app/controllers/oncall.controller.go
+++ b/backend/app/controllers/oncall.controller.go
@@ -59,7 +59,7 @@ func (c *oncallController) CreateSchedule(ctx *gin.Context) {
var request scheduleRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
message, definition, tzName := c.validateScheduleRequest(ctx, organizationId, &request, 0)
@@ -122,7 +122,7 @@ func (c *oncallController) UpdateSchedule(ctx *gin.Context) {
}
var request scheduleRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
message, definition, tzName := c.validateScheduleRequest(ctx, organizationId, &request, schedule.Id)
@@ -283,7 +283,7 @@ func (c *oncallController) CreateOverride(ctx *gin.Context) {
}
var request createOverrideRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if !request.StartAt.Before(request.EndAt) {
diff --git a/backend/app/controllers/organization_overview.controller.go b/backend/app/controllers/organization_overview.controller.go
index 7d28fd0a..4af2ebf8 100644
--- a/backend/app/controllers/organization_overview.controller.go
+++ b/backend/app/controllers/organization_overview.controller.go
@@ -1,6 +1,7 @@
package controllers
import (
+ "context"
"database/sql"
"fmt"
"math"
@@ -96,7 +97,7 @@ func clampPercent(value float64) float64 {
}
func otelFractionToPercent(value float64) float64 {
- if value <= 1.5 {
+ if value <= 1 {
value *= 100
}
return clampPercent(value)
@@ -142,6 +143,34 @@ func latestCounterRate(points []models.TimeSeriesPoint) (float64, bool) {
return delta / seconds, true
}
+func sumDeviceRates(series map[string][]models.TimeSeriesPoint) (float64, bool) {
+ total, found := 0.0, false
+ for _, points := range series {
+ rate, ok := latestCounterRate(points)
+ if !ok {
+ continue
+ }
+ total += rate
+ found = true
+ }
+ return total, found
+}
+
+// system.network.io is a cumulative counter per device, so summing samples
+// inside a bucket (or across devices) makes the bucket delta meaningless. The
+// last sample per device per minute, differenced and then summed, is the rate.
+func loadNetworkRate(ctx context.Context, projectId uuid.UUID, serverName, direction string, since, to time.Time) (*float64, error) {
+ series, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, projectId, models.MetricNameSystemNetworkIO, since, to, 1, "last", map[string]string{"direction": direction, "server_name": serverName}, "device", 0)
+ if err != nil {
+ return nil, err
+ }
+ rate, ok := sumDeviceRates(series)
+ if !ok {
+ return nil, nil
+ }
+ return pointerTo(rate), nil
+}
+
func applyServerMetadata(row *orgServerRow, tags map[string]string) {
row.HostName = tags["host.name"]
row.HostId = tags["host.id"]
@@ -218,14 +247,7 @@ func loadProjectServerRows(ctx *gin.Context, project *models.Project, dashboardI
if err != nil {
return nil, err
}
- networkReceive, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemNetworkIO, since, now, 1, "sum", map[string]string{"direction": "receive"}, "server_name", 0)
- if err != nil {
- return nil, err
- }
- networkTransmit, err := telemetry.MetricPointRepository.QueryTimeSeries(ctx, project.Id, models.MetricNameSystemNetworkIO, since, now, 1, "sum", map[string]string{"direction": "transmit"}, "server_name", 0)
- if err != nil {
- return nil, err
- }
+ networkTo := now.Truncate(time.Minute).Add(-time.Millisecond)
for _, point := range latestOtel {
row := rows[point.ServerName]
@@ -239,11 +261,11 @@ func loadProjectServerRows(ctx *gin.Context, project *models.Project, dashboardI
if value, ok := lastSeriesValue(filesystemUsed, point.ServerName); ok {
row.DiskPct = pointerTo(otelFractionToPercent(value))
}
- if value, ok := latestCounterRate(networkReceive[point.ServerName]); ok {
- row.NetworkRxBps = pointerTo(value)
+ if row.NetworkRxBps, err = loadNetworkRate(ctx, project.Id, point.ServerName, "receive", since, networkTo); err != nil {
+ return nil, err
}
- if value, ok := latestCounterRate(networkTransmit[point.ServerName]); ok {
- row.NetworkTxBps = pointerTo(value)
+ if row.NetworkTxBps, err = loadNetworkRate(ctx, project.Id, point.ServerName, "transmit", since, networkTo); err != nil {
+ return nil, err
}
}
}
@@ -344,13 +366,15 @@ func (c *organizationOverviewController) Issues(ctx *gin.Context) {
issues := make([]orgIssueRow, 0)
var totalGroups int64
+ partial := false
for _, project := range projects {
span := traceway.StartSpan(ctx, fmt.Sprintf("org overview issues: project %s", project.Id))
groups, total, err := telemetry.ExceptionStackTraceRepository.FindGrouped(ctx, project.Id, from, now, 1, orgOverviewMaxIssues, "last_seen", "", "", false)
span.End()
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to load issues for project %s: %w", project.Id, err))
- return
+ partial = true
+ traceway.CaptureException(traceway.NewStackTraceErrorf("failed to load issues for project %s: %w", project.Id, err))
+ continue
}
totalGroups += total
for _, group := range groups {
@@ -365,7 +389,7 @@ func (c *organizationOverviewController) Issues(ctx *gin.Context) {
issues = issues[:orgOverviewMaxIssues]
}
- ctx.JSON(http.StatusOK, gin.H{"issues": issues, "totalGroups": totalGroups})
+ ctx.JSON(http.StatusOK, gin.H{"issues": issues, "totalGroups": totalGroups, "partial": partial})
}
type orgPageRow struct {
@@ -468,13 +492,15 @@ func (c *organizationOverviewController) Monitors(ctx *gin.Context) {
from := now.AddDate(0, 0, -30)
aggregates := make(map[int]*models.CheckAggregates)
+ partial := false
for _, projectId := range projectsWithChecks {
span := traceway.StartSpan(ctx, fmt.Sprintf("org overview monitors: project %s", projectId))
projectAggregates, err := telemetry.CheckResultRepository.AggregatesByProject(ctx, projectId, from, now)
span.End()
if err != nil {
- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to aggregate check results for project %s: %w", projectId, err))
- return
+ partial = true
+ traceway.CaptureException(traceway.NewStackTraceErrorf("failed to aggregate check results for project %s: %w", projectId, err))
+ continue
}
for checkId, agg := range projectAggregates {
aggregates[checkId] = agg
@@ -490,5 +516,5 @@ func (c *organizationOverviewController) Monitors(ctx *gin.Context) {
})
}
- ctx.JSON(http.StatusOK, gin.H{"checks": items})
+ ctx.JSON(http.StatusOK, gin.H{"checks": items, "partial": partial})
}
diff --git a/backend/app/controllers/organization_overview_test.go b/backend/app/controllers/organization_overview_test.go
index ce6f74ec..e93dc8f9 100644
--- a/backend/app/controllers/organization_overview_test.go
+++ b/backend/app/controllers/organization_overview_test.go
@@ -1,6 +1,7 @@
package controllers
import (
+ "math"
"testing"
"time"
@@ -36,3 +37,33 @@ func TestLatestCounterRate(t *testing.T) {
t.Fatalf("reset rate = %v, %v, want 0 bytes/s", rate, ok)
}
}
+
+func TestSumDeviceRates(t *testing.T) {
+ now := time.Now().UTC()
+ series := map[string][]models.TimeSeriesPoint{
+ "eth0": {{Timestamp: now, Value: 1_000}, {Timestamp: now.Add(time.Minute), Value: 7_000}},
+ "eth1": {{Timestamp: now, Value: 500}, {Timestamp: now.Add(time.Minute), Value: 1_100}},
+ "reset": {{Timestamp: now, Value: 9_000}, {Timestamp: now.Add(time.Minute), Value: 10}},
+ "fresh": {{Timestamp: now.Add(time.Minute), Value: 42}},
+ }
+ rate, ok := sumDeviceRates(series)
+ if !ok || rate != 110 {
+ t.Fatalf("rate = %v, %v, want 110 bytes/s (100 + 10 + 0 for the reset device)", rate, ok)
+ }
+
+ if _, ok := sumDeviceRates(map[string][]models.TimeSeriesPoint{"fresh": series["fresh"]}); ok {
+ t.Fatal("a device with a single bucket reported a rate")
+ }
+ if _, ok := sumDeviceRates(nil); ok {
+ t.Fatal("no devices reported a rate")
+ }
+}
+
+func TestOtelFractionToPercent(t *testing.T) {
+ cases := map[float64]float64{0: 0, 0.42: 42, 1: 100, 1.2: 1.2, 55: 55, 140: 100}
+ for in, want := range cases {
+ if got := otelFractionToPercent(in); math.Abs(got-want) > 1e-9 {
+ t.Errorf("otelFractionToPercent(%v) = %v, want %v", in, got, want)
+ }
+ }
+}
diff --git a/backend/app/controllers/page.controller.go b/backend/app/controllers/page.controller.go
index b15ee31b..952623be 100644
--- a/backend/app/controllers/page.controller.go
+++ b/backend/app/controllers/page.controller.go
@@ -78,7 +78,7 @@ func (c *pageController) List(ctx *gin.Context) {
}
var request listPagesRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if !validPageStatusFilters[request.Status] {
@@ -384,7 +384,7 @@ func (c *pageController) UnresolvedForIssues(ctx *gin.Context) {
}
var request pagesForIssuesRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if len(request.Hashes) > maxBulkIssueHashes {
diff --git a/backend/app/controllers/password_reset.controller.go b/backend/app/controllers/password_reset.controller.go
index 3104cf63..b049854f 100644
--- a/backend/app/controllers/password_reset.controller.go
+++ b/backend/app/controllers/password_reset.controller.go
@@ -5,6 +5,7 @@ import (
"fmt"
"github.com/tracewayapp/traceway/backend/app/config"
"github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
"github.com/tracewayapp/traceway/backend/app/repositories/transactional"
"github.com/tracewayapp/traceway/backend/app/services"
@@ -31,7 +32,7 @@ func (c *passwordResetController) ForgotPassword(ctx *gin.Context) {
var request models.ForgotPasswordRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -113,7 +114,7 @@ func (c *passwordResetController) ResetPassword(ctx *gin.Context) {
var request models.ResetPasswordRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/pat.controller.go b/backend/app/controllers/pat.controller.go
index fd12f155..1a305588 100644
--- a/backend/app/controllers/pat.controller.go
+++ b/backend/app/controllers/pat.controller.go
@@ -25,7 +25,7 @@ func (c *patController) Create(ctx *gin.Context) {
var req models.CreatePATRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
name := strings.TrimSpace(req.Name)
diff --git a/backend/app/controllers/post_mortem.controller.go b/backend/app/controllers/post_mortem.controller.go
index 2a4507f8..6261a168 100644
--- a/backend/app/controllers/post_mortem.controller.go
+++ b/backend/app/controllers/post_mortem.controller.go
@@ -217,7 +217,7 @@ func (ctrl *postMortemController) Create(ctx *gin.Context) {
}
var req postMortemRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
@@ -279,7 +279,7 @@ func (ctrl *postMortemController) Update(ctx *gin.Context) {
}
var req postMortemRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
diff --git a/backend/app/controllers/profile.controller.go b/backend/app/controllers/profile.controller.go
index 159deb19..1c7c14f1 100644
--- a/backend/app/controllers/profile.controller.go
+++ b/backend/app/controllers/profile.controller.go
@@ -120,7 +120,7 @@ func (p profileController) FindGroupedByService(c *gin.Context) {
var request ProfileGroupedRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -155,7 +155,7 @@ func (p profileController) GetSeries(c *gin.Context) {
var request ProfileSeriesRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
@@ -191,7 +191,7 @@ func (p profileController) DiscoverTypes(c *gin.Context) {
var request ProfileTypesRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" {
@@ -227,7 +227,7 @@ func (p profileController) GetFlameGraph(c *gin.Context) {
var request ProfileFlameGraphRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
@@ -260,7 +260,7 @@ func (p profileController) GetTopFunctions(c *gin.Context) {
var request ProfileTopFunctionsRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
@@ -300,7 +300,7 @@ func (p profileController) DownloadPprof(c *gin.Context) {
var request ProfileFlameGraphRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
@@ -385,7 +385,7 @@ func (p profileController) GetSeriesBreakdown(c *gin.Context) {
var request ProfileSeriesBreakdownRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" || request.Dimension == "" {
@@ -425,7 +425,7 @@ func (p profileController) DiscoverDimensions(c *gin.Context) {
var request ProfileDimensionsRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
@@ -456,7 +456,7 @@ func (p profileController) DiscoverLabels(c *gin.Context) {
var request ProfileLabelsRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
if request.ServiceName == "" || request.Type == "" {
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.go
index 5418273d..801a2ebc 100644
--- a/backend/app/controllers/project.controller.go
+++ b/backend/app/controllers/project.controller.go
@@ -151,7 +151,7 @@ func (p projectController) ListProjects(c *gin.Context) {
func (p projectController) CreateProject(c *gin.Context) {
var request CreateProjectRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -229,7 +229,7 @@ func (p projectController) CreateProject(c *gin.Context) {
func (p projectController) UpdateProject(c *gin.Context) {
var request UpdateProjectRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -345,7 +345,7 @@ func (p projectController) UpdateProject(c *gin.Context) {
func (p projectController) DeleteProject(c *gin.Context) {
var request DeleteProjectRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/project_batch.go b/backend/app/controllers/project_batch.go
index 0da450ef..c11bf959 100644
--- a/backend/app/controllers/project_batch.go
+++ b/backend/app/controllers/project_batch.go
@@ -169,7 +169,7 @@ type BatchCreateProjectsRequest struct {
func (p projectController) BatchCreateProjects(ctx *gin.Context) {
var request BatchCreateProjectsRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/session.controller.go b/backend/app/controllers/session.controller.go
index 69d2a7b0..a9c3140d 100644
--- a/backend/app/controllers/session.controller.go
+++ b/backend/app/controllers/session.controller.go
@@ -38,7 +38,7 @@ func (s sessionController) FindAllSessions(c *gin.Context) {
var request SessionSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/setup.controller.go b/backend/app/controllers/setup.controller.go
index 515f565f..53f76f67 100644
--- a/backend/app/controllers/setup.controller.go
+++ b/backend/app/controllers/setup.controller.go
@@ -129,7 +129,7 @@ func validateSetupPlanPayload(payload *models.SetupPlanPayload) string {
func (s setupController) SubmitPlan(ctx *gin.Context) {
var payload models.SetupPlanPayload
if err := ctx.ShouldBindJSON(&payload); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if msg := validateSetupPlanPayload(&payload); msg != "" {
diff --git a/backend/app/controllers/setup_token.controller.go b/backend/app/controllers/setup_token.controller.go
index 9aea01a4..2e506c0d 100644
--- a/backend/app/controllers/setup_token.controller.go
+++ b/backend/app/controllers/setup_token.controller.go
@@ -22,7 +22,7 @@ type setupTokenController struct{}
func (s setupTokenController) Create(ctx *gin.Context) {
var req models.CreateSetupTokenRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
diff --git a/backend/app/controllers/status_page.controller.go b/backend/app/controllers/status_page.controller.go
index 6d0b7218..7e16bc68 100644
--- a/backend/app/controllers/status_page.controller.go
+++ b/backend/app/controllers/status_page.controller.go
@@ -16,6 +16,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/middleware"
"github.com/tracewayapp/traceway/backend/app/models"
"github.com/tracewayapp/traceway/backend/app/repositories/telemetry"
"github.com/tracewayapp/traceway/backend/app/repositories/transactional"
@@ -118,7 +119,7 @@ func (ctrl *statusPageController) Create(ctx *gin.Context) {
}
var req statusPageRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
@@ -180,7 +181,7 @@ func (ctrl *statusPageController) Update(ctx *gin.Context) {
}
var req statusPageRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
tx := db.GetTx(ctx)
diff --git a/backend/app/controllers/synthetic_check.controller.go b/backend/app/controllers/synthetic_check.controller.go
index a8693bb8..a12b650b 100644
--- a/backend/app/controllers/synthetic_check.controller.go
+++ b/backend/app/controllers/synthetic_check.controller.go
@@ -176,7 +176,7 @@ func (ctrl *syntheticCheckController) Overview(ctx *gin.Context) {
}
var req checkOverviewRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
from, to, ok := parseCheckRange(ctx, req.FromDate, req.ToDate)
@@ -211,7 +211,7 @@ func (ctrl *syntheticCheckController) Create(ctx *gin.Context) {
}
var req checkRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if message := validateCheckRequest(&req); message != "" {
@@ -328,7 +328,7 @@ func (ctrl *syntheticCheckController) Update(ctx *gin.Context) {
}
var req checkRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
@@ -482,7 +482,7 @@ func (ctrl *syntheticCheckController) Results(ctx *gin.Context) {
}
var req checkResultsRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
from, to, ok := parseCheckRange(ctx, req.FromDate, req.ToDate)
@@ -530,7 +530,7 @@ func (ctrl *syntheticCheckController) Series(ctx *gin.Context) {
}
var req checkSeriesRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
from, to, ok := parseCheckRange(ctx, req.FromDate, req.ToDate)
diff --git a/backend/app/controllers/synthetic_runner.controller.go b/backend/app/controllers/synthetic_runner.controller.go
index dcfbc2ba..1349637c 100644
--- a/backend/app/controllers/synthetic_runner.controller.go
+++ b/backend/app/controllers/synthetic_runner.controller.go
@@ -179,7 +179,7 @@ func (ctrl *syntheticRunnerController) Result(ctx *gin.Context) {
ctx.Request.Body = http.MaxBytesReader(ctx.Writer, ctx.Request.Body, runnerResultBodyLimit)
var req runnerResultRequest
if err := ctx.ShouldBindJSON(&req); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if req.Status != models.CheckResultUp && req.Status != models.CheckResultDown {
diff --git a/backend/app/controllers/task.controller.go b/backend/app/controllers/task.controller.go
index d28c5c79..4968f730 100644
--- a/backend/app/controllers/task.controller.go
+++ b/backend/app/controllers/task.controller.go
@@ -47,7 +47,7 @@ func (e taskController) FindAllTasks(c *gin.Context) {
var request TaskSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -79,7 +79,7 @@ func (e taskController) FindGroupedByTaskName(c *gin.Context) {
var request TaskSearchRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
@@ -123,7 +123,7 @@ func (e taskController) FindByTaskName(c *gin.Context) {
var request TaskInstancesRequest
if err := c.ShouldBindJSON(&request); err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ middleware.RejectBindError(c, err, err.Error())
return
}
diff --git a/backend/app/controllers/team.controller.go b/backend/app/controllers/team.controller.go
index ae23027a..a9235301 100644
--- a/backend/app/controllers/team.controller.go
+++ b/backend/app/controllers/team.controller.go
@@ -106,7 +106,7 @@ func (c *teamController) Create(ctx *gin.Context) {
var request createTeamRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if message := validateTeamName(request.Name); message != "" {
@@ -177,7 +177,7 @@ func (c *teamController) Update(ctx *gin.Context) {
}
var request updateTeamRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if message := validateTeamName(request.Name); message != "" {
@@ -271,7 +271,7 @@ func (c *teamController) SetMembers(ctx *gin.Context) {
}
var request setTeamMembersRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if message, err := c.checkMembersInOrg(tx, organizationId, request.UserIds); err != nil {
@@ -298,7 +298,7 @@ func (c *teamController) SetProjects(ctx *gin.Context) {
}
var request setTeamProjectsRequest
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if message, err := c.checkProjectsAssignable(tx, organizationId, team.Id, request.ProjectIds); err != nil {
diff --git a/backend/app/controllers/user_notification_rule.controller.go b/backend/app/controllers/user_notification_rule.controller.go
index 52ba347e..7d91f9a0 100644
--- a/backend/app/controllers/user_notification_rule.controller.go
+++ b/backend/app/controllers/user_notification_rule.controller.go
@@ -62,7 +62,7 @@ func (c *userNotificationRuleController) Put(ctx *gin.Context) {
var request notificationRuleChains
if err := ctx.ShouldBindJSON(&request); err != nil {
- ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ middleware.RejectBindError(ctx, err, "Invalid request body")
return
}
if len(request.High) > maxRuleStepsPerChain || len(request.Low) > maxRuleStepsPerChain {
diff --git a/backend/app/middleware/body_error_test.go b/backend/app/middleware/body_error_test.go
new file mode 100644
index 00000000..e384a68d
--- /dev/null
+++ b/backend/app/middleware/body_error_test.go
@@ -0,0 +1,87 @@
+package middleware
+
+import (
+ "encoding/json"
+ "errors"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+)
+
+func TestRejectBindError(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ addr := &net.TCPAddr{IP: net.ParseIP("10.1.2.3"), Port: 8082}
+ cases := []struct {
+ name string
+ err error
+ fallback string
+ wantStatus int
+ wantMessage string
+ }{
+ {
+ name: "max bytes exceeded",
+ err: &http.MaxBytesError{Limit: 64},
+ fallback: "Invalid request body",
+ wantStatus: http.StatusRequestEntityTooLarge,
+ wantMessage: "Request body too large",
+ },
+ {
+ name: "body too slow",
+ err: ErrBodyTooSlow,
+ fallback: "Invalid request body",
+ wantStatus: http.StatusRequestTimeout,
+ wantMessage: "Request body arrived too slowly",
+ },
+ {
+ name: "read deadline exceeded",
+ err: &net.OpError{Op: "read", Net: "tcp", Source: addr, Addr: addr, Err: os.ErrDeadlineExceeded},
+ fallback: "Invalid request body",
+ wantStatus: http.StatusRequestTimeout,
+ wantMessage: "Request body arrived too slowly",
+ },
+ {
+ name: "plain bind error uses the fallback",
+ err: errors.New("bad json"),
+ fallback: "Invalid request body",
+ wantStatus: http.StatusBadRequest,
+ wantMessage: "Invalid request body",
+ },
+ {
+ name: "plain bind error echoed through the fallback",
+ err: errors.New("bad json"),
+ fallback: "bad json",
+ wantStatus: http.StatusBadRequest,
+ wantMessage: "bad json",
+ },
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ rec := httptest.NewRecorder()
+ c, _ := gin.CreateTestContext(rec)
+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)
+
+ RejectBindError(c, tc.err, tc.fallback)
+
+ if rec.Code != tc.wantStatus {
+ t.Fatalf("status = %d, want %d (body %q)", rec.Code, tc.wantStatus, rec.Body.String())
+ }
+ var body struct {
+ Error string `json:"error"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
+ t.Fatalf("body %q is not JSON: %v", rec.Body.String(), err)
+ }
+ if body.Error != tc.wantMessage {
+ t.Fatalf("error = %q, want %q", body.Error, tc.wantMessage)
+ }
+ if strings.Contains(rec.Body.String(), addr.String()) {
+ t.Fatalf("body %q leaks the listener address", rec.Body.String())
+ }
+ })
+ }
+}
diff --git a/backend/app/middleware/ingest_admission.go b/backend/app/middleware/ingest_admission.go
index 83a16dd4..f8768bb2 100644
--- a/backend/app/middleware/ingest_admission.go
+++ b/backend/app/middleware/ingest_admission.go
@@ -61,6 +61,7 @@ func newAdmissionGate(capacity int, wait time.Duration, message string, onReject
return
}
}
+ restartBodyGuard(c)
defer func() { <-slots }()
c.Next()
}
diff --git a/backend/app/middleware/read_deadline.go b/backend/app/middleware/read_deadline.go
index 490850fc..417b7ef3 100644
--- a/backend/app/middleware/read_deadline.go
+++ b/backend/app/middleware/read_deadline.go
@@ -2,8 +2,10 @@ package middleware
import (
"errors"
+ "fmt"
"io"
"net/http"
+ "os"
"time"
"github.com/gin-gonic/gin"
@@ -15,6 +17,10 @@ var throughputGracePeriod = 20 * time.Second
var ErrBodyTooSlow = errors.New("request body delivered too slowly")
+// The raw deadline error is a *net.OpError naming the listener address, and
+// handlers echo bind errors verbatim, so it is replaced before it leaves Read.
+var ErrBodyTimedOut = fmt.Errorf("request body timed out: %w", os.ErrDeadlineExceeded)
+
const (
DefaultBodyIdle = 30 * time.Second
DefaultBodyTotal = 10 * time.Minute
@@ -27,6 +33,7 @@ type progressBody struct {
ctl *http.ResponseController
declared int64
idle time.Duration
+ total time.Duration
deadline time.Time
lastSet time.Time
start time.Time
@@ -36,6 +43,9 @@ type progressBody struct {
func (p *progressBody) Read(b []byte) (int, error) {
n, err := p.rc.Read(b)
+ if errors.Is(err, os.ErrDeadlineExceeded) {
+ err = ErrBodyTimedOut
+ }
if p.done {
return n, err
}
@@ -67,10 +77,34 @@ func (p *progressBody) arm(now time.Time) {
p.lastSet = now
}
+// restart re-arms the deadlines and restarts the throughput clock, so time a
+// request spent parked before its handler read anything (an admission gate)
+// is not held against it.
+func (p *progressBody) restart(now time.Time, idle, total time.Duration) {
+ p.idle = idle
+ p.total = total
+ p.deadline = now.Add(total)
+ p.start = now
+ p.read = 0
+ p.arm(now)
+}
+
func (p *progressBody) Close() error { return p.rc.Close() }
+func restartBodyGuard(c *gin.Context) {
+ if existing, ok := c.Get(bodyGuardContextKey); ok {
+ if p, ok := existing.(*progressBody); ok && !p.done {
+ p.restart(time.Now(), p.idle, p.total)
+ }
+ }
+}
+
func GuardBodyRead(c *gin.Context, idle, total time.Duration) {
if c.Request == nil || c.Request.Body == nil || c.Request.Body == http.NoBody {
+ // Nothing to read, but the server's ReadTimeout is still armed on the
+ // connection and would cancel a long-lived handler such as the MCP GET
+ // stream, so lift it the way a completed body does.
+ _ = http.NewResponseController(c.Writer).SetReadDeadline(time.Time{})
return
}
now := time.Now()
@@ -79,9 +113,7 @@ func GuardBodyRead(c *gin.Context, idle, total time.Duration) {
if p.done {
return
}
- p.idle = idle
- p.deadline = now.Add(total)
- p.arm(now)
+ p.restart(now, idle, total)
return
}
}
@@ -92,6 +124,7 @@ func GuardBodyRead(c *gin.Context, idle, total time.Duration) {
ctl: ctl,
declared: c.Request.ContentLength,
idle: idle,
+ total: total,
deadline: now.Add(total),
start: now,
}
diff --git a/backend/app/middleware/throughput_test.go b/backend/app/middleware/throughput_test.go
index 466afb27..cb7d80ee 100644
--- a/backend/app/middleware/throughput_test.go
+++ b/backend/app/middleware/throughput_test.go
@@ -175,3 +175,135 @@ func TestGuardBodyReadClearsTheDeadlineOnceTheBodyIsComplete(t *testing.T) {
t.Fatalf("a handler outliving the idle window after the body arrived lost its context: %v", err)
}
}
+
+func drainInSmallReads(r io.Reader) error {
+ buf := make([]byte, 64)
+ for {
+ if _, err := r.Read(buf); err != nil {
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ return err
+ }
+ }
+}
+
+func sendWholeBody(t *testing.T, addr, path string, size int) {
+ t.Helper()
+ conn, err := net.Dial("tcp", addr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { conn.Close() })
+ fmt.Fprintf(conn, "POST %s HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n", path, size)
+ go conn.Write(make([]byte, size))
+}
+
+func TestGuardBodyReadRestartsTheClockWhenRearmed(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ prev := throughputGracePeriod
+ throughputGracePeriod = 500 * time.Millisecond
+ t.Cleanup(func() { throughputGracePeriod = prev })
+
+ readErrs := make(chan error, 1)
+ r := gin.New()
+ r.Use(GuardBodyReads(DefaultBodyIdle, DefaultBodyTotal))
+ r.POST("/upload", func(c *gin.Context) {
+ time.Sleep(700 * time.Millisecond)
+ GuardBodyRead(c, DefaultBodyIdle, DefaultBodyTotal)
+ readErrs <- drainInSmallReads(c.Request.Body)
+ c.Status(http.StatusOK)
+ })
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: r}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+
+ sendWholeBody(t, ln.Addr().String(), "/upload", 200<<10)
+
+ select {
+ case err := <-readErrs:
+ if err != nil {
+ t.Fatalf("a body that arrived at once was rejected after the handler waited before reading: %v", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timed out")
+ }
+}
+
+func TestAdmissionGateRestartsTheGuardAfterWaiting(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ prev := throughputGracePeriod
+ throughputGracePeriod = 500 * time.Millisecond
+ t.Cleanup(func() { throughputGracePeriod = prev })
+
+ readErrs := make(chan error, 1)
+ r := gin.New()
+ r.Use(GuardBodyReads(DefaultBodyIdle, DefaultBodyTotal))
+ gate := newAdmissionGate(1, 5*time.Second, "saturated", nil)
+ r.POST("/hold", gate, func(c *gin.Context) {
+ time.Sleep(700 * time.Millisecond)
+ c.Status(http.StatusOK)
+ })
+ r.POST("/upload", gate, func(c *gin.Context) {
+ readErrs <- drainInSmallReads(c.Request.Body)
+ c.Status(http.StatusOK)
+ })
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: r}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+
+ sendWholeBody(t, ln.Addr().String(), "/hold", 0)
+ time.Sleep(50 * time.Millisecond)
+ sendWholeBody(t, ln.Addr().String(), "/upload", 200<<10)
+
+ select {
+ case err := <-readErrs:
+ if err != nil {
+ t.Fatalf("a body that waited in the admission gate was rejected: %v", err)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("timed out")
+ }
+}
+
+func TestGuardBodyReadLiftsTheServerReadTimeoutForBodilessRequests(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ ctxErrs := make(chan error, 1)
+ r := gin.New()
+ r.Use(GuardBodyReads(DefaultBodyIdle, DefaultBodyTotal))
+ r.GET("/stream", func(c *gin.Context) {
+ select {
+ case <-c.Request.Context().Done():
+ ctxErrs <- c.Request.Context().Err()
+ case <-time.After(1500 * time.Millisecond):
+ ctxErrs <- nil
+ }
+ c.Status(http.StatusOK)
+ })
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv := &http.Server{Handler: r, ReadTimeout: time.Second}
+ go srv.Serve(ln)
+ t.Cleanup(func() { srv.Close() })
+
+ conn, err := net.Dial("tcp", ln.Addr().String())
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer conn.Close()
+ fmt.Fprint(conn, "GET /stream HTTP/1.1\r\nHost: x\r\n\r\n")
+
+ if err := <-ctxErrs; err != nil {
+ t.Fatalf("a bodiless handler outliving ReadTimeout lost its context: %v", err)
+ }
+}
diff --git a/backend/app/notifications/adapter_email_test.go b/backend/app/notifications/adapter_email_test.go
new file mode 100644
index 00000000..cf366741
--- /dev/null
+++ b/backend/app/notifications/adapter_email_test.go
@@ -0,0 +1,29 @@
+package notifications
+
+import "testing"
+
+func TestEmailAdapterValidate(t *testing.T) {
+ eleven := make([]string, 11)
+ for i := range eleven {
+ eleven[i] = "[email protected]"
+ }
+ cases := []struct {
+ name string
+ recipients []string
+ ok bool
+ }{
+ {"bare address", []string{"[email protected]"}, true},
+ {"display name", []string{"Ops Team <[email protected]>"}, true},
+ {"comma-joined pair", []string{"[email protected], [email protected]"}, false},
+ {"header injection", []string{"[email protected]\r\nBcc: [email protected]"}, false},
+ {"missing at", []string{"ops.example.com"}, false},
+ {"empty", nil, false},
+ {"eleven recipients", eleven, false},
+ }
+ for _, c := range cases {
+ err := (&EmailAdapter{Recipients: c.recipients}).Validate()
+ if (err == nil) != c.ok {
+ t.Errorf("%s: err = %v, want ok=%v", c.name, err, c.ok)
+ }
+ }
+}
diff --git a/backend/app/repositories/telemetry/endpoint_repository_test.go b/backend/app/repositories/telemetry/endpoint_repository_test.go
index 7ea23e41..d4488e1d 100644
--- a/backend/app/repositories/telemetry/endpoint_repository_test.go
+++ b/backend/app/repositories/telemetry/endpoint_repository_test.go
@@ -550,3 +550,35 @@ func TestEndpointRepository_GetEndpointStats_EmptyWindow(t *testing.T) {
t.Errorf("expected IsStream false for empty window")
}
}
+
+func TestEndpointRepository_FindGroupedByEndpoint_RootFilterPercentiles(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ now := truncateMs(time.Now().UTC())
+
+ var endpoints []models.Endpoint
+ for i := 0; i < 4; i++ {
+ at := now.Add(time.Duration(i) * time.Second)
+ root := makeEndpoint(projectId, "GET /api/orders", 100*time.Millisecond, 200, at)
+ root.IsRoot = true
+ endpoints = append(endpoints, root, makeEndpoint(projectId, "GET /api/orders", 900*time.Millisecond, 200, at.Add(500*time.Millisecond)))
+ }
+ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ stats, total, err := EndpointRepository.FindGroupedByEndpoint(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "count", "desc", "", "root", "")
+ if err != nil {
+ t.Fatalf("FindGroupedByEndpoint with root filter failed: %v", err)
+ }
+ if total != 1 || len(stats) != 1 {
+ t.Fatalf("expected 1 grouped endpoint, got total=%d len=%d", total, len(stats))
+ }
+ if stats[0].Count != 4 {
+ t.Errorf("count = %d, want the 4 root calls", stats[0].Count)
+ }
+ if stats[0].P95Duration > 100*time.Millisecond {
+ t.Errorf("p95 = %v, want the root-only 100ms; non-root durations leaked into the percentile", stats[0].P95Duration)
+ }
+}
diff --git a/backend/app/repositories/telemetry/metric_point_repository_test.go b/backend/app/repositories/telemetry/metric_point_repository_test.go
index d0ba12d6..2416d0e4 100644
--- a/backend/app/repositories/telemetry/metric_point_repository_test.go
+++ b/backend/app/repositories/telemetry/metric_point_repository_test.go
@@ -487,3 +487,46 @@ func TestMetricPointRepository_QueryTimeSeries_LastAggregationWithGroupBy(t *tes
assertApproxEqual(t, "last sda", result["sda"][0].Value, 40.0, 0.1)
assertApproxEqual(t, "last sdb", result["sdb"][0].Value, 70.0, 0.1)
}
+
+func TestMetricPointRepository_QueryTimeSeries_LastPerDeviceWithServerFilter(t *testing.T) {
+ setupTestDB(t)
+ ctx := context.Background()
+ projectId := uuid.New()
+ base := time.Now().UTC().Truncate(time.Hour)
+ tags := func(server, device string) map[string]string {
+ return map[string]string{"server_name": server, "device": device, "direction": "receive"}
+ }
+
+ points := []models.MetricPoint{
+ makeMetricPoint(projectId, "system.network.io", 1000, tags("web-1", "eth0"), base),
+ makeMetricPoint(projectId, "system.network.io", 1600, tags("web-1", "eth0"), base.Add(30*time.Second)),
+ makeMetricPoint(projectId, "system.network.io", 2200, tags("web-1", "eth0"), base.Add(time.Minute)),
+ makeMetricPoint(projectId, "system.network.io", 2800, tags("web-1", "eth0"), base.Add(90*time.Second)),
+ makeMetricPoint(projectId, "system.network.io", 10, tags("web-1", "lo"), base),
+ makeMetricPoint(projectId, "system.network.io", 20, tags("web-1", "lo"), base.Add(time.Minute)),
+ makeMetricPoint(projectId, "system.network.io", 99999, tags("web-2", "eth0"), base.Add(time.Minute)),
+ }
+ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {
+ t.Fatalf("InsertAsync failed: %v", err)
+ }
+
+ filters := map[string]string{"direction": "receive", "server_name": "web-1"}
+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "system.network.io", base.Add(-time.Minute), base.Add(2*time.Minute), 1, "last", filters, "device", 0)
+ if err != nil {
+ t.Fatalf("QueryTimeSeries last per device failed: %v", err)
+ }
+ if len(result) != 2 {
+ t.Fatalf("expected eth0 and lo, got %v", result)
+ }
+ eth0, lo := result["eth0"], result["lo"]
+ if len(eth0) != 2 || len(lo) != 2 {
+ t.Fatalf("expected 2 buckets per device, got eth0=%d lo=%d", len(eth0), len(lo))
+ }
+ assertApproxEqual(t, "eth0 bucket 0", eth0[0].Value, 1600, 0.1)
+ assertApproxEqual(t, "eth0 bucket 1", eth0[1].Value, 2800, 0.1)
+ assertApproxEqual(t, "lo bucket 0", lo[0].Value, 10, 0.1)
+ assertApproxEqual(t, "lo bucket 1", lo[1].Value, 20, 0.1)
+ if gap := eth0[1].Timestamp.Sub(eth0[0].Timestamp); gap != time.Minute {
+ t.Fatalf("bucket gap = %v, want 1m", gap)
+ }
+}
diff --git a/backend/app/repositories/telemetry/sqlite/endpoint.repository.go b/backend/app/repositories/telemetry/sqlite/endpoint.repository.go
index 11fdcc9a..05474e3e 100644
--- a/backend/app/repositories/telemetry/sqlite/endpoint.repository.go
+++ b/backend/app/repositories/telemetry/sqlite/endpoint.repository.go
@@ -138,9 +138,6 @@ func (r *endpoint) toModel() models.Endpoint {
return e
}
-// rootFilterClause returns a SQL fragment ("", " AND <col> = 1", " AND <col> = 0")
-// to splice into a WHERE clause based on the rootFilter param. Accepts "all" |
-// "root" | "non_root"; defaults to "all" (no filter).
type endpointRepository struct{}
func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {
@@ -309,7 +306,7 @@ func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectI
continue
}
- durations, err := fetchSortedDurations(ctx, projectId, g.Endpoint, fromDate, toDate)
+ durations, err := fetchSortedDurations(ctx, projectId, g.Endpoint, fromDate, toDate, rootFilter)
if err != nil {
return nil, 0, err
}
@@ -537,7 +534,7 @@ func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId u
var stats []models.EndpointStats
for _, g := range groups {
- durations, err := fetchSortedDurations(ctx, projectId, g.Endpoint, start, end)
+ durations, err := fetchSortedDurations(ctx, projectId, g.Endpoint, start, end, "")
if err != nil {
return nil, err
}
@@ -619,7 +616,7 @@ func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uui
stats.Apdex = row.SatisfiedTolerating / float64(row.Count)
}
- durations, err := fetchSortedDurations(ctx, projectId, endpoint, start, end)
+ durations, err := fetchSortedDurations(ctx, projectId, endpoint, start, end, "")
if err != nil {
return nil, err
}
@@ -841,9 +838,9 @@ func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId u
// --- helpers ---
-func fetchSortedDurations(ctx context.Context, projectId uuid.UUID, endpoint string, from, to time.Time) ([]float64, error) {
+func fetchSortedDurations(ctx context.Context, projectId uuid.UUID, endpoint string, from, to time.Time, rootFilter string) ([]float64, error) {
results, err := lit.SelectNamed[endpointDurationRow](db.TelemetryDB,
- "SELECT duration FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0 ORDER BY duration ASC",
+ "SELECT duration FROM endpoints WHERE project_id = :project_id AND endpoint = :endpoint AND recorded_at >= :from AND recorded_at <= :to AND is_stream = 0"+shared.RootFilterClause("is_root", rootFilter)+" ORDER BY duration ASC",
lit.P{"project_id": projectId, "endpoint": endpoint, "from": sqlitetypes.NewSQLiteTime(from), "to": sqlitetypes.NewSQLiteTime(to)})
if err != nil {
return nil, err
@@ -926,7 +923,7 @@ func getTopEndpointsByMetric(ctx context.Context, projectId uuid.UUID, from, to
var metrics []epMetric
for _, ep := range epRows {
- durations, err := fetchSortedDurations(ctx, projectId, ep.Endpoint, from, to)
+ durations, err := fetchSortedDurations(ctx, projectId, ep.Endpoint, from, to, rootFilter)
if err != nil {
return nil, err
}
diff --git a/backend/app/repositories/transactional/pg/dashboard.repository.go b/backend/app/repositories/transactional/pg/dashboard.repository.go
index 13cd9e69..3477afec 100644
--- a/backend/app/repositories/transactional/pg/dashboard.repository.go
+++ b/backend/app/repositories/transactional/pg/dashboard.repository.go
@@ -86,7 +86,8 @@ func (r *dashboardRepository) FindAssignmentsByOrganization(tx *sql.Tx, organiza
`SELECT pd.dashboard_id, pd.project_id
FROM project_dashboards pd
JOIN dashboards d ON d.id = pd.dashboard_id
- WHERE d.organization_id = :organization_id`,
+ WHERE d.organization_id = :organization_id
+ ORDER BY pd.project_id ASC, pd.position ASC, pd.dashboard_id ASC`,
lit.P{"organization_id": organizationId},
)
}
diff --git a/backend/app/repositories/transactional/sqlite/dashboard.repository.go b/backend/app/repositories/transactional/sqlite/dashboard.repository.go
index d3f9fe11..3887f951 100644
--- a/backend/app/repositories/transactional/sqlite/dashboard.repository.go
+++ b/backend/app/repositories/transactional/sqlite/dashboard.repository.go
@@ -86,7 +86,8 @@ func (r *dashboardRepository) FindAssignmentsByOrganization(tx *sql.Tx, organiza
`SELECT pd.dashboard_id, pd.project_id
FROM project_dashboards pd
JOIN dashboards d ON d.id = pd.dashboard_id
- WHERE d.organization_id = :organization_id`,
+ WHERE d.organization_id = :organization_id
+ ORDER BY pd.project_id ASC, pd.position ASC, pd.dashboard_id ASC`,
lit.P{"organization_id": organizationId},
)
}
diff --git a/backend/app/services/email.service.go b/backend/app/services/email.service.go
index 87f5d1ec..da9a4c30 100644
--- a/backend/app/services/email.service.go
+++ b/backend/app/services/email.service.go
@@ -93,6 +93,21 @@ func sanitizeHeaderValues(values []string) []string {
return out
}
+func headerAddress(raw string) string {
+ if parsed, err := netmail.ParseAddress(raw); err == nil {
+ return parsed.String()
+ }
+ return sanitizeHeaderValues([]string{raw})[0]
+}
+
+func headerAddresses(values []string) []string {
+ out := make([]string, len(values))
+ for i, v := range values {
+ out[i] = headerAddress(v)
+ }
+ return out
+}
+
func envelopeAddresses(recipients []string) []string {
out := make([]string, 0, len(recipients))
for _, r := range recipients {
@@ -125,8 +140,8 @@ func SendEmail(ctx context.Context, email Email) error {
from := config.Config.SMTPFrom
var buf bytes.Buffer
- fmt.Fprintf(&buf, "From: %s\r\n", from)
- fmt.Fprintf(&buf, "To: %s\r\n", strings.Join(recipients, ", "))
+ fmt.Fprintf(&buf, "From: %s\r\n", headerAddress(from))
+ fmt.Fprintf(&buf, "To: %s\r\n", strings.Join(headerAddresses(recipients), ", "))
fmt.Fprintf(&buf, "Subject: %s\r\n", mime.QEncoding.Encode("utf-8", subject))
fmt.Fprintf(&buf, "Date: %s\r\n", time.Now().Format(time.RFC1123Z))
buf.WriteString("MIME-Version: 1.0\r\n")
@@ -326,6 +341,18 @@ func NotificationEmail(msg models.NotificationMessage, recipients []string) Emai
if msg.RuleType != "test" && msg.RuleName != "" {
email.Footer = fmt.Sprintf("You are receiving this because the notification rule %q fired.", msg.RuleName)
}
+ email.Text = plaintextBody(msg.Body, email.URL, email.Footer)
return email
}
+
+func plaintextBody(body, url, footer string) string {
+ text := strings.TrimRight(body, "\n")
+ if url != "" && !strings.Contains(body, url) {
+ text += "\n\n" + url
+ }
+ if footer != "" {
+ text += "\n\n" + footer
+ }
+ return text
+}
diff --git a/backend/app/services/email.service_test.go b/backend/app/services/email.service_test.go
index 9d3a8374..cb92d0f9 100644
--- a/backend/app/services/email.service_test.go
+++ b/backend/app/services/email.service_test.go
@@ -146,8 +146,8 @@ func TestNotificationEmailFillsChrome(t *testing.T) {
if !strings.Contains(email.Footer, `"Critical errors"`) {
t.Errorf("footer = %q, want it to name the rule", email.Footer)
}
- if email.Text != msg.Body {
- t.Error("plaintext alternative must stay the message body")
+ if !strings.HasPrefix(email.Text, msg.Body) || !strings.Contains(email.Text, email.URL) || !strings.HasSuffix(email.Text, email.Footer) {
+ t.Errorf("plaintext = %q, want the body followed by the link and the footer", email.Text)
}
}
diff --git a/backend/app/services/email_envelope_test.go b/backend/app/services/email_envelope_test.go
index 631b2e17..cb9a7c9f 100644
--- a/backend/app/services/email_envelope_test.go
+++ b/backend/app/services/email_envelope_test.go
@@ -11,13 +11,14 @@ import (
"github.com/tracewayapp/traceway/backend/app/config"
)
-func fakeSMTP(t *testing.T) (host string, port string, got *[]string) {
+func fakeSMTP(t *testing.T) (host string, port string, got *[]string, data *[]string) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
lines := []string{}
+ body := []string{}
done := make(chan struct{})
go func() {
defer close(done)
@@ -39,6 +40,8 @@ func fakeSMTP(t *testing.T) (host string, port string, got *[]string) {
if line == "." {
inData = false
fmt.Fprint(conn, "250 OK\r\n")
+ } else {
+ body = append(body, line)
}
continue
}
@@ -61,11 +64,11 @@ func fakeSMTP(t *testing.T) (host string, port string, got *[]string) {
}()
t.Cleanup(func() { ln.Close(); <-done })
h, p, _ := net.SplitHostPort(ln.Addr().String())
- return h, p, &lines
+ return h, p, &lines, &body
}
func TestSendEmailUsesBareAddressesInTheEnvelope(t *testing.T) {
- host, port, captured := fakeSMTP(t)
+ host, port, captured, _ := fakeSMTP(t)
prev := config.Config
config.Init(&config.Cfg{
@@ -101,3 +104,39 @@ func TestSendEmailUsesBareAddressesInTheEnvelope(t *testing.T) {
}
}
}
+
+func TestSendEmailEncodesDisplayNamesInHeaders(t *testing.T) {
+ host, port, _, body := fakeSMTP(t)
+
+ prev := config.Config
+ config.Init(&config.Cfg{
+ SMTPEnabled: "true", SMTPHost: host, SMTPPort: port,
+ SMTPFrom: "Zoë Alerts <[email protected]>",
+ })
+ t.Cleanup(func() { config.Init(prev) })
+
+ err := SendEmail(context.Background(), Email{
+ To: []string{"Zoë Ops <[email protected]>", "[email protected]"},
+ Subject: "Test",
+ Template: "invitation",
+ Title: "Test",
+ Text: "test",
+ Data: invitationData{InviterName: "Dana", OrgName: "Acme"},
+ })
+ if err != nil {
+ t.Fatalf("SendEmail: %v", err)
+ }
+
+ headers := strings.Join(*body, "\n")
+ if strings.Contains(headers, "Zoë") {
+ t.Fatalf("raw UTF-8 reached a header:\n%s", headers)
+ }
+ for _, want := range []string{
+ "From: =?utf-8?q?Zo=C3=AB_Alerts?= <[email protected]>",
+ "To: =?utf-8?q?Zo=C3=AB_Ops?= <[email protected]>, <[email protected]>",
+ } {
+ if !strings.Contains(headers, want) {
+ t.Errorf("missing header line %q in:\n%s", want, headers)
+ }
+ }
+}
diff --git a/backend/app/services/email_text_test.go b/backend/app/services/email_text_test.go
new file mode 100644
index 00000000..8777d27c
--- /dev/null
+++ b/backend/app/services/email_text_test.go
@@ -0,0 +1,31 @@
+package services
+
+import (
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func TestNotificationEmailPlaintextCarriesTheLinkAndFooter(t *testing.T) {
+ msg := models.NotificationMessage{
+ Subject: "Error rate high",
+ Body: "The error rate has reached 12.0% over the last 5 minutes.\n",
+ URL: "https://traceway.example.com/issues?preset=1h",
+ RuleName: "Error rate",
+ RuleType: "error_rate",
+ Severity: models.NotificationSeverityWarning,
+ Email: &models.NotificationEmail{Template: models.EmailTemplateAlert, Alert: &models.EmailAlert{}},
+ }
+ email := NotificationEmail(msg, []string{"[email protected]"})
+ want := "The error rate has reached 12.0% over the last 5 minutes.\n\nhttps://traceway.example.com/issues?preset=1h\n\nYou are receiving this because the notification rule \"Error rate\" fired."
+ if email.Text != want {
+ t.Fatalf("plaintext:\n got %q\nwant %q", email.Text, want)
+ }
+
+ msg.Body = "Page opened, acknowledge at https://traceway.example.com/issues?preset=1h"
+ msg.RuleName = ""
+ email = NotificationEmail(msg, []string{"[email protected]"})
+ if email.Text != msg.Body {
+ t.Fatalf("a link already in the body was repeated: %q", email.Text)
+ }
+}
diff --git a/backend/app/services/sourcemap_tw.go b/backend/app/services/sourcemap_tw.go
index e71482ff..be26516b 100644
--- a/backend/app/services/sourcemap_tw.go
+++ b/backend/app/services/sourcemap_tw.go
@@ -18,7 +18,6 @@ import (
const (
twWorkers = 2
twQueueDepth = 64
- twJobTimeout = 2 * time.Minute
)
type twJob struct {
@@ -92,8 +91,7 @@ func startTWWorkers() {
}
func warmTWArtifact(job twJob) {
- ctx, cancel := context.WithTimeout(context.Background(), twJobTimeout)
- defer cancel()
+ ctx := context.Background()
mapKey := SourceMapStorageKey(job.projectId, job.base+".map")
bundleKey := SourceMapStorageKey(job.projectId, job.base)
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index 2bc2c91a..ce3d8b3d 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -93,6 +93,13 @@ func Run(opts ...Option) {
os.Exit(1)
}
+ trustedNets, proxyErr := trustedProxyNets(cfg.TrustedProxyList())
+ if proxyErr != nil {
+ fmt.Fprintln(os.Stderr, "FATAL: invalid TRUSTED_PROXIES: "+proxyErr.Error())
+ fmt.Fprintln(os.Stderr, "Use comma-separated IP addresses or CIDR ranges, for example 10.0.0.0/8,203.0.113.7")
+ os.Exit(1)
+ }
+
err := db.Init()
if err != nil {
panic(fmt.Errorf("error connecting to database: %w", err))
@@ -196,7 +203,7 @@ func Run(opts ...Option) {
panic(fmt.Errorf("invalid TRUSTED_PROXIES: %w", err))
}
if cfg.TrustedProxyHeader == "" {
- router.Use(warnOnUntrustedForwardedFor(cfg.TrustedProxyList()))
+ router.Use(warnOnUntrustedForwardedFor(trustedNets))
}
router.Use(middleware.SecurityHeaders)
@@ -330,18 +337,17 @@ func parsePorts(ports string) []string {
return out
}
-func warnOnUntrustedForwardedFor(proxies []string) gin.HandlerFunc {
- detect := newUntrustedForwarderDetector(proxies)
+func warnOnUntrustedForwardedFor(nets []*net.IPNet) gin.HandlerFunc {
+ detect := newUntrustedForwarderDetector(nets)
return func(c *gin.Context) {
if peer, first := detect(c); first {
- config.Logf("X-Forwarded-For received from %s, which is not in TRUSTED_PROXIES. The header is ignored, so per-IP rate limits and session client IPs see that address instead of the real client. If %s is your proxy or CDN, add its range to TRUSTED_PROXIES.", peer, peer)
+ config.Logf("X-Forwarded-For or X-Real-IP received from %s, which is not in TRUSTED_PROXIES. The header is ignored, so per-IP rate limits and session client IPs see that address instead of the real client. If %s is your proxy or CDN, add its range to TRUSTED_PROXIES.", peer, peer)
}
c.Next()
}
}
-func newUntrustedForwarderDetector(proxies []string) func(*gin.Context) (string, bool) {
- nets := trustedProxyNets(proxies)
+func newUntrustedForwarderDetector(nets []*net.IPNet) func(*gin.Context) (string, bool) {
var once sync.Once
return func(c *gin.Context) (string, bool) {
if c.GetHeader("X-Forwarded-For") == "" && c.GetHeader("X-Real-IP") == "" {
@@ -358,22 +364,24 @@ func newUntrustedForwarderDetector(proxies []string) func(*gin.Context) (string,
}
}
-func trustedProxyNets(proxies []string) []*net.IPNet {
+func trustedProxyNets(proxies []string) ([]*net.IPNet, error) {
var nets []*net.IPNet
for _, p := range proxies {
if _, n, err := net.ParseCIDR(p); err == nil {
nets = append(nets, n)
continue
}
- if ip := net.ParseIP(p); ip != nil {
- bits := 32
- if ip.To4() == nil {
- bits = 128
- }
- nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
+ ip := net.ParseIP(p)
+ if ip == nil {
+ return nil, fmt.Errorf("%q is not an IP address or CIDR range", p)
+ }
+ bits := 32
+ if ip.To4() == nil {
+ bits = 128
}
+ nets = append(nets, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)})
}
- return nets
+ return nets, nil
}
func containsIP(nets []*net.IPNet, ip net.IP) bool {
diff --git a/backend/cmd/run_test.go b/backend/cmd/run_test.go
index d70a73bf..aeeabab2 100644
--- a/backend/cmd/run_test.go
+++ b/backend/cmd/run_test.go
@@ -75,7 +75,11 @@ func clientIPRouter(t *testing.T, cfg *config.Cfg) *gin.Engine {
func TestUntrustedForwarderDetectorFiresOnceForPeersOutsideTheList(t *testing.T) {
gin.SetMode(gin.TestMode)
- detect := newUntrustedForwarderDetector([]string{"10.0.0.0/8", "::1"})
+ nets, err := trustedProxyNets([]string{"10.0.0.0/8", "::1"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ detect := newUntrustedForwarderDetector(nets)
check := func(peer, xff string) (string, bool) {
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
@@ -99,6 +103,25 @@ func TestUntrustedForwarderDetectorFiresOnceForPeersOutsideTheList(t *testing.T)
}
}
+func TestTrustedProxyNetsRejectsMalformedEntries(t *testing.T) {
+ nets, err := trustedProxyNets([]string{"10.0.0.0/8", "203.0.113.7", "2001:db8::1", "2001:db8::/32"})
+ if err != nil {
+ t.Fatalf("valid list rejected: %v", err)
+ }
+ if len(nets) != 4 {
+ t.Fatalf("got %d networks, want 4", len(nets))
+ }
+ if ones, bits := nets[1].Mask.Size(); ones != 32 || bits != 32 {
+ t.Fatalf("bare IPv4 mask = /%d of %d, want /32", ones, bits)
+ }
+ if ones, bits := nets[2].Mask.Size(); ones != 128 || bits != 128 {
+ t.Fatalf("bare IPv6 mask = /%d of %d, want /128", ones, bits)
+ }
+ if _, err := trustedProxyNets([]string{"10.0.0.0/8", "not-a-cidr"}); err == nil {
+ t.Fatal("malformed entry accepted")
+ }
+}
+
func TestParsePorts(t *testing.T) {
cases := map[string][]string{
"80,8082": {"80", "8082"},
diff --git a/cli/cmd/traceway/metrics.go b/cli/cmd/traceway/metrics.go
index 85e85abf..0885927b 100644
--- a/cli/cmd/traceway/metrics.go
+++ b/cli/cmd/traceway/metrics.go
@@ -2,6 +2,7 @@ package main
import (
"fmt"
+ "sort"
"strings"
"github.com/spf13/cobra"
@@ -97,12 +98,22 @@ func runMetricsQuery(cmd *cobra.Command, _ []string) error {
_, _ = fmt.Fprintf(tw, "%s\t%s\t-\t0\t-\n", r.Name, pickStr(r.Unit, "-"))
continue
}
- for group, pts := range r.Series {
+ groups := make([]string, 0, len(r.Series))
+ for group := range r.Series {
+ groups = append(groups, group)
+ }
+ sort.Strings(groups)
+ for _, group := range groups {
+ pts := r.Series[group]
latest := "-"
if len(pts) > 0 {
latest = fmt.Sprintf("%g", pts[len(pts)-1].Value)
}
- _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%s\n", r.Name, pickStr(r.Unit, "-"), group, len(pts), latest)
+ cell := group
+ if r.TruncatedGroups {
+ cell += " (truncated)"
+ }
+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%d\t%s\n", r.Name, pickStr(r.Unit, "-"), cell, len(pts), latest)
}
}
return tw.Flush()
diff --git a/cli/pkg/client/metrics.go b/cli/pkg/client/metrics.go
index 63103b7b..2d7251b9 100644
--- a/cli/pkg/client/metrics.go
+++ b/cli/pkg/client/metrics.go
@@ -48,11 +48,16 @@ type MetricQueryResult struct {
Name string `json:"name"`
Unit string `json:"unit"`
Series map[string][]TimeSeriesPoint `json:"series"`
+ // TruncatedGroups is true when a grouped query was cut to the first 200 groups.
+ TruncatedGroups bool `json:"truncatedGroups,omitempty"`
}
// QueryMetricsResponse is the upstream MetricQueryResponse.
type QueryMetricsResponse struct {
Results []MetricQueryResult `json:"results"`
+ // IntervalMinutes is the effective bucket size: the server widens the
+ // requested interval so no series exceeds 2000 points.
+ IntervalMinutes int `json:"intervalMinutes,omitempty"`
}
// QueryMetrics runs one or more metric queries against the project.
diff --git a/cli/pkg/mcpserver/tools.go b/cli/pkg/mcpserver/tools.go
index 096ba7fa..f0b972ae 100644
--- a/cli/pkg/mcpserver/tools.go
+++ b/cli/pkg/mcpserver/tools.go
@@ -76,7 +76,7 @@ func (s *server) addTools(srv *mcp.Server) {
mcp.AddTool(srv, &mcp.Tool{
Name: "query_metrics",
OutputSchema: outSchema[client.QueryMetricsResponse](),
- Description: "Query time-bucketed metric series (aggregations: avg, sum, count, min, max). There is NO quantile aggregation: latency percentiles come from list_endpoints only. Host metrics from the Traceway OTel Agent live under system.* names; runtime names include go.gc_pause, mem.used_pcnt, go.go_routines. OTLP histogram metrics are stored as two series, <name>.avg and <name>.count. An unknown name returns an empty series cleanly, so probing names is safe.",
+ Description: "Query time-bucketed metric series (aggregations: avg, sum, count, min, max). There is NO quantile aggregation: latency percentiles come from list_endpoints only. Host metrics from the Traceway OTel Agent live under system.* names; runtime names include go.gc_pause, mem.used_pcnt, go.go_routines. OTLP histogram metrics are stored as two series, <name>.avg and <name>.count. An unknown name returns an empty series cleanly, so probing names is safe. A grouped query is cut to the first 200 groups (alphabetical) and that result carries truncatedGroups: true, while the top-level intervalMinutes is the bucket size actually used after the server widens it so no series exceeds 2000 points.",
Annotations: readOnly(),
}, s.queryMetrics)
diff --git a/cli/pkg/mcpserver/tools_metrics.go b/cli/pkg/mcpserver/tools_metrics.go
index e5a03116..87877da1 100644
--- a/cli/pkg/mcpserver/tools_metrics.go
+++ b/cli/pkg/mcpserver/tools_metrics.go
@@ -21,7 +21,7 @@ type metricQueryIn struct {
type queryMetricsIn struct {
projectIn
timeRangeIn
- IntervalMinutes int `json:"interval_minutes,omitempty" jsonschema:"Bucket size in minutes. Default 0 lets the server pick. Read down the buckets for the step where a value jumps."`
+ IntervalMinutes int `json:"interval_minutes,omitempty" jsonschema:"Bucket size in minutes. Default 0 lets the server pick. The server may widen it so no series exceeds 2000 points; the effective value is returned as intervalMinutes. Read down the buckets for the step where a value jumps."`
Queries []metricQueryIn `json:"queries" jsonschema:"One or more metric queries to run over the same window."`
}
diff --git a/cli/test/contract/testdata/metrics-query.schema.txt b/cli/test/contract/testdata/metrics-query.schema.txt
index 7b12f9d9..743f3f41 100644
--- a/cli/test/contract/testdata/metrics-query.schema.txt
+++ b/cli/test/contract/testdata/metrics-query.schema.txt
@@ -1,3 +1,4 @@
+intervalMinutes: number
results[].name: string
results[].series.__all__[].timestamp: string
results[].series.__all__[].value: number
diff --git a/docs/pages/learn/organization-overview.mdx b/docs/pages/learn/organization-overview.mdx
index 3a24d946..0b0bfd83 100644
--- a/docs/pages/learn/organization-overview.mdx
+++ b/docs/pages/learn/organization-overview.mdx
@@ -40,7 +40,7 @@ The strip across the top is the summary you read first.
| **Issues · 24h** | Distinct issues seen across all projects in the last 24 hours; opens the Issues tab |
| **Active response** | Open on-call pages plus monitors currently down; opens the Monitors tab |
-The whole page refreshes itself every minute, and **Refresh** forces it. A refresh that fails leaves the last good snapshot on screen with a warning rather than blanking the page, and if one project's telemetry cannot be read the others still render.
+The Overview tab refreshes itself every minute, and **Refresh** forces it. A refresh that fails leaves the last good snapshot on screen with a warning rather than blanking the page, and on every tab, if one project's telemetry cannot be read the others still render with a notice.
## Instances
diff --git a/docs/pages/server/local-setup.mdx b/docs/pages/server/local-setup.mdx
index 04a8fe2c..efd7bba6 100644
--- a/docs/pages/server/local-setup.mdx
+++ b/docs/pages/server/local-setup.mdx
@@ -4,10 +4,10 @@ This guide walks you through setting up Traceway on your local machine for devel
## Prerequisites
-- **Go** 1.25 or later
-- **Node.js** 18+ and npm
-- **ClickHouse** (for telemetry storage)
-- **PostgreSQL** (for user and project data)
+- **Go** 1.26 (the `toolchain` line in `backend/go.mod` is the exact version)
+- **Node.js** 22 and npm (`frontend/package.json` pins `22.x` and the repo sets `engine-strict`)
+- Nothing else for the default build: both databases are SQLite files created on first start
+- **ClickHouse** and **PostgreSQL** only when building with `-tags "transactional_pg telemetry_ch"`
## Database Setup
diff --git a/docs/pages/server/upgrade-request-limits.mdx b/docs/pages/server/upgrade-request-limits.mdx
index 2df8a057..0395f7ce 100644
--- a/docs/pages/server/upgrade-request-limits.mdx
+++ b/docs/pages/server/upgrade-request-limits.mdx
@@ -18,7 +18,7 @@ Symptoms after the upgrade:
- Public status pages answer `429` once one proxy address exceeds 30 requests a minute. Acknowledge links and CLI device logins hit their per-IP limits the same way.
- Sessions show the proxy's address as `client.ip`.
-- The server log contains a line starting with `X-Forwarded-For received from <address>, which is not in TRUSTED_PROXIES`. That address is the hop you need to list.
+- The server log contains a line starting with `X-Forwarded-For or X-Real-IP received from <address>, which is not in TRUSTED_PROXIES`. That address is the hop you need to list.
Fix: set `TRUSTED_PROXIES` to every hop in the chain, not just the outermost one. The value replaces the defaults, so include the private range your ingress uses as well:
@@ -54,7 +54,7 @@ The ingest admission gate (`INGEST_MAX_CONCURRENT`, default 2 x CPU cores with a
## Server timeouts
-The server now closes connections whose headers or body do not finish arriving. Headers must arrive within 15 seconds. Every request body has a progress deadline: no more than 30 seconds between bytes, 10 minutes in total. Routes that take large bodies have their own budget: uploads may take up to 30 minutes as long as data keeps flowing, `/api/report` up to 5 minutes, OTLP up to 2 minutes. A client that averages under 1 KB/s after the first 20 seconds is cut off with `408`; a body that has fully arrived is never rejected for being slow. Idle keep-alive connections are closed after 2 minutes.
+The server now closes connections whose headers or body do not finish arriving. Headers must arrive within 15 seconds. Every request body has a progress deadline: no more than 30 seconds between bytes, 10 minutes in total. Routes that take large bodies have their own budget: uploads may take up to 30 minutes as long as data keeps flowing, `/api/report` up to 5 minutes and OTLP up to 2 minutes, both with 20 seconds between bytes instead of 30. Time spent waiting in an admission gate does not count against any of these. A client that averages under 1 KB/s after the first 20 seconds is cut off with `408`; a body that has fully arrived is never rejected for being slow. Idle keep-alive connections are closed after 2 minutes.
## Public status pages in iframes
@@ -62,7 +62,7 @@ Every response now carries `X-Frame-Options: DENY` and a `frame-ancestors 'none'
## Metric query limits
-`POST /api/metrics/query` enforces: at most 50 queries per request and 20 tag filters per query, a time range of at most 731 days with `to` after `from` (`422`), buckets widened so no series exceeds 2000 points, at most 200 groups per query (the result carries `truncatedGroups: true` when cut), and a 30-second deadline for the whole request that answers `504`. Dashboards built in the UI stay well inside these limits.
+`POST /api/metrics/query` enforces: at most 50 queries per request and 20 tag filters per query, a time range of at most 731 days with `to` after `from` (`422`), buckets widened so no series exceeds 2000 points (the response reports the effective `intervalMinutes`), at most 200 groups per query (the result carries `truncatedGroups: true` when cut), and a 30-second deadline for the whole request that answers `504`. Dashboards built in the UI stay well inside these limits.
## Transactional requests
diff --git a/examples/devtesting-embedded/README.md b/examples/devtesting-embedded/README.md
index 91c8fb35..d0a1daf7 100644
--- a/examples/devtesting-embedded/README.md
+++ b/examples/devtesting-embedded/README.md
@@ -27,7 +27,7 @@ ORCAROUTER_MODEL=orcarouter/auto
# OPENROUTER_MODEL=anthropic/claude-sonnet-5
```
-When `ORCAROUTER_API_KEY` is set the chat routes through [OrcaRouter](https://www.orcarouter.ai) (`https://api.orcarouter.ai/v1`); otherwise it falls back to OpenRouter. It also runs gateway-level, zero-trust security for AI agents on the same endpoint — screening every prompt/response and governing every tool call on a default-deny basis, with no application code changes.
+When `ORCAROUTER_API_KEY` is set the chat routes through [OrcaRouter](https://www.orcarouter.ai) (`https://api.orcarouter.ai/v1`); otherwise it falls back to OpenRouter.
How it maps to Traceway:
diff --git a/examples/devtesting-embedded/ai.go b/examples/devtesting-embedded/ai.go
index 2fca4f27..14ee9819 100644
--- a/examples/devtesting-embedded/ai.go
+++ b/examples/devtesting-embedded/ai.go
@@ -540,14 +540,23 @@ type chatRequest struct {
} `json:"messages"`
}
-func registerAIChatRoutes(router *gin.Engine, svc *otelService) {
- model := os.Getenv("ORCAROUTER_MODEL")
- if model == "" {
- model = os.Getenv("OPENROUTER_MODEL")
+// defaultModel mirrors the gateway selection in callGateway, so the fallback
+// model always belongs to the provider that will actually serve the request.
+func defaultModel() string {
+ if os.Getenv("ORCAROUTER_API_KEY") != "" {
+ if model := os.Getenv("ORCAROUTER_MODEL"); model != "" {
+ return model
+ }
+ return "orcarouter/auto"
}
- if model == "" {
- model = "orcarouter/auto"
+ if model := os.Getenv("OPENROUTER_MODEL"); model != "" {
+ return model
}
+ return "anthropic/claude-sonnet-5"
+}
+
+func registerAIChatRoutes(router *gin.Engine, svc *otelService) {
+ model := defaultModel()
router.POST("/api/ai/chat", func(c *gin.Context) {
if os.Getenv("ORCAROUTER_API_KEY") == "" && os.Getenv("OPENROUTER_API_KEY") == "" {
diff --git a/examples/devtesting-embedded/devtesting-embedded b/examples/devtesting-embedded/devtesting-embedded
deleted file mode 100755
index 01aec00c..00000000
Binary files a/examples/devtesting-embedded/devtesting-embedded and /dev/null differ
diff --git a/examples/devtesting-embedded/go.mod b/examples/devtesting-embedded/go.mod
index e6787cff..3f32b305 100644
--- a/examples/devtesting-embedded/go.mod
+++ b/examples/devtesting-embedded/go.mod
@@ -23,25 +23,25 @@ require (
github.com/ClickHouse/clickhouse-go/v2 v2.42.0 // indirect
github.com/andybalholm/brotli v1.2.0 // indirect
github.com/apache/arrow-go/v18 v18.5.1 // indirect
- github.com/aws/aws-sdk-go-v2 v1.41.1 // indirect
- github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
+ github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect
+ github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
github.com/aws/aws-sdk-go-v2/config v1.32.7 // indirect
github.com/aws/aws-sdk-go-v2/credentials v1.19.7 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect
- github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect
- github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
- github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect
- github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect
- github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 // indirect
+ github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect
+ github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect
+ github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 // indirect
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect
- github.com/aws/smithy-go v1.24.0 // indirect
+ github.com/aws/smithy-go v1.24.2 // indirect
github.com/bytedance/gopkg v0.1.4 // indirect
github.com/bytedance/sonic v1.15.0 // indirect
github.com/bytedance/sonic/loader v0.5.1 // indirect
@@ -101,7 +101,7 @@ require (
github.com/pierrec/lz4/v4 v4.1.25 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
- github.com/quic-go/quic-go v0.59.0 // indirect
+ github.com/quic-go/quic-go v0.59.1 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/segmentio/asm v1.2.1 // indirect
github.com/segmentio/encoding v0.5.4 // indirect
@@ -129,20 +129,20 @@ require (
go.tracewayapp.com/tracewaygin v1.0.4 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/arch v0.25.0 // indirect
- golang.org/x/crypto v0.51.0 // indirect
+ golang.org/x/crypto v0.53.0 // indirect
golang.org/x/exp v0.0.0-20260112195511-716be5621a96 // indirect
- golang.org/x/mod v0.35.0 // indirect
- golang.org/x/net v0.55.0 // indirect
+ golang.org/x/mod v0.37.0 // indirect
+ golang.org/x/net v0.56.0 // indirect
golang.org/x/oauth2 v0.36.0 // indirect
- golang.org/x/sync v0.20.0 // indirect
- golang.org/x/sys v0.45.0 // indirect
- golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa // indirect
- golang.org/x/text v0.37.0 // indirect
- golang.org/x/tools v0.44.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
+ golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57 // indirect
+ golang.org/x/text v0.39.0 // indirect
+ golang.org/x/tools v0.47.0 // indirect
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect
- google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 // indirect
- google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
- google.golang.org/grpc v1.81.1 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 // indirect
+ google.golang.org/grpc v1.82.1 // indirect
google.golang.org/protobuf v1.36.11 // indirect
modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
modernc.org/libc v1.41.0 // indirect
@@ -154,6 +154,6 @@ require (
)
replace (
- github.com/tracewayapp/traceway/backend => /Users/dusanstanojevic/Documents/workspace/traceway/backend
- github.com/tracewayapp/traceway/cli => /Users/dusanstanojevic/Documents/workspace/traceway/cli
+ github.com/tracewayapp/traceway/backend => ../../backend
+ github.com/tracewayapp/traceway/cli => ../../cli
)
diff --git a/examples/devtesting-embedded/go.sum b/examples/devtesting-embedded/go.sum
index 7d1d8243..5669532e 100644
--- a/examples/devtesting-embedded/go.sum
+++ b/examples/devtesting-embedded/go.sum
@@ -18,34 +18,34 @@ github.com/apache/arrow-go/v18 v18.5.1 h1:yaQ6zxMGgf9YCYw4/oaeOU3AULySDlAYDOcnr4
github.com/apache/arrow-go/v18 v18.5.1/go.mod h1:OCCJsmdq8AsRm8FkBSSmYTwL/s4zHW9CqxeBxEytkNE=
github.com/apache/thrift v0.22.0 h1:r7mTJdj51TMDe6RtcmNdQxgn9XcyfGDOzegMDRg47uc=
github.com/apache/thrift v0.22.0/go.mod h1:1e7J/O1Ae6ZQMTYdy9xa3w9k+XHWPfRvdPyJeynQ+/g=
-github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=
-github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
-github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
+github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
+github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
+github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY=
github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY=
github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8=
github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY=
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U=
-github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik=
-github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
+github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
+github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
-github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
-github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
-github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8/go.mod h1:FsTpJtvC4U1fyDXk7c71XoDv3HlRm8V3NiYLeYLh5YE=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY=
-github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 h1:bGeHBsGZx0Dvu/eJC0Lh9adJa3M1xREcndxLNZlve2U=
-github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17/go.mod h1:dcW24lbU0CzHusTE8LLHhRLI42ejmINN8Lcr22bwh/g=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0 h1:oeu8VPlOre74lBA/PMhxa5vewaMIMmILM+RraSyB8KA=
-github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0/go.mod h1:5jggDlZ2CLQhwJBiZJb4vfk4f0GxWdEDruWKEJ1xOdo=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 h1:rWyie/PxDRIdhNf4DzRk0lvjVOqFJuNnO8WwaIRVxzQ=
+github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22/go.mod h1:zd/JsJ4P7oGfUhXn1VyLqaRZwPmZwg44Jf2dS84Dm3Y=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY=
+github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM=
+github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3xgIJMSC8S6hEVq+38DcvUlgFY0FM6mSI5oto=
+github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM=
+github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo=
+github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y=
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M=
github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk=
@@ -54,8 +54,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLz
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ=
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ=
-github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
-github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
+github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
+github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
github.com/bytedance/gopkg v0.1.4 h1:oZnQwnX82KAIWb7033bEwtxvTqXcYMxDBaQxo5JJHWM=
github.com/bytedance/gopkg v0.1.4/go.mod h1:v1zWfPm21Fb+OsyXN2VAHdL6TBb2L88anLQgdyje6R4=
github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE=
@@ -257,8 +257,8 @@ github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII=
-github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw=
-github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
+github.com/quic-go/quic-go v0.59.1 h1:0Gmua0HW1Tv7ANR7hUYwRyD0MG5OJfgvYSZasGZzBic=
+github.com/quic-go/quic-go v0.59.1/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
@@ -371,29 +371,29 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
-golang.org/x/crypto v0.51.0 h1:IBPXwPfKxY7cWQZ38ZCIRPI50YLeevDLlLnyC5wRGTI=
-golang.org/x/crypto v0.51.0/go.mod h1:8AdwkbraGNABw2kOX6YFPs3WM22XqI4EXEd8g+x7Oc8=
+golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
+golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
golang.org/x/exp v0.0.0-20260112195511-716be5621a96 h1:Z/6YuSHTLOHfNFdb8zVZomZr7cqNgTJvA8+Qz75D8gU=
golang.org/x/exp v0.0.0-20260112195511-716be5621a96/go.mod h1:nzimsREAkjBCIEFtHiYkrJyT+2uy9YZJB7H1k68CXZU=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
-golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
-golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
-golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
-golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
+golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
+golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
-golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -404,23 +404,23 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
-golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
-golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa h1:efT73AJZfAAUV7SOip6pWGkwJDzIGiKBZGVzHYa+ve4=
-golang.org/x/telemetry v0.0.0-20260409153401-be6f6cb8b1fa/go.mod h1:kHjTxDEnAu6/Nl9lDkzjWpR+bmKfxeiRuSDlsMb70gE=
+golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
+golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57 h1:nwGZBCt+FnXUrGsj5vjzAsEmkcaFvd82BbOjECiFYZc=
+golang.org/x/telemetry v0.0.0-20260625142307-59b4966ccb57/go.mod h1:3AWMyWHS+caVoiEXpiq6+tzKA40J4vQT3MYr80ZtQpc=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
-golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
-golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
+golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
+golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
-golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
-golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -429,12 +429,12 @@ golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhS
golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90=
gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=
gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=
-google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9 h1:VPWxll4HlMw1Vs/qXtN7BvhZqsS9cdAittCNvVENElA=
-google.golang.org/genproto/googleapis/api v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:7QBABkRtR8z+TEnmXTqIqwJLlzrZKVfAUm7tY3yGv0M=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
-google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ=
-google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
+google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478 h1:yQugLulqltosq0B/f8l4w9VryjV+N/5gcW0jQ3N8Qec=
+google.golang.org/genproto/googleapis/api v0.0.0-20260414002931-afd174a4e478/go.mod h1:C6ADNqOxbgdUUeRTU+LCHDPB9ttAMCTff6auwCVa4uc=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478 h1:RmoJA1ujG+/lRGNfUnOMfhCy5EipVMyvUE+KNbPbTlw=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260414002931-afd174a4e478/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/grpc v1.82.1 h1:NnAxzGRA0677vCa4BUkOAnO5+FfQqVl9iUXeD0IqcGE=
+google.golang.org/grpc v1.82.1/go.mod h1:yzTZ1TB1Z3SG+LIYaI+WiE8D5+PZ3ArnrSp8zF3+/ZA=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 750de5b6..4892db48 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -65,6 +65,9 @@
"typescript-eslint": "^8.48.1",
"vite": "^7.2.6",
"vitest": "^4.1.9"
+ },
+ "engines": {
+ "node": "22.x"
}
},
"node_modules/@asamuzakjp/css-color": {
diff --git a/frontend/src/lib/components/dashboard/widget-renderer.svelte b/frontend/src/lib/components/dashboard/widget-renderer.svelte
index dd123a3d..ff8e7d68 100644
--- a/frontend/src/lib/components/dashboard/widget-renderer.svelte
+++ b/frontend/src/lib/components/dashboard/widget-renderer.svelte
@@ -49,6 +49,7 @@
let loading = $state(true);
let singleValue = $state<number | null>(null);
let resolvedUnit = $state('');
+ let truncated = $state(false);
let loadSequence = 0;
const colors = [
@@ -140,6 +141,7 @@
{ projectId: projectsState.currentProjectId ?? undefined }
);
if (sequence !== loadSequence) return;
+ truncated = response.results.some((r) => r.truncatedGroups);
const units = new SvelteSet<string>();
const usedKeys = new SvelteSet<string>();
@@ -368,4 +370,8 @@
{/each}
</div>
{/if}
+
+ {#if truncated && !loading}
+ <div class="px-2 pt-1 text-xs text-muted-foreground">Showing the first 200 groups</div>
+ {/if}
</div>
diff --git a/frontend/src/lib/components/organization-project-switcher.svelte b/frontend/src/lib/components/organization-project-switcher.svelte
index b37a8f14..705ca29d 100644
--- a/frontend/src/lib/components/organization-project-switcher.svelte
+++ b/frontend/src/lib/components/organization-project-switcher.svelte
@@ -99,7 +99,7 @@
<DropdownMenu.Separator />
{/if}
<DropdownMenu.Group>
- {#if group.projects.length !== 1}
+ {#if group.projects.length > 1}
<DropdownMenu.Item
onclick={() => selectOrganization(group.organization.id)}
class="cursor-pointer py-2"
diff --git a/frontend/src/lib/components/ui/endpoint-filter/endpoint-filter.svelte b/frontend/src/lib/components/ui/endpoint-filter/endpoint-filter.svelte
index af1116a3..a1610b9b 100644
--- a/frontend/src/lib/components/ui/endpoint-filter/endpoint-filter.svelte
+++ b/frontend/src/lib/components/ui/endpoint-filter/endpoint-filter.svelte
@@ -8,12 +8,14 @@
rootValue?: string;
methodValue?: string;
class?: string;
+ onChange?: (value: string) => void;
};
let {
rootValue = $bindable('all'),
methodValue = $bindable('all'),
- class: className = 'sm:rounded-none sm:border-r-0'
+ class: className = 'sm:rounded-none sm:border-r-0',
+ onChange
}: Props = $props();
const METHOD_COLORS: Record<string, string> = {
@@ -31,7 +33,7 @@
);
</script>
-<Select.Root type="single" bind:value={methodValue}>
+<Select.Root type="single" bind:value={methodValue} onValueChange={(v) => onChange?.(v ?? '')}>
<Select.Trigger
aria-label="Filter by HTTP method"
class={cn('h-9 w-[130px] shrink-0 shadow-none', className)}
@@ -58,4 +60,8 @@
</Select.Content>
</Select.Root>
-<RootFilter bind:value={rootValue} class={cn('h-9 w-[110px] shrink-0 shadow-none', className)} />
+<RootFilter
+ bind:value={rootValue}
+ class={cn('h-9 w-[110px] shrink-0 shadow-none', className)}
+ {onChange}
+/>
diff --git a/frontend/src/lib/components/ui/root-filter/root-filter.svelte b/frontend/src/lib/components/ui/root-filter/root-filter.svelte
index d88f7fe8..045ab387 100644
--- a/frontend/src/lib/components/ui/root-filter/root-filter.svelte
+++ b/frontend/src/lib/components/ui/root-filter/root-filter.svelte
@@ -5,9 +5,10 @@
type Props = {
value?: string;
class?: string;
+ onChange?: (value: string) => void;
};
- let { value = $bindable('all'), class: className = 'w-[120px]' }: Props = $props();
+ let { value = $bindable('all'), class: className = 'w-[120px]', onChange }: Props = $props();
</script>
<ToolbarSelect
@@ -15,4 +16,5 @@
options={ROOT_FILTER_OPTIONS}
class={className}
ariaLabel="Filter by root or non-root"
+ {onChange}
/>
diff --git a/frontend/src/lib/types/dashboard.ts b/frontend/src/lib/types/dashboard.ts
index 5ca73a32..5fe0d830 100644
--- a/frontend/src/lib/types/dashboard.ts
+++ b/frontend/src/lib/types/dashboard.ts
@@ -82,10 +82,12 @@ export type MetricQueryResult = {
name: string;
unit: string;
series: Record<string, TimeSeriesPoint[]>;
+ truncatedGroups?: boolean;
};
export type MetricQueryResponse = {
results: MetricQueryResult[];
+ intervalMinutes?: number;
};
export type ExplorerMetricsTab = 'application' | 'stats' | 'server' | 'explorer';
diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelte
index f53190db..0add1b93 100644
--- a/frontend/src/routes/endpoints/+page.svelte
+++ b/frontend/src/routes/endpoints/+page.svelte
@@ -372,6 +372,11 @@
loadData(true);
}
+ function applyFilterChange() {
+ page = 1;
+ loadData(true);
+ }
+
function handleChartRangeSelect(from: Date, to: Date) {
selectedPreset = null;
fromDate = new CalendarDate(from.getFullYear(), from.getMonth() + 1, from.getDate());
@@ -460,7 +465,11 @@
disabled={loading}
>
{#snippet pillEnd()}
- <EndpointFilter bind:rootValue={rootFilter} bind:methodValue={methodFilter} />
+ <EndpointFilter
+ bind:rootValue={rootFilter}
+ bind:methodValue={methodFilter}
+ onChange={applyFilterChange}
+ />
{/snippet}
</SearchBar>
diff --git a/frontend/src/routes/organization/+page.svelte b/frontend/src/routes/organization/+page.svelte
index 0264c919..e46eb84d 100644
--- a/frontend/src/routes/organization/+page.svelte
+++ b/frontend/src/routes/organization/+page.svelte
@@ -49,9 +49,12 @@
: projectsState.projects.filter((project) => project.organizationId === currentOrganizationId)
);
- const singleProject = $derived(
- organizationProjects.length === 1 ? organizationProjects[0] : null
- );
+ const redirectHref = $derived.by(() => {
+ if (currentOrganizationId === null) return null;
+ if (organizationProjects.length === 1) return `/?projectId=${organizationProjects[0].id}`;
+ if (organizationProjects.length === 0) return '/setup';
+ return null;
+ });
const hasBackendProjects = $derived(
organizationProjects.some((project) => isBackendFramework(project.framework))
@@ -81,8 +84,8 @@
$effect(() => {
const organizationId = currentOrganizationId;
if (organizationId === null) return;
- if (projectsState.loaded && singleProject) {
- gotoHref(`/?projectId=${singleProject.id}`, { replaceState: true });
+ if (projectsState.loaded && redirectHref) {
+ gotoHref(redirectHref, { replaceState: true });
return;
}
if (
@@ -102,7 +105,7 @@
});
</script>
-{#if !projectsState.loaded || singleProject}
+{#if !projectsState.loaded || redirectHref}
<div class="flex h-48 items-center justify-center">
<LoadingCircle size="xlg" />
</div>
diff --git a/frontend/src/routes/organization/issues-tab.svelte b/frontend/src/routes/organization/issues-tab.svelte
index 25bc61d8..09375317 100644
--- a/frontend/src/routes/organization/issues-tab.svelte
+++ b/frontend/src/routes/organization/issues-tab.svelte
@@ -5,6 +5,7 @@
import * as Table from '$lib/components/ui/table';
import TableContainer from '$lib/components/traceway/table-container.svelte';
import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';
+ import PartialNotice from './partial-notice.svelte';
import { getErrorMessage } from '$lib/utils/errors';
import { formatRelativeTimeAgo } from '$lib/utils/formatters';
import { createRowClickHandler } from '$lib/utils/navigation';
@@ -23,6 +24,7 @@
let issues = $state<OrgIssueRow[]>([]);
let totalGroups = $state(0);
+ let partial = $state(false);
let loading = $state(true);
let error = $state('');
let loadGeneration = 0;
@@ -31,12 +33,14 @@
const generation = ++loadGeneration;
loading = true;
error = '';
+ partial = false;
api
.get(`/organizations/${orgId}/overview/issues`)
.then((response) => {
if (generation !== loadGeneration) return;
issues = response.issues || [];
totalGroups = response.totalGroups || 0;
+ partial = response.partial === true;
})
.catch((cause) => {
if (generation !== loadGeneration) return;
@@ -72,6 +76,10 @@
{/if}
</div>
+ {#if partial}
+ <PartialNotice />
+ {/if}
+
{#if loading}
<div class="flex h-48 items-center justify-center">
<LoadingCircle size="xlg" />
diff --git a/frontend/src/routes/organization/monitors-tab.svelte b/frontend/src/routes/organization/monitors-tab.svelte
index f6aff555..24f05fc5 100644
--- a/frontend/src/routes/organization/monitors-tab.svelte
+++ b/frontend/src/routes/organization/monitors-tab.svelte
@@ -11,6 +11,7 @@
import { Badge } from '$lib/components/ui/badge';
import TableContainer from '$lib/components/traceway/table-container.svelte';
import ErrorRetryBox from '$lib/components/traceway/error-retry-box.svelte';
+ import PartialNotice from './partial-notice.svelte';
import CheckStatusBadge from '$lib/components/synthetics/check-status-badge.svelte';
import MonitorTypeBadge from '$lib/components/synthetics/monitor-type-badge.svelte';
import {
@@ -36,11 +37,14 @@
let checks = $state<OrgMonitorRow[]>([]);
let checksLoading = $state(true);
let checksError = $state('');
+ let checksPartial = $state(false);
+ let checksGeneration = 0;
let incidents = $state<OrgIncident[]>([]);
let incidentsLoading = $state(true);
let incidentsError = $state('');
- let loadGeneration = 0;
+ let incidentsGeneration = 0;
+ let activeOrganizationId: number | null = null;
const SORT_STORAGE_KEY = 'org-monitors';
const initialSort = getSortState(SORT_STORAGE_KEY, { field: 'status', direction: 'asc' });
@@ -50,15 +54,17 @@
async function loadChecks(orgId: number, generation: number) {
checksLoading = true;
checksError = '';
+ checksPartial = false;
try {
const response = await api.get(`/organizations/${orgId}/overview/monitors`);
- if (generation !== loadGeneration) return;
+ if (generation !== checksGeneration) return;
checks = response.checks || [];
+ checksPartial = response.partial === true;
} catch (e) {
- if (generation !== loadGeneration) return;
+ if (generation !== checksGeneration) return;
checksError = getErrorMessage(e) || 'Failed to load monitors';
} finally {
- if (generation === loadGeneration) checksLoading = false;
+ if (generation === checksGeneration) checksLoading = false;
}
}
@@ -67,29 +73,35 @@
incidentsError = '';
try {
const response = await api.get(`/organizations/${orgId}/incidents`);
- if (generation !== loadGeneration) return;
+ if (generation !== incidentsGeneration) return;
incidents = response.incidents || [];
} catch (e) {
- if (generation !== loadGeneration) return;
+ if (generation !== incidentsGeneration) return;
incidentsError = getErrorMessage(e) || 'Failed to load incidents';
} finally {
- if (generation === loadGeneration) incidentsLoading = false;
+ if (generation === incidentsGeneration) incidentsLoading = false;
}
}
$effect(() => {
const orgId = organizationId;
- const generation = ++loadGeneration;
- loadChecks(orgId, generation);
- loadIncidents(orgId, generation);
+ if (activeOrganizationId !== orgId) {
+ activeOrganizationId = orgId;
+ checks = [];
+ checksError = '';
+ incidents = [];
+ incidentsError = '';
+ }
+ loadChecks(orgId, ++checksGeneration);
+ loadIncidents(orgId, ++incidentsGeneration);
});
function retryChecks() {
- loadChecks(organizationId, ++loadGeneration);
+ loadChecks(organizationId, ++checksGeneration);
}
function retryIncidents() {
- loadIncidents(organizationId, ++loadGeneration);
+ loadIncidents(organizationId, ++incidentsGeneration);
}
function handleSort(field: SortField) {
@@ -147,6 +159,9 @@
<div class="space-y-6">
<section class="space-y-3">
+ {#if checksPartial}
+ <PartialNotice />
+ {/if}
{#if checksLoading}
<div class="flex h-48 items-center justify-center">
<LoadingCircle size="xlg" />
diff --git a/frontend/src/routes/organization/overview-tab.svelte b/frontend/src/routes/organization/overview-tab.svelte
index 7702c597..531691f7 100644
--- a/frontend/src/routes/organization/overview-tab.svelte
+++ b/frontend/src/routes/organization/overview-tab.svelte
@@ -16,6 +16,7 @@
import Sparkline from '$lib/components/dashboard/sparkline.svelte';
import type { MetricTrendPoint } from '$lib/types/dashboard';
import type { OncallPage } from '$lib/state/oncall.svelte';
+ import PartialNotice from './partial-notice.svelte';
import {
Activity,
ArrowDown,
@@ -626,14 +627,11 @@
</div>
{#if serversPartial || (serversError && servers.length > 0)}
- <div
- class="flex items-center gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 px-4 py-2.5 text-sm text-amber-700 dark:text-amber-300"
- >
- <TriangleAlert class="size-4 shrink-0" />
- {serversPartial
+ <PartialNotice
+ message={serversPartial
? 'Some projects could not be read. The instances shown are still current.'
: 'The last refresh failed. Showing the most recent snapshot.'}
- </div>
+ />
{/if}
{#if serversLoading && servers.length === 0}
diff --git a/frontend/src/routes/organization/partial-notice.svelte b/frontend/src/routes/organization/partial-notice.svelte
new file mode 100644
index 00000000..57b7ad46
--- /dev/null
+++ b/frontend/src/routes/organization/partial-notice.svelte
@@ -0,0 +1,14 @@
+<script lang="ts">
+ import { TriangleAlert } from '@lucide/svelte';
+
+ let {
+ message = 'Some projects could not be read. The data shown is still current.'
+ }: { message?: string } = $props();
+</script>
+
+<div
+ class="flex items-center gap-2 rounded-lg border border-amber-500/25 bg-amber-500/5 px-4 py-2.5 text-sm text-amber-700 dark:text-amber-300"
+>
+ <TriangleAlert class="size-4 shrink-0" />
+ {message}
+</div>
diff --git a/frontend/src/routes/tasks/+page.svelte b/frontend/src/routes/tasks/+page.svelte
index ca760932..9e7e6a68 100644
--- a/frontend/src/routes/tasks/+page.svelte
+++ b/frontend/src/routes/tasks/+page.svelte
@@ -11,7 +11,7 @@
import { PaginationFooter } from '$lib/components/ui/pagination-footer';
import { TimeRangePicker } from '$lib/components/ui/time-range-picker';
import { SearchBar } from '$lib/components/ui/search-bar';
- import { RootFilter } from '$lib/components/ui/root-filter';
+ import { RootFilter, isRootFilterValue } from '$lib/components/ui/root-filter';
import { NonRootChip } from '$lib/components/ui/non-root-chip';
import { CalendarDate } from '@internationalized/date';
import { browser } from '$app/environment';
@@ -68,9 +68,10 @@
function readSearchAndFilterFromUrl() {
if (!browser) return { search: '', rootFilter: 'all' };
const params = new URLSearchParams(window.location.search);
+ const rootParam = params.get('rootFilter');
return {
search: params.get('search') || '',
- rootFilter: params.get('rootFilter') || 'all'
+ rootFilter: isRootFilterValue(rootParam) ? rootParam : 'all'
};
}
@@ -99,12 +100,15 @@
function handlePopState() {
const urlParams = parseTimeRangeFromUrl(timezone);
const range = getResolvedTimeRange(urlParams, timezone);
+ const searchState = readSearchAndFilterFromUrl();
selectedPreset = urlParams.preset;
fromDate = dateToCalendarDate(range.from, timezone);
fromTime = dateToTimeString(range.from, timezone);
toDate = dateToCalendarDate(range.to, timezone);
toTime = dateToTimeString(range.to, timezone);
+ searchQuery = searchState.search;
+ rootFilter = searchState.rootFilter;
page = 1;
loadData(false);
@@ -230,6 +234,11 @@
loadData(true);
}
+ function applyFilterChange() {
+ page = 1;
+ loadData(true);
+ }
+
onMount(() => {
// Add popstate listener for back/forward navigation
window.addEventListener('popstate', handlePopState);
@@ -269,6 +278,7 @@
{#snippet pillEnd()}
<RootFilter
bind:value={rootFilter}
+ onChange={applyFilterChange}
class="h-9 w-[110px] shrink-0 shadow-none sm:rounded-none sm:border-r-0"
/>
{/snippet}