Skip to content

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

feat: smarter health check (#179)

narrow-adventurea7ebd1cdad7b
diff --git a/backend/app/cache/project_cache.go b/backend/app/cache/project_cache.go
index 7b3bcedd..df2fec12 100644
--- a/backend/app/cache/project_cache.go
+++ b/backend/app/cache/project_cache.go
@@ -106,6 +106,8 @@ func (c *projectCache) UpdateProject(proj *models.Project) {
}
cached.Name = proj.Name
cached.Framework = proj.Framework
+ cached.DropHealthyHealthchecks = proj.DropHealthyHealthchecks
+ cached.HealthcheckPaths = proj.HealthcheckPaths
}
func (c *projectCache) RemoveProject(id uuid.UUID) {
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index a05e6222..d94ae2d3 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -58,13 +58,18 @@ func (e clientController) Report(c *gin.Context) {
return
}
- if project, exists := c.Get(middleware.ProjectContextKey); exists {
- if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {
- if !hooks.CanReport(*p.OrganizationId) {
- monitoring.RecordRateLimited(*p.OrganizationId)
- c.AbortWithStatus(http.StatusTooManyRequests)
- return
- }
+ var project *models.Project
+ if projectAsAny, exists := c.Get(middleware.ProjectContextKey); exists {
+ if p, ok := projectAsAny.(*models.Project); ok {
+ project = p
+ }
+ }
+
+ if project != nil && project.OrganizationId != nil {
+ if !hooks.CanReport(*project.OrganizationId) {
+ monitoring.RecordRateLimited(*project.OrganizationId)
+ c.AbortWithStatus(http.StatusTooManyRequests)
+ return
}
}
@@ -139,14 +144,6 @@ func (e clientController) Report(c *gin.Context) {
spansToInsert = append(spansToInsert, span)
}
}
- projectAsAny, projectExists := c.Get(middleware.ProjectContextKey)
- var project *models.Project
- if projectExists {
- if p, ok := projectAsAny.(*models.Project); ok {
- project = p
- }
- }
-
var sourceMaps *[]*models.SourceMap
if project != nil && isJsFramework(project.Framework) {
loadSpan := traceway.StartSpan(c, "report.load_source_maps")
@@ -242,6 +239,12 @@ func (e clientController) Report(c *gin.Context) {
}
convertSpan.End()
+ var droppedHealthchecks int
+ endpointsToInsert, spansToInsert, droppedHealthchecks = services.FilterHealthchecks(project, endpointsToInsert, spansToInsert, exceptionStackTraceToInsert)
+ if droppedHealthchecks > 0 {
+ monitoring.RecordHealthchecksDropped(monitoring.SignalNative, droppedHealthchecks)
+ }
+
convertMs := float64(time.Since(convertStart).Microseconds()) / 1000.0
insertStart := time.Now()
@@ -315,18 +318,16 @@ func (e clientController) Report(c *gin.Context) {
exceptionHashes = append(exceptionHashes, est.ExceptionHash)
}
- if project, exists := c.Get(middleware.ProjectContextKey); exists {
- if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {
- hooks.BroadcastReport(hooks.ReportEvent{
- OrganizationId: *p.OrganizationId,
- ProjectId: projectId,
- EndpointCount: len(endpointsToInsert),
- ErrorCount: len(exceptionStackTraceToInsert),
- TaskCount: len(tasksToInsert),
- RecordingCount: len(recordingsWork),
- ExceptionHashes: exceptionHashes,
- })
- }
+ if project != nil && project.OrganizationId != nil {
+ hooks.BroadcastReport(hooks.ReportEvent{
+ OrganizationId: *project.OrganizationId,
+ ProjectId: projectId,
+ EndpointCount: len(endpointsToInsert),
+ ErrorCount: len(exceptionStackTraceToInsert),
+ TaskCount: len(tasksToInsert),
+ RecordingCount: len(recordingsWork),
+ ExceptionHashes: exceptionHashes,
+ })
}
for _, rw := range recordingsWork {
diff --git a/backend/app/controllers/otelcontrollers/otel.controller.go b/backend/app/controllers/otelcontrollers/otel.controller.go
index 5ad1318c..a4aa498d 100644
--- a/backend/app/controllers/otelcontrollers/otel.controller.go
+++ b/backend/app/controllers/otelcontrollers/otel.controller.go
@@ -34,16 +34,21 @@ func (o otelController) ExportTraces(c *gin.Context) {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("UseClientAuth middleware must be applied: %w", err))
return
}
- if project, exists := c.Get(middleware.ProjectContextKey); exists {
- if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {
- if attrs := traceway.GetAttributesFromContext(c); attrs != nil {
- attrs.SetTag("organization_id", fmt.Sprintf("%d", *p.OrganizationId))
- }
- if !hooks.CanReport(*p.OrganizationId) {
- monitoring.RecordRateLimited(*p.OrganizationId)
- c.AbortWithStatus(http.StatusTooManyRequests)
- return
- }
+ var project *models.Project
+ if projectAsAny, exists := c.Get(middleware.ProjectContextKey); exists {
+ if p, ok := projectAsAny.(*models.Project); ok {
+ project = p
+ }
+ }
+
+ if project != nil && project.OrganizationId != nil {
+ if attrs := traceway.GetAttributesFromContext(c); attrs != nil {
+ attrs.SetTag("organization_id", fmt.Sprintf("%d", *project.OrganizationId))
+ }
+ if !hooks.CanReport(*project.OrganizationId) {
+ monitoring.RecordRateLimited(*project.OrganizationId)
+ c.AbortWithStatus(http.StatusTooManyRequests)
+ return
}
}
req, bodyBytes, err := decodeTraceRequest(c)
@@ -54,6 +59,13 @@ func (o otelController) ExportTraces(c *gin.Context) {
convertStart := time.Now()
endpoints, tasks, spans, exceptions, aiTraces, aiConversations := convertTraces(projectId, req)
+
+ var droppedHealthchecks int
+ endpoints, spans, droppedHealthchecks = services.FilterHealthchecks(project, endpoints, spans, exceptions)
+ if droppedHealthchecks > 0 {
+ monitoring.RecordHealthchecksDropped(monitoring.SignalTraces, droppedHealthchecks)
+ }
+
convertMs := msSince(convertStart)
insertStart := time.Now()
@@ -111,17 +123,15 @@ func (o otelController) ExportTraces(c *gin.Context) {
exceptionHashes = append(exceptionHashes, ex.ExceptionHash)
}
- if project, exists := c.Get(middleware.ProjectContextKey); exists {
- if p, ok := project.(*models.Project); ok && p.OrganizationId != nil {
- hooks.BroadcastReport(hooks.ReportEvent{
- OrganizationId: *p.OrganizationId,
- ProjectId: projectId,
- EndpointCount: len(endpoints),
- ErrorCount: len(exceptions),
- TaskCount: len(tasks),
- ExceptionHashes: exceptionHashes,
- })
- }
+ if project != nil && project.OrganizationId != nil {
+ hooks.BroadcastReport(hooks.ReportEvent{
+ OrganizationId: *project.OrganizationId,
+ ProjectId: projectId,
+ EndpointCount: len(endpoints),
+ ErrorCount: len(exceptions),
+ TaskCount: len(tasks),
+ ExceptionHashes: exceptionHashes,
+ })
}
writeTraceResponse(c)
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.go
index 8e6fdae0..fdc2c133 100644
--- a/backend/app/controllers/project.controller.go
+++ b/backend/app/controllers/project.controller.go
@@ -10,6 +10,7 @@ import (
"fmt"
"net/http"
"regexp"
+ "strings"
"unicode/utf8"
"github.com/gin-gonic/gin"
@@ -59,8 +60,10 @@ type CreateProjectRequest struct {
}
type UpdateProjectRequest struct {
- Name string `json:"name" binding:"required"`
- Framework string `json:"framework" binding:"required"`
+ Name string `json:"name" binding:"required"`
+ Framework string `json:"framework" binding:"required"`
+ DropHealthyHealthchecks *bool `json:"dropHealthyHealthchecks"`
+ HealthcheckPaths *[]string `json:"healthcheckPaths"`
}
type DeleteProjectRequest struct {
@@ -153,6 +156,32 @@ func (p projectController) UpdateProject(c *gin.Context) {
return
}
+ var healthcheckPaths *[]string
+ if request.HealthcheckPaths != nil {
+ if len(*request.HealthcheckPaths) > 50 {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "At most 50 healthcheck paths are allowed"})
+ return
+ }
+ cleaned := make([]string, 0, len(*request.HealthcheckPaths))
+ for _, path := range *request.HealthcheckPaths {
+ path = strings.TrimSpace(path)
+ if path == "" {
+ continue
+ }
+ if utf8.RuneCountInString(path) > 200 {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Healthcheck paths must be at most 200 characters"})
+ return
+ }
+ base := strings.TrimSuffix(strings.TrimPrefix(path, "*"), "*")
+ if !strings.HasPrefix(base, "/") {
+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Healthcheck paths must start with / (a leading or trailing * is allowed as a wildcard)"})
+ return
+ }
+ cleaned = append(cleaned, path)
+ }
+ healthcheckPaths = &cleaned
+ }
+
projectId, err := middleware.GetProjectId(c)
if err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("RequireProjectAccess middleware must be applied: %w", err))
@@ -160,7 +189,7 @@ func (p projectController) UpdateProject(c *gin.Context) {
}
project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {
- return repositories.ProjectRepository.Update(tx, projectId, request.Name, request.Framework)
+ return repositories.ProjectRepository.Update(tx, projectId, request.Name, request.Framework, request.DropHealthyHealthchecks, healthcheckPaths)
})
if err != nil {
c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("error updating project: %w", err))
diff --git a/backend/app/migrations/pg/0037_add_drop_healthy_healthchecks_to_projects.up.sql b/backend/app/migrations/pg/0037_add_drop_healthy_healthchecks_to_projects.up.sql
new file mode 100644
index 00000000..952ff95f
--- /dev/null
+++ b/backend/app/migrations/pg/0037_add_drop_healthy_healthchecks_to_projects.up.sql
@@ -0,0 +1 @@
+ALTER TABLE projects ADD COLUMN drop_healthy_healthchecks BOOLEAN NOT NULL DEFAULT TRUE
diff --git a/backend/app/migrations/pg/0038_add_healthcheck_paths_to_projects.up.sql b/backend/app/migrations/pg/0038_add_healthcheck_paths_to_projects.up.sql
new file mode 100644
index 00000000..27295b0a
--- /dev/null
+++ b/backend/app/migrations/pg/0038_add_healthcheck_paths_to_projects.up.sql
@@ -0,0 +1 @@
+ALTER TABLE projects ADD COLUMN healthcheck_paths TEXT NOT NULL DEFAULT '[]'
diff --git a/backend/app/migrations/sqlite/0011_add_drop_healthy_healthchecks_to_projects.up.sql b/backend/app/migrations/sqlite/0011_add_drop_healthy_healthchecks_to_projects.up.sql
new file mode 100644
index 00000000..000cfa02
--- /dev/null
+++ b/backend/app/migrations/sqlite/0011_add_drop_healthy_healthchecks_to_projects.up.sql
@@ -0,0 +1 @@
+ALTER TABLE projects ADD COLUMN drop_healthy_healthchecks INTEGER NOT NULL DEFAULT 1
diff --git a/backend/app/migrations/sqlite/0012_add_healthcheck_paths_to_projects.up.sql b/backend/app/migrations/sqlite/0012_add_healthcheck_paths_to_projects.up.sql
new file mode 100644
index 00000000..27295b0a
--- /dev/null
+++ b/backend/app/migrations/sqlite/0012_add_healthcheck_paths_to_projects.up.sql
@@ -0,0 +1 @@
+ALTER TABLE projects ADD COLUMN healthcheck_paths TEXT NOT NULL DEFAULT '[]'
diff --git a/backend/app/models/project.model.go b/backend/app/models/project.model.go
index c2ee0a1d..4bbefbd4 100644
--- a/backend/app/models/project.model.go
+++ b/backend/app/models/project.model.go
@@ -1,20 +1,58 @@
package models
import (
+ "database/sql/driver"
+ "encoding/json"
+ "fmt"
"github.com/tracewayapp/traceway/backend/app/config"
"time"
"github.com/google/uuid"
)
+type StringSlice []string
+
+func (s *StringSlice) Scan(src any) error {
+ var data []byte
+ switch v := src.(type) {
+ case nil:
+ *s = nil
+ return nil
+ case string:
+ data = []byte(v)
+ case []byte:
+ data = v
+ default:
+ return fmt.Errorf("StringSlice.Scan: unsupported type %T", src)
+ }
+ if len(data) == 0 {
+ *s = nil
+ return nil
+ }
+ return json.Unmarshal(data, s)
+}
+
+func (s StringSlice) Value() (driver.Value, error) {
+ if len(s) == 0 {
+ return "[]", nil
+ }
+ b, err := json.Marshal(s)
+ if err != nil {
+ return nil, err
+ }
+ return string(b), nil
+}
+
type Project struct {
- Id uuid.UUID `json:"id"`
- Name string `json:"name"`
- Token string `json:"token"`
- Framework string `json:"framework"`
- OrganizationId *int `json:"organizationId"`
- CreatedAt time.Time `json:"createdAt"`
- SourceMapToken *string `json:"sourceMapToken,omitempty"`
+ Id uuid.UUID `json:"id"`
+ Name string `json:"name"`
+ Token string `json:"token"`
+ Framework string `json:"framework"`
+ OrganizationId *int `json:"organizationId"`
+ CreatedAt time.Time `json:"createdAt"`
+ SourceMapToken *string `json:"sourceMapToken,omitempty"`
+ DropHealthyHealthchecks bool `json:"dropHealthyHealthchecks"`
+ HealthcheckPaths StringSlice `json:"healthcheckPaths"`
}
func (p Project) ToProjectWithBackendUrl() *ProjectWithBackendUrl {
diff --git a/backend/app/monitoring/metrics.go b/backend/app/monitoring/metrics.go
index 784a1781..220a4ef1 100644
--- a/backend/app/monitoring/metrics.go
+++ b/backend/app/monitoring/metrics.go
@@ -39,6 +39,12 @@ func RecordIngestBatch(signal, table string, convertMs, insertMs float64, size,
traceway.CaptureMetricWithTags("traceway.ingest.batch.bytes", float64(bytes), tags)
}
+func RecordHealthchecksDropped(signal string, count int) {
+ traceway.CaptureMetricWithTags("traceway.ingest.healthchecks_dropped", float64(count), map[string]string{
+ "signal": signal,
+ })
+}
+
func RecordRateLimited(orgID int) {
traceway.CaptureMetricWithTags("traceway.ingest.rate_limited", 1, map[string]string{
"org_id": strconv.Itoa(orgID),
diff --git a/backend/app/repositories/project.repository.go b/backend/app/repositories/project.repository.go
index ab796161..0f778d80 100644
--- a/backend/app/repositories/project.repository.go
+++ b/backend/app/repositories/project.repository.go
@@ -15,14 +15,16 @@ import (
type projectRepository struct{}
type projectWithRole struct {
- Id uuid.UUID `lit:"id"`
- Name string `lit:"name"`
- Token string `lit:"token"`
- Framework string `lit:"framework"`
- OrganizationId *int `lit:"organization_id"`
- CreatedAt time.Time `lit:"created_at"`
- SourceMapToken *string `lit:"source_map_token"`
- Role string `lit:"role"`
+ Id uuid.UUID `lit:"id"`
+ Name string `lit:"name"`
+ Token string `lit:"token"`
+ Framework string `lit:"framework"`
+ OrganizationId *int `lit:"organization_id"`
+ CreatedAt time.Time `lit:"created_at"`
+ SourceMapToken *string `lit:"source_map_token"`
+ DropHealthyHealthchecks bool `lit:"drop_healthy_healthchecks"`
+ HealthcheckPaths models.StringSlice `lit:"healthcheck_paths"`
+ Role string `lit:"role"`
}
func init() {
@@ -34,7 +36,7 @@ func init() {
func (p *projectRepository) FindAllWithBackendUrlByUserId(tx *sql.Tx, userId int) ([]*models.ProjectWithBackendUrl, error) {
rows, err := lit.SelectNamed[projectWithRole](
tx,
- `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token, ou.role
+ `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token, p.drop_healthy_healthchecks, p.healthcheck_paths, ou.role
FROM projects p
INNER JOIN organization_users ou ON p.organization_id = ou.organization_id
WHERE ou.user_id = :user_id
@@ -55,13 +57,15 @@ func (p *projectRepository) FindAllWithBackendUrlByUserId(tx *sql.Tx, userId int
}
project := models.Project{
- Id: row.Id,
- Name: row.Name,
- Token: token,
- Framework: row.Framework,
- OrganizationId: row.OrganizationId,
- CreatedAt: row.CreatedAt,
- SourceMapToken: sourceMapToken,
+ Id: row.Id,
+ Name: row.Name,
+ Token: token,
+ Framework: row.Framework,
+ OrganizationId: row.OrganizationId,
+ CreatedAt: row.CreatedAt,
+ SourceMapToken: sourceMapToken,
+ DropHealthyHealthchecks: row.DropHealthyHealthchecks,
+ HealthcheckPaths: row.HealthcheckPaths,
}
result = append(result, project.ToProjectWithBackendUrl())
}
@@ -72,14 +76,14 @@ func (p *projectRepository) FindAllWithBackendUrlByUserId(tx *sql.Tx, userId int
func (p *projectRepository) FindAll(tx *sql.Tx) ([]*models.Project, error) {
return lit.Select[models.Project](
tx,
- "SELECT id, name, token, framework, organization_id, created_at, source_map_token FROM projects ORDER BY created_at ASC",
+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths FROM projects ORDER BY created_at ASC",
)
}
func (p *projectRepository) FindByToken(tx *sql.Tx, token string) (*models.Project, error) {
return lit.SelectSingleNamed[models.Project](
tx,
- "SELECT id, name, token, framework, organization_id, created_at, source_map_token FROM projects WHERE token = :token",
+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths FROM projects WHERE token = :token",
lit.P{"token": token},
)
}
@@ -87,18 +91,19 @@ func (p *projectRepository) FindByToken(tx *sql.Tx, token string) (*models.Proje
func (p *projectRepository) FindById(tx *sql.Tx, id uuid.UUID) (*models.Project, error) {
return lit.SelectSingleNamed[models.Project](
tx,
- "SELECT id, name, token, framework, organization_id, created_at, source_map_token FROM projects WHERE id = :id",
+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths FROM projects WHERE id = :id",
lit.P{"id": id},
)
}
func (p *projectRepository) Create(tx *sql.Tx, name string, framework string) (*models.Project, error) {
project := &models.Project{
- Id: uuid.New(),
- Name: name,
- Token: generateSecureToken(),
- Framework: framework,
- CreatedAt: time.Now().UTC(),
+ Id: uuid.New(),
+ Name: name,
+ Token: generateSecureToken(),
+ Framework: framework,
+ CreatedAt: time.Now().UTC(),
+ DropHealthyHealthchecks: true,
}
err := lit.InsertExistingUuid(tx, project)
@@ -111,12 +116,13 @@ func (p *projectRepository) Create(tx *sql.Tx, name string, framework string) (*
func (p *projectRepository) CreateWithOrganization(tx *sql.Tx, name string, framework string, organizationId int) (*models.Project, error) {
project := &models.Project{
- Id: uuid.New(),
- Name: name,
- Token: generateSecureToken(),
- Framework: framework,
- OrganizationId: &organizationId,
- CreatedAt: time.Now().UTC(),
+ Id: uuid.New(),
+ Name: name,
+ Token: generateSecureToken(),
+ Framework: framework,
+ OrganizationId: &organizationId,
+ CreatedAt: time.Now().UTC(),
+ DropHealthyHealthchecks: true,
}
err := lit.InsertExistingUuid(tx, project)
@@ -130,7 +136,7 @@ func (p *projectRepository) CreateWithOrganization(tx *sql.Tx, name string, fram
func (p *projectRepository) FindByOrganizationId(tx *sql.Tx, organizationId int) ([]*models.Project, error) {
return lit.SelectNamed[models.Project](
tx,
- "SELECT id, name, token, framework, organization_id, created_at, source_map_token FROM projects WHERE organization_id = :org_id ORDER BY created_at ASC",
+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths FROM projects WHERE organization_id = :org_id ORDER BY created_at ASC",
lit.P{"org_id": organizationId},
)
}
@@ -138,7 +144,7 @@ func (p *projectRepository) FindByOrganizationId(tx *sql.Tx, organizationId int)
func (p *projectRepository) FindByUserId(tx *sql.Tx, userId int) ([]*models.Project, error) {
return lit.SelectNamed[models.Project](
tx,
- `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token
+ `SELECT DISTINCT p.id, p.name, p.token, p.framework, p.organization_id, p.created_at, p.source_map_token, p.drop_healthy_healthchecks, p.healthcheck_paths
FROM projects p
INNER JOIN organization_users ou ON p.organization_id = ou.organization_id
WHERE ou.user_id = :user_id
@@ -184,7 +190,7 @@ func (p *projectRepository) GenerateSourceMapToken(tx *sql.Tx, projectId uuid.UU
return token, nil
}
-func (p *projectRepository) Update(tx *sql.Tx, id uuid.UUID, name string, framework string) (*models.Project, error) {
+func (p *projectRepository) Update(tx *sql.Tx, id uuid.UUID, name string, framework string, dropHealthyHealthchecks *bool, healthcheckPaths *[]string) (*models.Project, error) {
project, err := p.FindById(tx, id)
if err != nil {
return nil, err
@@ -194,6 +200,12 @@ func (p *projectRepository) Update(tx *sql.Tx, id uuid.UUID, name string, framew
}
project.Name = name
project.Framework = framework
+ if dropHealthyHealthchecks != nil {
+ project.DropHealthyHealthchecks = *dropHealthyHealthchecks
+ }
+ if healthcheckPaths != nil {
+ project.HealthcheckPaths = models.StringSlice(*healthcheckPaths)
+ }
err = lit.UpdateNamed[models.Project](tx, project, "id = :id", lit.P{"id": id})
if err != nil {
return nil, err
@@ -221,7 +233,7 @@ func (p *projectRepository) Delete(tx *sql.Tx, id uuid.UUID) error {
func (p *projectRepository) FindBySourceMapToken(tx *sql.Tx, token string) (*models.Project, error) {
return lit.SelectSingleNamed[models.Project](
tx,
- "SELECT id, name, token, framework, organization_id, created_at, source_map_token FROM projects WHERE source_map_token = :smt",
+ "SELECT id, name, token, framework, organization_id, created_at, source_map_token, drop_healthy_healthchecks, healthcheck_paths FROM projects WHERE source_map_token = :smt",
lit.P{"smt": token},
)
}
diff --git a/backend/app/repositories/project.repository_sqlite_test.go b/backend/app/repositories/project.repository_sqlite_test.go
new file mode 100644
index 00000000..c84c1c55
--- /dev/null
+++ b/backend/app/repositories/project.repository_sqlite_test.go
@@ -0,0 +1,90 @@
+//go:build !pgch
+
+package repositories
+
+import (
+ "testing"
+
+ "github.com/tracewayapp/traceway/backend/app/db"
+)
+
+func setupProjectsTable(t *testing.T) {
+ t.Helper()
+ _, err := db.DB.Exec(`CREATE TABLE IF NOT EXISTS projects (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ token TEXT NOT NULL,
+ framework TEXT NOT NULL DEFAULT 'custom',
+ organization_id INTEGER,
+ source_map_token TEXT,
+ created_at DATETIME NOT NULL DEFAULT (datetime('now')),
+ drop_healthy_healthchecks INTEGER NOT NULL DEFAULT 1,
+ healthcheck_paths TEXT NOT NULL DEFAULT '[]'
+ )`)
+ if err != nil {
+ t.Fatalf("failed to create projects table: %v", err)
+ }
+}
+
+func TestProjectHealthcheckFieldsRoundTrip(t *testing.T) {
+ setupTestDB(t)
+ setupProjectsTable(t)
+
+ tx, err := db.DB.Begin()
+ if err != nil {
+ t.Fatalf("failed to begin tx: %v", err)
+ }
+ defer tx.Rollback()
+
+ created, err := ProjectRepository.Create(tx, "test-project", "gin")
+ if err != nil {
+ t.Fatalf("failed to create project: %v", err)
+ }
+ if !created.DropHealthyHealthchecks {
+ t.Errorf("new project should default DropHealthyHealthchecks to true")
+ }
+
+ found, err := ProjectRepository.FindById(tx, created.Id)
+ if err != nil {
+ t.Fatalf("failed to find project: %v", err)
+ }
+ if found == nil {
+ t.Fatal("project not found after create")
+ }
+ if !found.DropHealthyHealthchecks {
+ t.Errorf("DropHealthyHealthchecks = false after round trip, expected true")
+ }
+ if len(found.HealthcheckPaths) != 0 {
+ t.Errorf("HealthcheckPaths = %v, expected empty", found.HealthcheckPaths)
+ }
+
+ disable := false
+ paths := []string{"/internal/probe", "/checks/*"}
+ updated, err := ProjectRepository.Update(tx, created.Id, "test-project", "gin", &disable, &paths)
+ if err != nil {
+ t.Fatalf("failed to update project: %v", err)
+ }
+ if updated.DropHealthyHealthchecks {
+ t.Errorf("DropHealthyHealthchecks = true after disabling")
+ }
+
+ found, err = ProjectRepository.FindById(tx, created.Id)
+ if err != nil {
+ t.Fatalf("failed to re-find project: %v", err)
+ }
+ if found.DropHealthyHealthchecks {
+ t.Errorf("DropHealthyHealthchecks = true after round trip, expected false")
+ }
+ if len(found.HealthcheckPaths) != 2 || found.HealthcheckPaths[0] != "/internal/probe" || found.HealthcheckPaths[1] != "/checks/*" {
+ t.Errorf("HealthcheckPaths = %v, expected %v", found.HealthcheckPaths, paths)
+ }
+
+ keepDrop := true
+ updated, err = ProjectRepository.Update(tx, created.Id, "renamed", "gin", &keepDrop, nil)
+ if err != nil {
+ t.Fatalf("failed to update project without paths: %v", err)
+ }
+ if len(updated.HealthcheckPaths) != 2 {
+ t.Errorf("nil healthcheckPaths should keep existing value, got %v", updated.HealthcheckPaths)
+ }
+}
diff --git a/backend/app/services/healthcheck.service.go b/backend/app/services/healthcheck.service.go
new file mode 100644
index 00000000..631798f9
--- /dev/null
+++ b/backend/app/services/healthcheck.service.go
@@ -0,0 +1,123 @@
+package services
+
+import (
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+var defaultHealthcheckPaths = map[string]bool{
+ "/health": true,
+ "/healthz": true,
+ "/healthcheck": true,
+ "/health-check": true,
+ "/health_check": true,
+ "/ping": true,
+ "/livez": true,
+ "/readyz": true,
+ "/live": true,
+ "/ready": true,
+ "/alive": true,
+ "/up": true,
+ "/heartbeat": true,
+ "/status": true,
+ "/ht": true,
+ "/actuator/health": true,
+}
+
+func ShouldDropHealthcheck(project *models.Project, endpoint string, statusCode int16) bool {
+ if project == nil || !project.DropHealthyHealthchecks {
+ return false
+ }
+ if statusCode >= 400 {
+ return false
+ }
+ method, path, found := strings.Cut(endpoint, " ")
+ if !found || (method != "GET" && method != "HEAD") {
+ return false
+ }
+ return isHealthcheckPath(path, project.HealthcheckPaths)
+}
+
+func isHealthcheckPath(path string, customPaths []string) bool {
+ path = strings.ToLower(strings.TrimSpace(path))
+ if len(path) > 1 {
+ path = strings.TrimRight(path, "/")
+ }
+ if defaultHealthcheckPaths[path] {
+ return true
+ }
+ if strings.HasPrefix(path, "/actuator/health/") {
+ return true
+ }
+ if strings.HasSuffix(path, "/health") {
+ return true
+ }
+ for _, custom := range customPaths {
+ if matchesCustomPath(path, strings.ToLower(strings.TrimSpace(custom))) {
+ return true
+ }
+ }
+ return false
+}
+
+func matchesCustomPath(path, pattern string) bool {
+ if pattern == "" || pattern == "*" {
+ return false
+ }
+ startsWithStar := strings.HasPrefix(pattern, "*")
+ endsWithStar := strings.HasSuffix(pattern, "*")
+ if startsWithStar && endsWithStar {
+ return strings.Contains(path, pattern[1:len(pattern)-1])
+ }
+ if startsWithStar {
+ return strings.HasSuffix(path, pattern[1:])
+ }
+ if endsWithStar {
+ return strings.HasPrefix(path, pattern[:len(pattern)-1])
+ }
+ if len(pattern) > 1 {
+ pattern = strings.TrimRight(pattern, "/")
+ }
+ return path == pattern
+}
+
+func FilterHealthchecks(project *models.Project, endpoints []models.Endpoint, spans []models.Span, exceptions []models.ExceptionStackTrace) ([]models.Endpoint, []models.Span, int) {
+ if project == nil || !project.DropHealthyHealthchecks || len(endpoints) == 0 {
+ return endpoints, spans, 0
+ }
+
+ dropped := map[uuid.UUID]bool{}
+ for _, e := range endpoints {
+ if ShouldDropHealthcheck(project, e.Endpoint, e.StatusCode) {
+ dropped[e.Id] = true
+ }
+ }
+ if len(dropped) == 0 {
+ return endpoints, spans, 0
+ }
+
+ for _, exc := range exceptions {
+ if exc.TraceId != nil {
+ delete(dropped, *exc.TraceId)
+ }
+ }
+ if len(dropped) == 0 {
+ return endpoints, spans, 0
+ }
+
+ keptEndpoints := endpoints[:0]
+ for _, e := range endpoints {
+ if !dropped[e.Id] {
+ keptEndpoints = append(keptEndpoints, e)
+ }
+ }
+ keptSpans := spans[:0]
+ for _, s := range spans {
+ if !dropped[s.TraceId] {
+ keptSpans = append(keptSpans, s)
+ }
+ }
+ return keptEndpoints, keptSpans, len(dropped)
+}
diff --git a/backend/app/services/healthcheck.service_test.go b/backend/app/services/healthcheck.service_test.go
new file mode 100644
index 00000000..49b7496d
--- /dev/null
+++ b/backend/app/services/healthcheck.service_test.go
@@ -0,0 +1,132 @@
+package services
+
+import (
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+func TestShouldDropHealthcheck(t *testing.T) {
+ enabled := &models.Project{DropHealthyHealthchecks: true}
+ disabled := &models.Project{DropHealthyHealthchecks: false}
+ withCustom := &models.Project{
+ DropHealthyHealthchecks: true,
+ HealthcheckPaths: models.StringSlice{"/internal/probe", "/checks/*", "*/liveness"},
+ }
+
+ tests := []struct {
+ name string
+ project *models.Project
+ endpoint string
+ statusCode int16
+ expected bool
+ }{
+ {"nil project", nil, "GET /health", 200, false},
+ {"disabled", disabled, "GET /health", 200, false},
+ {"healthy default path", enabled, "GET /health", 200, true},
+ {"healthz", enabled, "GET /healthz", 200, true},
+ {"healthcheck", enabled, "GET /healthcheck", 204, true},
+ {"hyphenated", enabled, "GET /health-check", 200, true},
+ {"underscored", enabled, "GET /health_check", 200, true},
+ {"ping", enabled, "GET /ping", 200, true},
+ {"livez", enabled, "GET /livez", 200, true},
+ {"readyz", enabled, "GET /readyz", 200, true},
+ {"live", enabled, "GET /live", 200, true},
+ {"ready", enabled, "GET /ready", 200, true},
+ {"alive", enabled, "GET /alive", 200, true},
+ {"rails up", enabled, "GET /up", 200, true},
+ {"heartbeat", enabled, "GET /heartbeat", 200, true},
+ {"status", enabled, "GET /status", 200, true},
+ {"django ht", enabled, "GET /ht", 200, true},
+ {"django ht trailing slash", enabled, "GET /ht/", 200, true},
+ {"actuator", enabled, "GET /actuator/health", 200, true},
+ {"actuator liveness", enabled, "GET /actuator/health/liveness", 200, true},
+ {"prefixed health suffix", enabled, "GET /api/health", 200, true},
+ {"deeply prefixed health", enabled, "GET /api/v1/health", 200, true},
+ {"head method", enabled, "HEAD /health", 200, true},
+ {"uppercase path", enabled, "GET /HEALTH", 200, true},
+ {"redirect status kept dropped", enabled, "GET /health", 301, true},
+ {"failing healthcheck kept", enabled, "GET /health", 503, false},
+ {"client error kept", enabled, "GET /health", 404, false},
+ {"post not dropped", enabled, "POST /health", 200, false},
+ {"no method prefix", enabled, "/health", 200, false},
+ {"unmatched", enabled, "UNMATCHED", 200, false},
+ {"regular endpoint", enabled, "GET /api/users", 200, false},
+ {"healthy substring not matched", enabled, "GET /healthyrecipes", 200, false},
+ {"shipping not ping", enabled, "GET /api/shipping", 200, false},
+ {"custom exact", withCustom, "GET /internal/probe", 200, true},
+ {"custom prefix wildcard", withCustom, "GET /checks/db", 200, true},
+ {"custom suffix wildcard", withCustom, "GET /svc/liveness", 200, true},
+ {"custom no match", withCustom, "GET /internal/other", 200, false},
+ {"custom failing kept", withCustom, "GET /internal/probe", 500, false},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ result := ShouldDropHealthcheck(tt.project, tt.endpoint, tt.statusCode)
+ if result != tt.expected {
+ t.Errorf("ShouldDropHealthcheck(%q, %d) = %v, expected %v", tt.endpoint, tt.statusCode, result, tt.expected)
+ }
+ })
+ }
+}
+
+func TestFilterHealthchecks(t *testing.T) {
+ project := &models.Project{DropHealthyHealthchecks: true}
+
+ healthyId := uuid.New()
+ failingId := uuid.New()
+ regularId := uuid.New()
+ excId := uuid.New()
+
+ endpoints := []models.Endpoint{
+ {Id: healthyId, Endpoint: "GET /health", StatusCode: 200},
+ {Id: failingId, Endpoint: "GET /health", StatusCode: 503},
+ {Id: regularId, Endpoint: "GET /api/users", StatusCode: 200},
+ {Id: excId, Endpoint: "GET /healthz", StatusCode: 200},
+ }
+ spans := []models.Span{
+ {Id: uuid.New(), TraceId: healthyId},
+ {Id: uuid.New(), TraceId: regularId},
+ {Id: uuid.New(), TraceId: excId},
+ }
+ exceptions := []models.ExceptionStackTrace{
+ {Id: uuid.New(), TraceId: &excId},
+ }
+
+ keptEndpoints, keptSpans, dropped := FilterHealthchecks(project, endpoints, spans, exceptions)
+
+ if dropped != 1 {
+ t.Errorf("dropped = %d, expected 1", dropped)
+ }
+ if len(keptEndpoints) != 3 {
+ t.Fatalf("len(keptEndpoints) = %d, expected 3", len(keptEndpoints))
+ }
+ for _, e := range keptEndpoints {
+ if e.Id == healthyId {
+ t.Errorf("healthy healthcheck endpoint was not dropped")
+ }
+ }
+ if len(keptSpans) != 2 {
+ t.Fatalf("len(keptSpans) = %d, expected 2", len(keptSpans))
+ }
+ for _, s := range keptSpans {
+ if s.TraceId == healthyId {
+ t.Errorf("span of dropped healthcheck was not dropped")
+ }
+ }
+}
+
+func TestFilterHealthchecksDisabled(t *testing.T) {
+ project := &models.Project{DropHealthyHealthchecks: false}
+ endpoints := []models.Endpoint{
+ {Id: uuid.New(), Endpoint: "GET /health", StatusCode: 200},
+ }
+
+ keptEndpoints, _, dropped := FilterHealthchecks(project, endpoints, nil, nil)
+
+ if dropped != 0 || len(keptEndpoints) != 1 {
+ t.Errorf("disabled filter dropped endpoints: kept=%d dropped=%d", len(keptEndpoints), dropped)
+ }
+}
diff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.json
index 0e532cbd..6e772709 100644
--- a/docs/pages/learn/_meta.json
+++ b/docs/pages/learn/_meta.json
@@ -7,6 +7,7 @@
"sessions": "Sessions",
"attributes": "Attributes",
"spans": "Spans",
+ "healthchecks": "Healthchecks",
"metrics": "Metrics",
"logs": "Logs",
"alerts": "Alerts",
diff --git a/docs/pages/learn/healthchecks.mdx b/docs/pages/learn/healthchecks.mdx
new file mode 100644
index 00000000..f015561b
--- /dev/null
+++ b/docs/pages/learn/healthchecks.mdx
@@ -0,0 +1,52 @@
+# Healthchecks
+
+Healthcheck endpoints get hit constantly: Kubernetes probes every few seconds, load balancer target checks, uptime monitors. Storing every successful probe wastes events on traffic that carries no information. Traceway detects healthcheck endpoints at ingestion and **only stores requests that fail**.
+
+## How It Works
+
+When a request arrives on either ingestion path (the native SDK `/api/report` endpoint or OTLP traces), Traceway checks three things:
+
+1. The method is `GET` or `HEAD`
+2. The path matches a known healthcheck pattern (built-in or custom)
+3. The response status is below 400
+
+If all three are true, the request is dropped before it is written to the database. Its child spans are dropped with it. Requests with status 400 or higher are always stored, so a failing healthcheck still shows up in your endpoints list and can trigger alerts.
+
+Exceptions are never dropped. If a healthcheck request returns 200 but captures an exception, both the exception and its trace are kept so the error remains fully inspectable.
+
+## Built-In Paths
+
+Path matching is case-insensitive and ignores trailing slashes. The built-in list covers the common conventions:
+
+| Pattern | Used by |
+|---------|---------|
+| `/health`, `/healthcheck`, `/health-check`, `/health_check` | General convention, ASP.NET Core |
+| `/healthz`, `/livez`, `/readyz` | Kubernetes probes |
+| `/live`, `/ready`, `/alive` | Container orchestrators, lightship |
+| `/ping`, `/status`, `/heartbeat` | Load balancers, uptime monitors |
+| `/up` | Rails 7.1+, Laravel 11+ |
+| `/ht` | Django (django-health-check) |
+| `/actuator/health` and sub-paths | Spring Boot Actuator |
+| any path ending in `/health` | Catches prefixed variants like `/api/health` |
+
+## Custom Paths
+
+If your healthcheck lives somewhere else, add custom paths in the project settings. Each entry is one path, with optional wildcards:
+
+| Pattern | Matches |
+|---------|---------|
+| `/internal/probe` | Exactly `/internal/probe` |
+| `/checks/*` | Any path starting with `/checks/` |
+| `*/liveness` | Any path ending in `/liveness` |
+
+## Configuration
+
+The feature is **enabled by default** for every project. To change it, open the project switcher, edit the project, and use the **Drop healthy healthcheck requests** toggle. The same form accepts custom paths (one per line) and shows the full built-in list.
+
+Turning the toggle off stores all healthcheck traffic again. The setting takes effect immediately, no restart required.
+
+## Dashboard Behavior
+
+Endpoints detected as healthchecks show a **Healthcheck** badge in the endpoints list and on the endpoint detail page. Because only failures are stored, the request count and error rate for these endpoints reflect failures only. A healthcheck endpoint showing a 100% error rate means "every stored request failed", which is expected, since healthy requests are not stored at all.
+
+Dropped requests are counted in the `traceway.ingest.healthchecks_dropped` self-monitoring metric, tagged with the ingestion signal (`native` or `traces`), so you can verify the filter is working.
diff --git a/frontend/src/lib/components/edit-project-modal.svelte b/frontend/src/lib/components/edit-project-modal.svelte
index 3a0f06fb..6fb01c0b 100644
--- a/frontend/src/lib/components/edit-project-modal.svelte
+++ b/frontend/src/lib/components/edit-project-modal.svelte
@@ -1,9 +1,12 @@
<script lang="ts">
import * as Sheet from "$lib/components/ui/sheet";
import * as AlertDialog from "$lib/components/ui/alert-dialog";
+ import * as Tabs from "$lib/components/ui/tabs";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
+ import { Checkbox } from "$lib/components/ui/checkbox";
+ import { DEFAULT_HEALTHCHECK_PATHS } from '$lib/utils/healthcheck';
import { projectsState, type Project, type Framework } from '$lib/state/projects.svelte';
import { Check, Trash2, Copy, CircleAlert } from 'lucide-svelte';
import FrameworkCombobox from './framework-combobox.svelte';
@@ -18,8 +21,14 @@
let { open, onOpenChange, project }: Props = $props();
+ const tabTriggerClass = "-mb-px rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2.5 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none";
+
+ let activeTab = $state('project');
let projectName = $state('');
let selectedFramework = $state<Framework>('gin');
+ let dropHealthyHealthchecks = $state(true);
+ let healthcheckPathsText = $state('');
+ let showDefaultHealthcheckPaths = $state(false);
let loading = $state(false);
let error = $state('');
let showDeleteConfirm = $state(false);
@@ -29,8 +38,11 @@
$effect(() => {
if (open && project) {
+ activeTab = 'project';
projectName = project.name;
selectedFramework = project.framework;
+ dropHealthyHealthchecks = project.dropHealthyHealthchecks ?? true;
+ healthcheckPathsText = (project.healthcheckPaths ?? []).join('\n');
error = '';
}
});
@@ -53,6 +65,12 @@
!!project && deleteConfirmName === project.name
);
+ let subtitle = $derived(
+ activeTab === 'healthchecks' ? 'Control which healthcheck requests are stored.'
+ : activeTab === 'danger' ? 'Irreversible and destructive actions.'
+ : ''
+ );
+
async function handleSubmit(e: Event) {
e.preventDefault();
if (!projectName.trim()) {
@@ -64,8 +82,13 @@
loading = true;
error = '';
+ const healthcheckPaths = healthcheckPathsText
+ .split('\n')
+ .map(p => p.trim())
+ .filter(p => p.length > 0);
+
try {
- await projectsState.updateProject(project.id, projectName.trim(), selectedFramework);
+ await projectsState.updateProject(project.id, projectName.trim(), selectedFramework, dropHealthyHealthchecks, healthcheckPaths);
toast.success('Successfully updated the project', { position: 'top-center' });
onOpenChange(false);
} catch (err: any) {
@@ -100,61 +123,28 @@
</script>
<Sheet.Root {open} onOpenChange={handleClose}>
- <Sheet.Content side="right" class="w-[400px] sm:w-[540px]">
- <Sheet.Header>
+ <Sheet.Content side="right" class="w-full overflow-y-auto sm:w-[540px]">
+ <Sheet.Header class="px-6 pb-0">
<Sheet.Title>Edit Project</Sheet.Title>
- <Sheet.Description>
- Update your project name or framework.
- </Sheet.Description>
</Sheet.Header>
- <form onsubmit={handleSubmit} class="px-6 py-6 space-y-5">
- <div class="space-y-2">
- <Label for="edit-project-name">Project Name</Label>
- <Input
- id="edit-project-name"
- type="text"
- placeholder="My Application"
- bind:value={projectName}
- disabled={loading}
- />
- <p class="text-xs text-muted-foreground">
- A unique name for your project (letters, numbers, spaces, hyphens)
- </p>
- </div>
+ <Tabs.Root value={activeTab} onValueChange={(v) => { if (v) activeTab = v; }}>
+ <Tabs.List class="h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0 pl-6 pt-0">
+ <Tabs.Trigger value="project" class={tabTriggerClass}>Project</Tabs.Trigger>
+ <Tabs.Trigger value="healthchecks" class={tabTriggerClass}>Healthchecks</Tabs.Trigger>
+ <Tabs.Trigger value="danger" class={tabTriggerClass}>Danger Zone</Tabs.Trigger>
+ </Tabs.List>
+ </Tabs.Root>
- <div class="space-y-2">
- <Label for="edit-framework">Framework</Label>
- <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />
- <p class="text-xs text-muted-foreground">
- Select your framework for tailored integration code
- </p>
- </div>
-
- {#if error}
- <div class="rounded-md bg-destructive/10 border border-destructive/20 p-3">
- <p class="text-sm text-destructive">{error}</p>
- </div>
- {/if}
+ {#if subtitle}
+ <Sheet.Description class="px-6">{subtitle}</Sheet.Description>
+ {/if}
- <div class="flex justify-end gap-2 pt-2">
- <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>
- Cancel
- </Button>
- <Button type="submit" disabled={loading}>
- {#if loading}
- Updating...
- {:else}
- <Check class="mr-2 h-4 w-4" />
- Update Project
- {/if}
- </Button>
- </div>
- </form>
-
- <div class="px-6 pb-6">
- <div class="border-t pt-6">
- <p class="text-sm text-muted-foreground mb-3">Danger zone</p>
+ {#if activeTab === 'danger'}
+ <div class="px-6 pb-6 space-y-3">
+ <p class="text-sm text-muted-foreground">
+ Permanently delete this project along with all of its data, including transactions, exceptions, logs, metrics, and dashboards.
+ </p>
<Button
type="button"
variant="destructiveOutline"
@@ -164,7 +154,100 @@
Delete Project
</Button>
</div>
- </div>
+ {:else}
+ <form onsubmit={handleSubmit} class="px-6 pb-6 space-y-5">
+ {#if activeTab === 'project'}
+ <div class="space-y-2">
+ <Label for="edit-project-name">Project Name</Label>
+ <Input
+ id="edit-project-name"
+ type="text"
+ placeholder="My Application"
+ bind:value={projectName}
+ disabled={loading}
+ />
+ <p class="text-xs text-muted-foreground">
+ A unique name for your project (letters, numbers, spaces, hyphens)
+ </p>
+ </div>
+
+ <div class="space-y-2">
+ <Label for="edit-framework">Framework</Label>
+ <FrameworkCombobox bind:value={selectedFramework} disabled={loading} />
+ <p class="text-xs text-muted-foreground">
+ Select your framework for tailored integration code
+ </p>
+ </div>
+ {:else}
+ <div class="flex items-start gap-2">
+ <Checkbox
+ checked={dropHealthyHealthchecks}
+ onCheckedChange={(checked) => dropHealthyHealthchecks = checked === true}
+ disabled={loading}
+ class="mt-0.5"
+ aria-label="Drop healthy healthcheck requests"
+ />
+ <div class="space-y-1">
+ <Label class="cursor-pointer" onclick={() => { if (!loading) dropHealthyHealthchecks = !dropHealthyHealthchecks; }}>Drop healthy healthcheck requests</Label>
+ <p class="text-xs text-muted-foreground">
+ Requests to common healthcheck endpoints (GET/HEAD) are only stored when they fail with status 400 or higher.
+ <button
+ type="button"
+ class="underline hover:text-foreground"
+ onclick={() => showDefaultHealthcheckPaths = !showDefaultHealthcheckPaths}
+ >
+ {showDefaultHealthcheckPaths ? 'Hide' : 'Show'} built-in paths
+ </button>
+ </p>
+ {#if showDefaultHealthcheckPaths}
+ <div class="flex flex-wrap gap-1 pt-1">
+ {#each DEFAULT_HEALTHCHECK_PATHS as path}
+ <code class="rounded bg-muted px-1.5 py-0.5 text-xs">{path}</code>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ </div>
+
+ {#if dropHealthyHealthchecks}
+ <div class="space-y-2">
+ <Label for="edit-healthcheck-paths">Additional healthcheck paths</Label>
+ <textarea
+ id="edit-healthcheck-paths"
+ bind:value={healthcheckPathsText}
+ disabled={loading}
+ rows="3"
+ placeholder={"/internal/probe\n/checks/*"}
+ class="border-input bg-background dark:bg-input/30 placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 flex w-full rounded-md border px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50"
+ ></textarea>
+ <p class="text-xs text-muted-foreground">
+ One path per line. Use a trailing * to match a prefix or a leading * to match a suffix.
+ </p>
+ </div>
+ {/if}
+ {/if}
+
+ {#if error}
+ <div class="rounded-md bg-destructive/10 border border-destructive/20 p-3">
+ <p class="text-sm text-destructive">{error}</p>
+ </div>
+ {/if}
+
+ <div class="flex justify-end gap-2 pt-2">
+ <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={loading}>
+ {#if loading}
+ Updating...
+ {:else}
+ <Check class="mr-2 h-4 w-4" />
+ Update Project
+ {/if}
+ </Button>
+ </div>
+ </form>
+ {/if}
</Sheet.Content>
</Sheet.Root>
diff --git a/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte b/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte
index ce81cbfd..50078f2e 100644
--- a/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte
+++ b/frontend/src/lib/components/trace-logs/trace-logs-panel.svelte
@@ -53,6 +53,9 @@
let activeTab = $state<'this-trace' | 'all-distributed'>('this-trace');
+ const tabTriggerClass =
+ 'rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none';
+
// This-trace data
let logs = $state<LogRecord[]>([]);
let loading = $state(true);
@@ -166,31 +169,23 @@
</script>
<Card.Root class="gap-0 pb-0 overflow-hidden">
- <Card.Header>
+ <Card.Header class={distributedTraceId ? '' : 'pb-4'}>
<Card.Title>Logs</Card.Title>
</Card.Header>
<Card.Content class="p-0">
<Tabs.Root value={activeTab} onValueChange={onTabChange}>
- <Tabs.List
- class="h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0 pl-6 pt-0 pb-2"
- >
- <Tabs.Trigger
- value="this-trace"
- class="rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none"
+ {#if distributedTraceId}
+ <Tabs.List
+ class="h-auto w-full justify-start gap-4 rounded-none border-b bg-transparent p-0 pl-6 pt-0 pb-2"
>
- This Trace
- </Tabs.Trigger>
- {#if distributedTraceId}
- <Tabs.Trigger
- value="all-distributed"
- class="rounded-none border-b-2 border-transparent bg-transparent px-0 pb-2 pt-0 text-sm font-medium text-muted-foreground shadow-none data-[state=active]:border-primary data-[state=active]:bg-transparent data-[state=active]:text-foreground data-[state=active]:shadow-none"
- >
+ <Tabs.Trigger value="this-trace" class={tabTriggerClass}>This Trace</Tabs.Trigger>
+ <Tabs.Trigger value="all-distributed" class={tabTriggerClass}>
All Distributed Traces
</Tabs.Trigger>
- {/if}
- </Tabs.List>
+ </Tabs.List>
+ {/if}
- <Tabs.Content value="this-trace" class="mt-0">
+ <Tabs.Content value="this-trace" class={distributedTraceId ? 'mt-0' : 'mt-0 border-t'}>
{#if loading}
<div class="flex items-center justify-center py-6">
<LoadingCircle size="lg" />
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
index c346eec6..7701d626 100644
--- a/frontend/src/lib/state/projects.svelte.ts
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -67,6 +67,8 @@ export interface Project {
createdAt: string;
sourceMapToken: string | null;
backendUrl: string;
+ dropHealthyHealthchecks: boolean;
+ healthcheckPaths: string[] | null;
}
export interface ProjectWithToken extends Project {
@@ -149,8 +151,8 @@ class ProjectsState {
return response;
}
- async updateProject(id: string, name: string, framework: Framework): Promise<Project> {
- const response = await api.put('/projects', { name, framework }, {
+ async updateProject(id: string, name: string, framework: Framework, dropHealthyHealthchecks: boolean, healthcheckPaths: string[]): Promise<Project> {
+ const response = await api.put('/projects', { name, framework, dropHealthyHealthchecks, healthcheckPaths }, {
projectId: id
});
await this.loadProjects();
diff --git a/frontend/src/lib/utils/healthcheck.ts b/frontend/src/lib/utils/healthcheck.ts
new file mode 100644
index 00000000..6856c5b2
--- /dev/null
+++ b/frontend/src/lib/utils/healthcheck.ts
@@ -0,0 +1,38 @@
+export const DEFAULT_HEALTHCHECK_PATHS = [
+ '/health', '/healthz', '/healthcheck', '/health-check', '/health_check',
+ '/ping', '/livez', '/readyz', '/live', '/ready', '/alive', '/up',
+ '/heartbeat', '/status', '/ht', '/actuator/health/*', '*/health'
+];
+
+const DEFAULT_PATH_SET = new Set([
+ '/health', '/healthz', '/healthcheck', '/health-check', '/health_check',
+ '/ping', '/livez', '/readyz', '/live', '/ready', '/alive', '/up',
+ '/heartbeat', '/status', '/ht', '/actuator/health'
+]);
+
+function matchesCustomPath(path: string, pattern: string): boolean {
+ if (pattern === '' || pattern === '*') return false;
+ const startsWithStar = pattern.startsWith('*');
+ const endsWithStar = pattern.endsWith('*');
+ if (startsWithStar && endsWithStar) return path.includes(pattern.slice(1, -1));
+ if (startsWithStar) return path.endsWith(pattern.slice(1));
+ if (endsWithStar) return path.startsWith(pattern.slice(0, -1));
+ if (pattern.length > 1) pattern = pattern.replace(/\/+$/, '');
+ return path === pattern;
+}
+
+export function isHealthcheckEndpoint(endpoint: string, customPaths?: string[] | null): boolean {
+ const spaceIdx = endpoint.indexOf(' ');
+ if (spaceIdx === -1) return false;
+ const method = endpoint.slice(0, spaceIdx);
+ if (method !== 'GET' && method !== 'HEAD') return false;
+ let path = endpoint.slice(spaceIdx + 1).trim().toLowerCase();
+ if (path.length > 1) path = path.replace(/\/+$/, '');
+ if (DEFAULT_PATH_SET.has(path)) return true;
+ if (path.startsWith('/actuator/health/')) return true;
+ if (path.endsWith('/health')) return true;
+ for (const custom of customPaths ?? []) {
+ if (matchesCustomPath(path, custom.trim().toLowerCase())) return true;
+ }
+ return false;
+}
diff --git a/frontend/src/routes/endpoints/+page.svelte b/frontend/src/routes/endpoints/+page.svelte
index b65ae43f..6f2dc9b9 100644
--- a/frontend/src/routes/endpoints/+page.svelte
+++ b/frontend/src/routes/endpoints/+page.svelte
@@ -21,6 +21,7 @@
import { browser } from '$app/environment';
import { CalendarDate } from "@internationalized/date";
import { projectsState } from '$lib/state/projects.svelte';
+ import { isHealthcheckEndpoint } from '$lib/utils/healthcheck';
import { createRowClickHandler } from '$lib/utils/navigation';
import { resolve } from '$app/paths';
import PageHeader from '$lib/components/issues/page-header.svelte';
@@ -44,6 +45,8 @@
import { ChartLine } from '@lucide/svelte';
const timezone = $derived(getTimezone());
+ const dropHealthyHealthchecks = $derived(projectsState.currentProject?.dropHealthyHealthchecks ?? false);
+ const healthcheckPaths = $derived(projectsState.currentProject?.healthcheckPaths ?? []);
type EndpointStats = {
endpoint: string;
@@ -565,6 +568,9 @@
{#if endpoint.isStream}
<Badge variant="outline" class="font-sans text-xs" title="Streaming response (SSE / WebSocket / long-poll). Excluded from latency, Apdex, and impact scoring.">Stream</Badge>
{/if}
+ {#if dropHealthyHealthchecks && isHealthcheckEndpoint(endpoint.endpoint, healthcheckPaths)}
+ <Badge variant="outline" class="font-sans text-xs" title="Healthcheck endpoint. Only failed requests (status 400+) are stored, so counts and error rates reflect failures only. Configure in project settings.">Healthcheck</Badge>
+ {/if}
{#if endpoint.hasNonRoot}
<NonRootChip mixed={endpoint.hasRoot && endpoint.hasNonRoot} />
{/if}
diff --git a/frontend/src/routes/endpoints/[endpoint]/+page.svelte b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
index 030404b6..6a05e0a1 100644
--- a/frontend/src/routes/endpoints/[endpoint]/+page.svelte
+++ b/frontend/src/routes/endpoints/[endpoint]/+page.svelte
@@ -21,6 +21,7 @@
import { CalendarDate } from '@internationalized/date';
import { ErrorDisplay } from '$lib/components/ui/error-display';
import { projectsState } from '$lib/state/projects.svelte';
+ import { isHealthcheckEndpoint } from '$lib/utils/healthcheck';
import AttributesDisplay from '$lib/components/attributes-display.svelte';
import { createRowClickHandler } from '$lib/utils/navigation';
import { goto } from '$app/navigation';
@@ -376,6 +377,16 @@
</Tooltip.Content>
</Tooltip.Root>
{/if}
+ {#if (projectsState.currentProject?.dropHealthyHealthchecks ?? false) && isHealthcheckEndpoint(decodeURIComponent(data.endpoint), projectsState.currentProject?.healthcheckPaths)}
+ <Tooltip.Root>
+ <Tooltip.Trigger>
+ <Badge variant="outline" class="font-sans">Healthcheck</Badge>
+ </Tooltip.Trigger>
+ <Tooltip.Content side="bottom" class="max-w-xs">
+ Only failed requests (status 400+) are stored for this endpoint, so counts and error rates reflect failures only. Configure in project settings.
+ </Tooltip.Content>
+ </Tooltip.Root>
+ {/if}
{/snippet}
</PageHeader>