The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
progress
ddux72cdc7fe65c1
diff --git a/Dockerfile b/Dockerfileindex 3d68c99e..2df6c2ed 100644--- a/Dockerfile+++ b/Dockerfile@@ -35,7 +35,7 @@ RUN go mod edit -dropreplace=go.tracewayapp.com -dropreplace=go.tracewayapp.com/RUN go mod tidyRUN go mod download-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "localdist,nochdb" -ldflags="-s -w" -o /traceway ./cmd/traceway+RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "localdist,pgch" -ldflags="-s -w" -o /traceway ./cmd/traceway# ==============================================================================# Stage 3: ClickHouse binary sourcediff --git a/Dockerfile.minimal b/Dockerfile.minimalindex 7723c4d1..66381b26 100644--- a/Dockerfile.minimal+++ b/Dockerfile.minimal@@ -46,7 +46,7 @@ RUN go mod tidyRUN go mod download# Build with embedded static files-RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "localdist,nochdb" -ldflags="-s -w" -o /traceway ./cmd/traceway+RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -tags "localdist,pgch" -ldflags="-s -w" -o /traceway ./cmd/traceway# ==============================================================================# Stage 3: Minimal runtime imagediff --git a/Dockerfile.test-pgch b/Dockerfile.test-pgchnew file mode 100644index 00000000..f5abbcd5--- /dev/null+++ b/Dockerfile.test-pgch@@ -0,0 +1,35 @@+# ==============================================================================+# Traceway pgch Test Image+# Runs ClickHouse + PostgreSQL + Go tests in a single container+# ==============================================================================++FROM golang:1.25-bookworm++# Install PostgreSQL + ClickHouse+RUN apt-get update && apt-get install -y --no-install-recommends \+ postgresql \+ postgresql-client \+ sudo \+ ca-certificates \+ curl \+ gnupg \+ && rm -rf /var/lib/apt/lists/*++# Install ClickHouse+RUN curl -fsSL https://packages.clickhouse.com/rpm/lts/repodata/repomd.xml.key | gpg --dearmor -o /usr/share/keyrings/clickhouse-keyring.gpg \+ && echo "deb [signed-by=/usr/share/keyrings/clickhouse-keyring.gpg] https://packages.clickhouse.com/deb stable main" > /etc/apt/sources.list.d/clickhouse.list \+ && apt-get update \+ && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends clickhouse-server clickhouse-client \+ && rm -rf /var/lib/apt/lists/*++# Copy backend source+WORKDIR /app/backend+COPY backend/go.mod backend/go.sum ./+RUN go mod download+COPY backend/ ./++# Copy the entrypoint+COPY scripts/test-pgch-entrypoint.sh /entrypoint.sh+RUN chmod +x /entrypoint.sh++ENTRYPOINT ["/entrypoint.sh"]diff --git a/README.md b/README.mdindex cbeee036..6086da47 100644--- a/README.md+++ b/README.md@@ -6,7 +6,7 @@</picture></p>-<h3 align="center">Error tracking and performance monitoring</h3>+<h3 align="center">Open-source error tracking and performance monitoring for Go applications</h3><p align="center"><a href="https://tracewayapp.com">Website</a> · <a href="https://docs.tracewayapp.com">Docs</a> · <a href="https://github.com/tracewayapp/go-client">Go Client SDK</a>@@ -14,59 +14,128 @@---+Traceway is a self-hosted observability platform that ingests OpenTelemetry traces and metrics, groups exceptions automatically, and gives you endpoint performance, distributed tracing, and alerts — all in a single binary. No OTel Collector or separate time-series database required.++It can run as a standalone server with ClickHouse + PostgreSQL, or **embedded directly inside your Go application** with SQLite for zero-infrastructure local development.+<img width="2452" height="1966" alt="Traceway Dashboard" src="https://github.com/user-attachments/assets/30a4fa24-7d08-4b36-a8f3-42abc73692fd" />## Features-- **OpenTelemetry Compatible** — Replaces the whole stack, does not need the OTel collector or an additional DB.-- **Embeded Golang Mode** — Can run directly in your Go app. Great for local development and testing.-- **Issue Tracking** — Automatic exception grouping with stack traces and contextual tags-- **Endpoint Performance** — P50, P95, P99 latency percentiles with Apdex scoring-- **Predefined SLOs** — Impact score combining Apdex, error rate, P99, and request volume-- **Session Replay** — Replay user sessions to see exactly what happened before an error-- **Embedded Tracing for Go** — Run Traceway inside your Go process with zero infrastructure-- **System Metrics** — CPU, memory, goroutines, and GC monitoring+- **OTel-Native** — Accepts OTLP/HTTP traces and metrics directly, no Collector needed+- **Embedded Mode** — Run Traceway inside your Go process with SQLite, zero external dependencies+- **Issue Tracking** — Automatic exception grouping with normalized stack trace hashing and contextual tags+- **Endpoint Performance** — P50, P95, P99 latency percentiles with Apdex scoring and impact scores- **Distributed Tracing** — Full request traces with span breakdowns+- **Alerts & Notifications** — Configurable rules (error rate, latency thresholds, Apdex drops, metric thresholds) with email, Slack, GitHub, and webhook delivery+- **Session Replay** — Replay user sessions to see exactly what happened before an error+- **System Metrics** — CPU, memory, goroutines, and GC monitoring with custom metric support- **Background Tasks** — Track and monitor async job performance+- **Multi-Tenant** — Organization-based access control with owner, admin, user, and read-only roles## Quick Start+### Docker (standalone server)+```bashdocker compose up --build```-See the [docs](https://docs.tracewayapp.com) for all deployment options and configuration.+Open `http://localhost` to access the dashboard.-## Embedded Mode+See the [self-hosting docs](https://docs.tracewayapp.com/server/docker-compose) for configuration and deployment options.-Run Traceway inside your Go process with zero infrastructure — no Docker, no external databases:+### Embedded Mode (inside your Go app)-1. Install `libchdb`: `curl -sL https://lib.chdb.io | bash`-2. Add the server module: `go get github.com/tracewayapp/traceway/backend`-3. Call `tracewaybackend.Run()` in your app startup+Run Traceway inside your Go process — no Docker, no external databases:-See the [embedded mode docs](https://docs.tracewayapp.com/learn/embedded-mode) for full setup.+```bash+go get github.com/tracewayapp/traceway/backend+```-## Documentation+```go+import tracewaybackend "github.com/tracewayapp/traceway/backend"-Full documentation is available at **[docs.tracewayapp.com](https://docs.tracewayapp.com)**:+func main() {+ go tracewaybackend.Run(+ tracewaybackend.WithPort(8082),+ tracewaybackend.WithDefaultUser("[email protected]", "admin"),+ tracewaybackend.WithDefaultProject("My App", "go", "dev-token"),+ )-- **SDK Integration** — Set up the Go or Node.js client in your application-- **Self-Hosting** — Deploy with Docker Compose or on your own infrastructure-- **Concepts** — How tracing, exception grouping, and metrics work+ // ... start your app, point OTel exporter to http://localhost:8082/api/otel/v1/traces+}+```++Open `http://localhost:8082`, log in, and hit your app to see traces appear.++See the [embedded mode guide](https://docs.tracewayapp.com/learn/embedded-mode) for the full step-by-step setup with OpenTelemetry, or check the [working example](./examples/embedded-backend-otel).++## Tech Stack-## More Screenshots+| Component | Technology |+|-----------|------------|+| Backend | Go 1.25, Gin |+| Frontend | SvelteKit 2, Svelte 5, Tailwind CSS v4 |+| Telemetry DB | ClickHouse (standalone) or SQLite (embedded) |+| Relational DB | PostgreSQL (standalone) or SQLite (embedded) |+| Client SDKs | [Go](https://github.com/tracewayapp/go-client), OpenTelemetry (any language) |-See the [`/printscreens`](./printscreens) directory for screenshots of all pages.+## Screenshots++| | |+|---|---|+|  |  |+|  |  |+|  |  |## Project Structure| Directory | Description ||-----------|-------------|-| `backend/` | Go/Gin API server with ClickHouse and PostgreSQL |-| `frontend/` | SvelteKit 2 dashboard application |+| `backend/` | Go/Gin API server — telemetry ingestion, REST API, notifications, migrations |+| `frontend/` | SvelteKit 2 dashboard SPA |+| `docs/` | Documentation site (Nextra) |+| `examples/` | Working examples for embedded mode ([OTel](./examples/embedded-backend-otel), [Go client](./examples/embedded-backend-go-client)) || `website/` | Landing page |-| `docs/` | Documentation source |++## Build Tags++| Tag | Purpose |+|-----|---------|+| *(none)* | SQLite storage — embedded mode, zero dependencies. This is the default. |+| `pgch` | ClickHouse + PostgreSQL storage — standalone server mode. |+| `localdist` | Embeds the pre-built frontend into the Go binary. Used in Docker builds. |++```bash+# Embedded mode (SQLite, default)+cd backend && go build ./cmd/traceway++# Standalone server (ClickHouse + PostgreSQL)+cd backend && go build -tags pgch ./cmd/traceway++# Docker image (embedded frontend + CH/PG)+cd backend && go build -tags "localdist,pgch" ./cmd/traceway+```++## Running Tests++```bash+# SQLite tests (default, no tags needed)+cd backend && go test -v -count=1 ./app/repositories/++# ClickHouse + PostgreSQL tests (requires Docker)+./scripts/test-backend-pgch.sh+```++## Documentation++Full documentation at **[docs.tracewayapp.com](https://docs.tracewayapp.com)**:++- [**Client SDKs**](https://docs.tracewayapp.com/client) — Go, Node.js, and OpenTelemetry integration guides+- [**Self-Hosting**](https://docs.tracewayapp.com/server) — Docker Compose and deployment options+- [**Concepts**](https://docs.tracewayapp.com/learn) — How tracing, exception grouping, metrics, and alerts work+- [**Embedded Mode**](https://docs.tracewayapp.com/learn/embedded-mode) — Run Traceway inside your Go app## Linksdiff --git a/backend/app/chdb/chdb.go b/backend/app/chdb/chdb.goindex 295fb425..5b12bc33 100644--- a/backend/app/chdb/chdb.go+++ b/backend/app/chdb/chdb.go@@ -1,10 +1,11 @@+//go:build pgch+package chdbimport ("github.com/tracewayapp/traceway/backend/app/config""context""crypto/tls"- "database/sql""fmt""strings""time"@@ -21,12 +22,8 @@ type ChConn interface {}var Conn ChConn-var EmbeddedDB *sql.DBfunc Init() error {- if config.Config.ClickhouseType == "embedded" {- return initEmbedded()- }return initExternal()}diff --git a/backend/app/chdb/chdb_sqlite.go b/backend/app/chdb/chdb_sqlite.gonew file mode 100644index 00000000..9a0d1e1f--- /dev/null+++ b/backend/app/chdb/chdb_sqlite.go@@ -0,0 +1,5 @@+//go:build !pgch++package chdb++func Init() error { return nil }diff --git a/backend/app/chdb/embedded.go b/backend/app/chdb/embedded.godeleted file mode 100644index f9abd812..00000000--- a/backend/app/chdb/embedded.go+++ /dev/null@@ -1,442 +0,0 @@-//go:build !nochdb--package chdb--import (- "context"- "database/sql"- "encoding/json"- "fmt"- "strconv"- "strings"- "time"-- "github.com/tracewayapp/traceway/backend/app/config"-- "github.com/ClickHouse/clickhouse-go/v2/lib/column"- "github.com/ClickHouse/clickhouse-go/v2/lib/driver"- chdblib "github.com/chdb-io/chdb-go/chdb"- _ "github.com/chdb-io/chdb-go/chdb/driver"- "github.com/google/uuid"-)--type embeddedConn struct {- session *chdblib.Session-}--func initEmbedded() error {- path := config.Config.ClickhousePath-- // Create session first (global singleton in chdb-go)- var session *chdblib.Session- var err error- if path != "" {- session, err = chdblib.NewSession(path)- } else {- session, err = chdblib.NewSession()- }- if err != nil {- return fmt.Errorf("failed to create chdb session: %w", err)- }-- // Also open sql.DB for migrations (reuses the same session singleton)- dsn := ""- if path != "" {- dsn = "session=" + path- }- db, err := sql.Open("chdb", dsn)- if err != nil {- return fmt.Errorf("failed to open embedded clickhouse: %w", err)- }- EmbeddedDB = db-- Conn = &embeddedConn{session: session}- config.Logln("Initialized embedded ClickHouse (chdb)")- return nil-}--// Query uses the native session API with JSONCompactStrings format,-// bypassing the Parquet driver that cannot serialize UUID columns.-func (c *embeddedConn) Query(ctx context.Context, query string, args ...any) (driver.Rows, error) {- interpolated := interpolateQuery(query, args)- result, err := c.session.Query(interpolated, "JSONCompactStrings")- if err != nil {- return nil, err- }-- buf := result.Buf()- if len(buf) == 0 {- result.Free()- return &embeddedRows{}, nil- }-- var parsed jsonResult- if err := json.Unmarshal(buf, &parsed); err != nil {- result.Free()- return nil, fmt.Errorf("failed to parse query result: %w", err)- }- result.Free()-- cols := make([]string, len(parsed.Meta))- for i, m := range parsed.Meta {- cols[i] = m.Name- }-- return &embeddedRows{columns: cols, data: parsed.Data}, nil-}--func (c *embeddedConn) QueryRow(ctx context.Context, query string, args ...any) driver.Row {- interpolated := interpolateQuery(query, args)- result, err := c.session.Query(interpolated, "JSONCompactStrings")- if err != nil {- return &embeddedRow{err: err}- }-- buf := result.Buf()- if len(buf) == 0 {- result.Free()- return &embeddedRow{err: sql.ErrNoRows}- }-- var parsed jsonResult- if err := json.Unmarshal(buf, &parsed); err != nil {- result.Free()- return &embeddedRow{err: fmt.Errorf("failed to parse query result: %w", err)}- }- result.Free()-- if len(parsed.Data) == 0 {- return &embeddedRow{err: sql.ErrNoRows}- }-- return &embeddedRow{data: parsed.Data[0]}-}--func (c *embeddedConn) PrepareBatch(ctx context.Context, query string, opts ...driver.PrepareBatchOption) (driver.Batch, error) {- return &embeddedBatch{session: c.session, query: query}, nil-}--func (c *embeddedConn) Exec(ctx context.Context, query string, args ...any) error {- interpolated := interpolateQuery(query, args)- result, err := c.session.Query(interpolated)- if err != nil {- return err- }- if result != nil {- result.Free()- }- return nil-}--// --- Query interpolation -----func interpolateQuery(query string, args []any) string {- if len(args) == 0 {- return query- }- for _, arg := range args {- query = strings.Replace(query, "?", formatValue(arg), 1)- }- return query-}--// --- JSON result types -----type jsonResult struct {- Meta []jsonMeta `json:"meta"`- Data [][]*string `json:"data"`- Rows int `json:"rows"`-}--type jsonMeta struct {- Name string `json:"name"`- Type string `json:"type"`-}--// --- Rows adapter -----type embeddedRows struct {- columns []string- data [][]*string- index int-}--func (r *embeddedRows) Next() bool {- r.index++- return r.index <= len(r.data)-}--func (r *embeddedRows) Scan(dest ...any) error {- if r.index < 1 || r.index > len(r.data) {- return fmt.Errorf("no current row")- }- row := r.data[r.index-1]- if len(dest) != len(row) {- return fmt.Errorf("scan: expected %d destinations, got %d", len(row), len(dest))- }- for i, d := range dest {- if err := scanValue(d, row[i]); err != nil {- return fmt.Errorf("column %d: %w", i, err)- }- }- return nil-}--func (r *embeddedRows) Close() error { return nil }-func (r *embeddedRows) Err() error { return nil }-func (r *embeddedRows) Columns() []string { return r.columns }-func (r *embeddedRows) ScanStruct(dest any) error { return fmt.Errorf("ScanStruct not supported in embedded mode") }-func (r *embeddedRows) ColumnTypes() []driver.ColumnType { return nil }-func (r *embeddedRows) Totals(dest ...any) error { return nil }--// --- Row adapter -----type embeddedRow struct {- data []*string- err error-}--func (r *embeddedRow) Scan(dest ...any) error {- if r.err != nil {- return r.err- }- if len(dest) != len(r.data) {- return fmt.Errorf("scan: expected %d destinations, got %d", len(r.data), len(dest))- }- for i, d := range dest {- if err := scanValue(d, r.data[i]); err != nil {- return fmt.Errorf("column %d: %w", i, err)- }- }- return nil-}--func (r *embeddedRow) Err() error { return r.err }-func (r *embeddedRow) ScanStruct(dest any) error { return fmt.Errorf("ScanStruct not supported in embedded mode") }--// --- Scan helper: convert JSON string values to Go types -----func scanValue(dest any, src *string) error {- if src == nil {- return nil // NULL — leave dest as zero value- }- val := *src-- switch d := dest.(type) {- case *string:- *d = val- case *uuid.UUID:- id, err := uuid.Parse(val)- if err != nil {- return fmt.Errorf("parse UUID %q: %w", val, err)- }- *d = id- case **uuid.UUID:- id, err := uuid.Parse(val)- if err != nil {- return fmt.Errorf("parse UUID %q: %w", val, err)- }- *d = &id- case *time.Time:- for _, layout := range []string{- "2006-01-02 15:04:05.000000000",- "2006-01-02 15:04:05.000000",- "2006-01-02 15:04:05.000",- "2006-01-02 15:04:05",- } {- if t, err := time.Parse(layout, val); err == nil {- *d = t- return nil- }- }- return fmt.Errorf("parse time %q: no matching layout", val)- case *time.Duration:- v, err := strconv.ParseInt(val, 10, 64)- if err != nil {- return err- }- *d = time.Duration(v)- case *bool:- *d = val == "true" || val == "1"- case *int:- v, err := strconv.Atoi(val)- if err != nil {- return err- }- *d = v- case *int8:- v, err := strconv.ParseInt(val, 10, 8)- if err != nil {- return err- }- *d = int8(v)- case *int16:- v, err := strconv.ParseInt(val, 10, 16)- if err != nil {- return err- }- *d = int16(v)- case *int32:- v, err := strconv.ParseInt(val, 10, 32)- if err != nil {- return err- }- *d = int32(v)- case *int64:- v, err := strconv.ParseInt(val, 10, 64)- if err != nil {- return err- }- *d = v- case *uint:- v, err := strconv.ParseUint(val, 10, 64)- if err != nil {- return err- }- *d = uint(v)- case *uint8:- v, err := strconv.ParseUint(val, 10, 8)- if err != nil {- return err- }- *d = uint8(v)- case *uint16:- v, err := strconv.ParseUint(val, 10, 16)- if err != nil {- return err- }- *d = uint16(v)- case *uint32:- v, err := strconv.ParseUint(val, 10, 32)- if err != nil {- return err- }- *d = uint32(v)- case *uint64:- v, err := strconv.ParseUint(val, 10, 64)- if err != nil {- return err- }- *d = v- case *float32:- v, err := strconv.ParseFloat(val, 32)- if err != nil {- return err- }- *d = float32(v)- case *float64:- v, err := strconv.ParseFloat(val, 64)- if err != nil {- return err- }- *d = v- default:- return fmt.Errorf("unsupported scan type %T", dest)- }- return nil-}--// --- Batch adapter -----type embeddedBatch struct {- session *chdblib.Session- query string- rows [][]any- sent bool-}--func (b *embeddedBatch) Append(v ...any) error {- b.rows = append(b.rows, v)- return nil-}--func (b *embeddedBatch) Send() error {- if len(b.rows) == 0 {- b.sent = true- return nil- }-- var sb strings.Builder- sb.WriteString(b.query)- sb.WriteString(" VALUES ")-- for i, row := range b.rows {- if i > 0 {- sb.WriteString(", ")- }- sb.WriteString("(")- for j, v := range row {- if j > 0 {- sb.WriteString(", ")- }- sb.WriteString(formatValue(v))- }- sb.WriteString(")")- }-- result, err := b.session.Query(sb.String())- if err != nil {- return err- }- if result != nil {- result.Free()- }- b.sent = true- return err-}--func (b *embeddedBatch) Abort() error { return nil }-func (b *embeddedBatch) AppendStruct(v any) error { return fmt.Errorf("AppendStruct not supported in embedded mode") }-func (b *embeddedBatch) Column(int) driver.BatchColumn { return nil }-func (b *embeddedBatch) Flush() error { return nil }-func (b *embeddedBatch) IsSent() bool { return b.sent }-func (b *embeddedBatch) Rows() int { return len(b.rows) }-func (b *embeddedBatch) Columns() []column.Interface { return nil }-func (b *embeddedBatch) Close() error { return nil }--// --- Value formatting for batch INSERTs and query interpolation -----func formatValue(v any) string {- if v == nil {- return "NULL"- }- switch val := v.(type) {- case string:- return "'" + strings.ReplaceAll(val, "'", "\\'") + "'"- case uuid.UUID:- return "'" + val.String() + "'"- case time.Time:- return "'" + val.UTC().Format("2006-01-02 15:04:05") + "'"- case bool:- if val {- return "1"- }- return "0"- case int:- return fmt.Sprintf("%d", val)- case int8:- return fmt.Sprintf("%d", val)- case int16:- return fmt.Sprintf("%d", val)- case int32:- return fmt.Sprintf("%d", val)- case int64:- return fmt.Sprintf("%d", val)- case uint:- return fmt.Sprintf("%d", val)- case uint8:- return fmt.Sprintf("%d", val)- case uint16:- return fmt.Sprintf("%d", val)- case uint32:- return fmt.Sprintf("%d", val)- case uint64:- return fmt.Sprintf("%d", val)- case float32:- return fmt.Sprintf("%v", val)- case float64:- return fmt.Sprintf("%v", val)- default:- return "'" + strings.ReplaceAll(fmt.Sprintf("%v", v), "'", "\\'") + "'"- }-}diff --git a/backend/app/chdb/embedded_stub.go b/backend/app/chdb/embedded_stub.godeleted file mode 100644index d7082dc2..00000000--- a/backend/app/chdb/embedded_stub.go+++ /dev/null@@ -1,9 +0,0 @@-//go:build nochdb--package chdb--import "fmt"--func initEmbedded() error {- return fmt.Errorf("embedded ClickHouse not available — this binary was built with the nochdb tag")-}diff --git a/backend/app/config/config.go b/backend/app/config/config.goindex 26126760..e2c43be7 100644--- a/backend/app/config/config.go+++ b/backend/app/config/config.go@@ -14,13 +14,11 @@ type Cfg struct {PostgresSSLMode stringSQLitePath string- ClickhouseType stringClickhouseServer stringClickhouseDatabase stringClickhouseUsername stringClickhousePassword stringClickhouseTLS string- ClickhousePath stringStorageType stringStoragePath string@@ -62,13 +60,11 @@ func LoadFromEnv() *Cfg {PostgresSSLMode: os.Getenv("POSTGRES_SSLMODE"),SQLitePath: os.Getenv("SQLITE_PATH"),- ClickhouseType: os.Getenv("CLICKHOUSE_TYPE"),ClickhouseServer: os.Getenv("CLICKHOUSE_SERVER"),ClickhouseDatabase: os.Getenv("CLICKHOUSE_DATABASE"),ClickhouseUsername: os.Getenv("CLICKHOUSE_USERNAME"),ClickhousePassword: os.Getenv("CLICKHOUSE_PASSWORD"),ClickhouseTLS: os.Getenv("CLICKHOUSE_TLS"),- ClickhousePath: os.Getenv("CLICKHOUSE_PATH"),StorageType: os.Getenv("STORAGE_TYPE"),StoragePath: os.Getenv("STORAGE_PATH"),diff --git a/backend/app/migrations/migrations.go b/backend/app/migrations/migrations_default.gosimilarity index 70%rename from backend/app/migrations/migrations.gorename to backend/app/migrations/migrations_default.goindex f01dae58..5889e708 100644--- a/backend/app/migrations/migrations.go+++ b/backend/app/migrations/migrations_default.go@@ -1,3 +1,5 @@+//go:build pgch+package migrationsimport (@@ -8,7 +10,6 @@ import ("sort""strings"- "github.com/tracewayapp/traceway/backend/app/chdb""github.com/tracewayapp/traceway/backend/app/config""github.com/tracewayapp/traceway/backend/app/db"@@ -190,86 +191,18 @@ func runMigrationsSQLite(db *sql.DB) error {return nil}-func runMigrationsEmbeddedClickhouse(chDB *sql.DB) error {- _, err := chDB.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations_ch (- version String,- applied_at DateTime DEFAULT now()- ) ENGINE = MergeTree() ORDER BY version`)- if err != nil {- return fmt.Errorf("failed to create schema_migrations_ch table: %w", err)- }-- entries, err := migrationsChFS.ReadDir("ch")- if err != nil {- return fmt.Errorf("failed to read ch migrations dir: %w", err)- }-- var files []string- for _, e := range entries {- if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {- files = append(files, e.Name())- }- }- sort.Strings(files)-- for _, file := range files {- version := strings.TrimSuffix(file, ".up.sql")-- rows, err := chDB.Query("SELECT count() FROM schema_migrations_ch WHERE version = ?", version)- if err != nil {- return fmt.Errorf("failed to check migration version %s: %w", version, err)- }- var count int- if rows.Next() {- if err := rows.Scan(&count); err != nil {- rows.Close()- return fmt.Errorf("failed to scan migration count for %s: %w", version, err)- }- }- rows.Close()- if count > 0 {- continue- }-- content, err := migrationsChFS.ReadFile("ch/" + file)- if err != nil {- return fmt.Errorf("failed to read migration file %s: %w", file, err)- }-- stmt := strings.TrimSpace(string(content))- if stmt == "" {- continue- }- if _, err := chDB.Exec(stmt); err != nil {- return fmt.Errorf("failed to execute migration %s: %w", file, err)- }-- if _, err := chDB.Exec("INSERT INTO schema_migrations_ch (version) VALUES (?)", version); err != nil {- return fmt.Errorf("failed to record migration version %s: %w", version, err)- }- }-- return nil-}-func Run(dbType string) error {cfg := config.Config// Run ClickHouse migrations- if cfg.ClickhouseType == "embedded" {- if err := runMigrationsEmbeddedClickhouse(chdb.EmbeddedDB); err != nil {- return fmt.Errorf("embedded clickhouse migrations failed: %w", err)- }- } else {- tlsConfig := "&secure=true"- if cfg.ClickhouseTLS == "false" {- tlsConfig = ""- }+ tlsConfig := "&secure=true"+ if cfg.ClickhouseTLS == "false" {+ tlsConfig = ""+ }- err := runMigrationsClickhouse(fmt.Sprintf(`clickhouse://%s?username=%s&password=%s&database=%s%s`, cfg.ClickhouseServer, url.QueryEscape(cfg.ClickhouseUsername), url.QueryEscape(cfg.ClickhousePassword), cfg.ClickhouseDatabase, tlsConfig))- if err != nil {- return fmt.Errorf("clickhouse migrations failed: %w", err)- }+ err := runMigrationsClickhouse(fmt.Sprintf(`clickhouse://%s?username=%s&password=%s&database=%s%s`, cfg.ClickhouseServer, url.QueryEscape(cfg.ClickhouseUsername), url.QueryEscape(cfg.ClickhousePassword), cfg.ClickhouseDatabase, tlsConfig))+ if err != nil {+ return fmt.Errorf("clickhouse migrations failed: %w", err)}if dbType == "sqlite" {diff --git a/backend/app/migrations/migrations_sqlite.go b/backend/app/migrations/migrations_sqlite.gonew file mode 100644index 00000000..b0a9a687--- /dev/null+++ b/backend/app/migrations/migrations_sqlite.go@@ -0,0 +1,83 @@+//go:build !pgch++package migrations++import (+ "embed"+ "fmt"+ "sort"+ "strings"++ "github.com/tracewayapp/traceway/backend/app/db"+)++type ExtensionMigration struct {+ Source embed.FS+ Path string+ Table string+}++var ExtensionPostgresMigrations []ExtensionMigration++//go:embed sqlite/*.sql+var migrationsSqliteFS embed.FS++func Run(dbType string) error {+ sqliteDB := db.DB++ _, err := sqliteDB.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (+ version TEXT PRIMARY KEY,+ applied_at DATETIME DEFAULT (datetime('now'))+ )`)+ if err != nil {+ return fmt.Errorf("failed to create schema_migrations table: %w", err)+ }++ entries, err := migrationsSqliteFS.ReadDir("sqlite")+ if err != nil {+ return fmt.Errorf("failed to read sqlite migrations dir: %w", err)+ }++ var files []string+ for _, e := range entries {+ if !e.IsDir() && strings.HasSuffix(e.Name(), ".up.sql") {+ files = append(files, e.Name())+ }+ }+ sort.Strings(files)++ for _, file := range files {+ version := strings.TrimSuffix(file, ".up.sql")++ var count int+ err := sqliteDB.QueryRow("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", version).Scan(&count)+ if err != nil {+ return fmt.Errorf("failed to check migration version %s: %w", version, err)+ }+ if count > 0 {+ continue+ }++ content, err := migrationsSqliteFS.ReadFile("sqlite/" + file)+ if err != nil {+ return fmt.Errorf("failed to read migration file %s: %w", file, err)+ }++ statements := strings.Split(string(content), ";")+ for _, stmt := range statements {+ stmt = strings.TrimSpace(stmt)+ if stmt == "" {+ continue+ }+ if _, err := sqliteDB.Exec(stmt); err != nil {+ return fmt.Errorf("failed to execute migration %s: %w", file, err)+ }+ }++ if _, err := sqliteDB.Exec("INSERT INTO schema_migrations (version) VALUES (?)", version); err != nil {+ return fmt.Errorf("failed to record migration version %s: %w", version, err)+ }+ }++ return nil+}diff --git a/backend/app/migrations/sqlite/0002_telemetry_tables.up.sql b/backend/app/migrations/sqlite/0002_telemetry_tables.up.sqlnew file mode 100644index 00000000..8ae8a39e--- /dev/null+++ b/backend/app/migrations/sqlite/0002_telemetry_tables.up.sql@@ -0,0 +1,104 @@+CREATE TABLE IF NOT EXISTS endpoints (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ endpoint TEXT NOT NULL DEFAULT '',+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL,+ status_code INTEGER NOT NULL DEFAULT 0,+ body_size INTEGER NOT NULL DEFAULT 0,+ client_ip TEXT NOT NULL DEFAULT '',+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT ''+);+CREATE INDEX IF NOT EXISTS idx_endpoints_project_recorded ON endpoints(project_id, recorded_at);+CREATE INDEX IF NOT EXISTS idx_endpoints_project_endpoint ON endpoints(project_id, endpoint);++CREATE TABLE IF NOT EXISTS tasks (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ task_name TEXT NOT NULL DEFAULT '',+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL,+ client_ip TEXT NOT NULL DEFAULT '',+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT ''+);+CREATE INDEX IF NOT EXISTS idx_tasks_project_recorded ON tasks(project_id, recorded_at);++CREATE TABLE IF NOT EXISTS exception_stack_traces (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ trace_id TEXT,+ trace_type TEXT NOT NULL DEFAULT 'endpoint',+ exception_hash TEXT NOT NULL DEFAULT '',+ stack_trace TEXT NOT NULL DEFAULT '',+ recorded_at DATETIME NOT NULL,+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT '',+ is_message INTEGER NOT NULL DEFAULT 0+);+CREATE INDEX IF NOT EXISTS idx_exceptions_project_recorded ON exception_stack_traces(project_id, recorded_at);+CREATE INDEX IF NOT EXISTS idx_exceptions_project_hash ON exception_stack_traces(project_id, exception_hash);++CREATE TABLE IF NOT EXISTS spans (+ id TEXT NOT NULL,+ trace_id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ start_time DATETIME NOT NULL,+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_spans_project_trace ON spans(project_id, trace_id);++CREATE TABLE IF NOT EXISTS metric_points (+ project_id TEXT NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ value REAL NOT NULL DEFAULT 0,+ tags TEXT NOT NULL DEFAULT '{}',+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_metric_points_project_name ON metric_points(project_id, name, recorded_at);++CREATE TABLE IF NOT EXISTS session_recordings (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ exception_id TEXT NOT NULL,+ file_path TEXT NOT NULL DEFAULT '',+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_session_recordings_project_exception ON session_recordings(project_id, exception_id);++CREATE TABLE IF NOT EXISTS archived_exceptions (+ project_id TEXT NOT NULL,+ exception_hash TEXT NOT NULL,+ archived_at DATETIME NOT NULL DEFAULT (datetime('now')),+ UNIQUE(project_id, exception_hash)+);++CREATE TABLE IF NOT EXISTS slow_endpoints (+ project_id TEXT NOT NULL,+ endpoint TEXT NOT NULL,+ offset_ms INTEGER NOT NULL DEFAULT 0,+ reason TEXT NOT NULL DEFAULT '',+ UNIQUE(project_id, endpoint)+);++CREATE TABLE IF NOT EXISTS fired_notifications (+ project_id TEXT NOT NULL,+ rule_id INTEGER NOT NULL DEFAULT 0,+ rule_type TEXT NOT NULL DEFAULT '',+ rule_name TEXT NOT NULL DEFAULT '',+ channel_type TEXT NOT NULL DEFAULT '',+ channel_name TEXT NOT NULL DEFAULT '',+ severity TEXT NOT NULL DEFAULT '',+ subject TEXT NOT NULL DEFAULT '',+ body TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT '',+ error_message TEXT NOT NULL DEFAULT '',+ endpoint TEXT NOT NULL DEFAULT '',+ fired_at DATETIME NOT NULL+);diff --git a/backend/app/notifications/evaluator_event.go b/backend/app/notifications/evaluator_event.goindex 6d2516d8..31605115 100644--- a/backend/app/notifications/evaluator_event.go+++ b/backend/app/notifications/evaluator_event.go@@ -1,61 +1,20 @@+//go:build pgch+package notificationsimport ("context"- "database/sql""encoding/json""fmt"- "log"- "strings""time""github.com/google/uuid""github.com/tracewayapp/traceway/backend/app/chdb"- "github.com/tracewayapp/traceway/backend/app/db""github.com/tracewayapp/traceway/backend/app/hooks""github.com/tracewayapp/traceway/backend/app/models"- "github.com/tracewayapp/traceway/backend/app/repositories"traceway "go.tracewayapp.com")-func registerReportHook() {- hooks.RegisterReportHook(func(event hooks.ReportEvent) {- if len(event.ExceptionHashes) == 0 {- return- }- go evaluateEventRules(event)- })-}--func evaluateEventRules(event hooks.ReportEvent) {- rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {- return repositories.NotificationRuleRepository.FindEnabledEventRules(tx, event.ProjectId)- })- if err != nil {- traceway.CaptureException(fmt.Errorf("failed to load event notification rules: %w", err))- return- }-- ctx := context.Background()-- for _, rule := range rules {- if rule.SnoozedUntil != nil && rule.SnoozedUntil.After(time.Now()) {- continue- }-- switch rule.RuleType {- case "new_error":- evaluateNewError(ctx, rule, event)- case "error_regression":- evaluateErrorRegression(ctx, rule, event)- }- }-}--type newErrorConfig struct {- IgnorePatterns []string `json:"ignorePatterns"`-}-func evaluateNewError(ctx context.Context, rule *models.NotificationRuleWithChannel, event hooks.ReportEvent) {var cfg newErrorConfigjson.Unmarshal(rule.Config, &cfg)@@ -177,43 +136,3 @@ func getExceptionDetails(ctx context.Context, projectId uuid.UUID, hash string)details.ErrorType = extractErrorType(stackTrace)return details}--func extractErrorType(stackTrace string) string {- if stackTrace == "" {- return "Unknown Error"- }- lines := strings.SplitN(stackTrace, "\n", 2)- if len(lines) > 0 {- line := strings.TrimSpace(lines[0])- if idx := strings.Index(line, ":"); idx > 0 {- return line[:idx]- }- return line- }- return "Unknown Error"-}--func getProjectName(projectId uuid.UUID) string {- project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {- return repositories.ProjectRepository.FindById(tx, projectId)- })- if err != nil || project == nil {- return ""- }- return project.Name-}--func shouldIgnore(errorType string, patterns []string) bool {- lower := strings.ToLower(errorType)- for _, pattern := range patterns {- pattern = strings.ToLower(strings.TrimSpace(pattern))- if pattern == "" {- continue- }- pattern = strings.ReplaceAll(pattern, "*", "")- if strings.Contains(lower, pattern) {- return true- }- }- return false-}diff --git a/backend/app/notifications/evaluator_event_sqlite.go b/backend/app/notifications/evaluator_event_sqlite.gonew file mode 100644index 00000000..d2cf243f--- /dev/null+++ b/backend/app/notifications/evaluator_event_sqlite.go@@ -0,0 +1,137 @@+//go:build !pgch++package notifications++import (+ "context"+ "database/sql"+ "encoding/json"+ "fmt"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/hooks"+ "github.com/tracewayapp/traceway/backend/app/models"+ traceway "go.tracewayapp.com"+)++func evaluateNewError(ctx context.Context, rule *models.NotificationRuleWithChannel, event hooks.ReportEvent) {+ var cfg newErrorConfig+ json.Unmarshal(rule.Config, &cfg)++ for _, hash := range event.ExceptionHashes {+ dedupKey := fmt.Sprintf("%d:%s", rule.Id, hash)+ if dedup.isDuplicate(dedupKey, time.Duration(rule.CooldownMinutes)*time.Minute) {+ continue+ }++ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ?",+ event.ProjectId.String(), hash).Scan(&count)+ if err != nil {+ traceway.CaptureException(fmt.Errorf("new_error check failed: %w", err))+ continue+ }++ if count > 1 {+ var archivedCount int64+ archErr := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM archived_exceptions WHERE project_id = ? AND exception_hash = ?",+ event.ProjectId.String(), hash).Scan(&archivedCount)+ if archErr != nil || archivedCount == 0 {+ continue+ }++ var postArchiveCount int64+ archErr = db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? AND recorded_at > (SELECT MAX(archived_at) FROM archived_exceptions WHERE project_id = ? AND exception_hash = ?)",+ event.ProjectId.String(), hash, event.ProjectId.String(), hash).Scan(&postArchiveCount)+ if archErr != nil {+ traceway.CaptureException(fmt.Errorf("new_error post-archive count failed: %w", archErr))+ continue+ }++ if postArchiveCount > 1 {+ continue+ }+ }++ details := getExceptionDetails(ctx, event.ProjectId, hash)++ if shouldIgnore(details.ErrorType, cfg.IgnorePatterns) {+ continue+ }++ dedup.record(dedupKey)+ projectName := getProjectName(rule.ProjectId)+ msg := buildNewErrorMessage(details, projectName)+ dispatch(rule, msg)+ }+}++func evaluateErrorRegression(ctx context.Context, rule *models.NotificationRuleWithChannel, event hooks.ReportEvent) {+ for _, hash := range event.ExceptionHashes {+ dedupKey := fmt.Sprintf("%d:%s", rule.Id, hash)+ if dedup.isDuplicate(dedupKey, time.Duration(rule.CooldownMinutes)*time.Minute) {+ continue+ }++ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM archived_exceptions WHERE project_id = ? AND exception_hash = ?",+ event.ProjectId.String(), hash).Scan(&count)+ if err != nil {+ traceway.CaptureException(fmt.Errorf("error_regression check failed: %w", err))+ continue+ }++ if count == 0 {+ continue+ }++ details := getExceptionDetails(ctx, event.ProjectId, hash)+ dedup.record(dedupKey)+ projectName := getProjectName(rule.ProjectId)+ msg := buildErrorRegressionMessage(details, projectName)+ dispatch(rule, msg)+ }+}++func getExceptionDetails(ctx context.Context, projectId uuid.UUID, hash string) ExceptionDetails {+ var idStr, stackTrace, appVersion, serverName, attributesJSON, recordedAtStr string++ err := db.DB.QueryRowContext(ctx,+ "SELECT id, stack_trace, attributes, app_version, server_name, recorded_at FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT 1",+ projectId.String(), hash).Scan(&idStr, &stackTrace, &attributesJSON, &appVersion, &serverName, &recordedAtStr)++ details := ExceptionDetails{+ Hash: hash,+ }++ if err != nil {+ if err == sql.ErrNoRows {+ details.ErrorType = "Unknown Error"+ return details+ }+ details.ErrorType = "Unknown Error"+ return details+ }++ details.Id = idStr+ details.StackTrace = stackTrace+ details.AppVersion = appVersion+ details.ServerName = serverName+ details.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)++ if attributesJSON != "" && attributesJSON != "{}" {+ attrs := make(map[string]string)+ if jsonErr := json.Unmarshal([]byte(attributesJSON), &attrs); jsonErr == nil {+ details.Attributes = attrs+ }+ }++ details.ErrorType = extractErrorType(stackTrace)+ return details+}diff --git a/backend/app/notifications/evaluator_helpers.go b/backend/app/notifications/evaluator_helpers.gonew file mode 100644index 00000000..bdb9d163--- /dev/null+++ b/backend/app/notifications/evaluator_helpers.go@@ -0,0 +1,94 @@+package notifications++import (+ "context"+ "database/sql"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/hooks"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+ traceway "go.tracewayapp.com"+)++type newErrorConfig struct {+ IgnorePatterns []string `json:"ignorePatterns"`+}++func registerReportHook() {+ hooks.RegisterReportHook(func(event hooks.ReportEvent) {+ if len(event.ExceptionHashes) == 0 {+ return+ }+ go evaluateEventRules(event)+ })+}++func evaluateEventRules(event hooks.ReportEvent) {+ rules, err := db.ExecuteTransaction(func(tx *sql.Tx) ([]*models.NotificationRuleWithChannel, error) {+ return repositories.NotificationRuleRepository.FindEnabledEventRules(tx, event.ProjectId)+ })+ if err != nil {+ traceway.CaptureException(fmt.Errorf("failed to load event notification rules: %w", err))+ return+ }++ ctx := context.Background()++ for _, rule := range rules {+ if rule.SnoozedUntil != nil && rule.SnoozedUntil.After(time.Now()) {+ continue+ }++ switch rule.RuleType {+ case "new_error":+ evaluateNewError(ctx, rule, event)+ case "error_regression":+ evaluateErrorRegression(ctx, rule, event)+ }+ }+}++func extractErrorType(stackTrace string) string {+ if stackTrace == "" {+ return "Unknown Error"+ }+ lines := strings.SplitN(stackTrace, "\n", 2)+ if len(lines) > 0 {+ line := strings.TrimSpace(lines[0])+ if idx := strings.Index(line, ":"); idx > 0 {+ return line[:idx]+ }+ return line+ }+ return "Unknown Error"+}++func getProjectName(projectId uuid.UUID) string {+ project, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.Project, error) {+ return repositories.ProjectRepository.FindById(tx, projectId)+ })+ if err != nil || project == nil {+ return ""+ }+ return project.Name+}++func shouldIgnore(errorType string, patterns []string) bool {+ lower := strings.ToLower(errorType)+ for _, pattern := range patterns {+ pattern = strings.ToLower(strings.TrimSpace(pattern))+ if pattern == "" {+ continue+ }+ pattern = strings.ReplaceAll(pattern, "*", "")+ if strings.Contains(lower, pattern) {+ return true+ }+ }+ return false+}diff --git a/backend/app/notifications/evaluator_polled.go b/backend/app/notifications/evaluator_polled.goindex e7e39544..18adb55e 100644--- a/backend/app/notifications/evaluator_polled.go+++ b/backend/app/notifications/evaluator_polled.go@@ -1,3 +1,5 @@+//go:build pgch+package notificationsimport (diff --git a/backend/app/notifications/evaluator_polled_sqlite.go b/backend/app/notifications/evaluator_polled_sqlite.gonew file mode 100644index 00000000..7fbba491--- /dev/null+++ b/backend/app/notifications/evaluator_polled_sqlite.go@@ -0,0 +1,822 @@+//go:build !pgch++package notifications++import (+ "context"+ "encoding/json"+ "fmt"+ "math"+ "sort"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories"+)++type EvalResult struct {+ Fired bool+ Message Message+ Messages []Message+}++type RuleEvaluator func(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error)++var polledEvaluators = map[string]RuleEvaluator{+ "error_rate_threshold": evaluateErrorRateThreshold,+ "endpoint_p95_threshold": evaluateEndpointP95Threshold,+ "endpoint_p99_threshold": evaluateEndpointP99Threshold,+ "apdex_drop": evaluateApdexDrop,+ "metric_threshold": evaluateMetricThreshold,+ "no_data": evaluateNoData,+ "error_count_threshold": evaluateErrorCountThreshold,+ "task_duration_threshold": evaluateTaskDurationThreshold,+ "throughput_drop": evaluateThroughputDrop,+ "endpoint_error_rate": evaluateEndpointErrorRate,+ "impact_score_critical": evaluateImpactScoreCritical,+ "impact_score_high": evaluateImpactScoreHigh,+ "impact_score_medium": evaluateImpactScoreMedium,+}++// --- Error Rate Threshold ---++type errorRateConfig struct {+ ThresholdPercent float64 `json:"thresholdPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateErrorRateThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg errorRateConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid error_rate_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var total, errors int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) as total, SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) as errors FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(&total, &errors)+ if err != nil {+ return nil, err+ }++ if total < int64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ rate := float64(errors) / float64(total) * 100+ if rate < cfg.ThresholdPercent {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildErrorRateMessage(rate, cfg.ThresholdPercent, cfg.LookbackMinutes, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint P95 Threshold ---++type endpointLatencyConfig struct {+ Endpoint string `json:"endpoint"`+ ThresholdMs float64 `json:"thresholdMs"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateEndpointP95Threshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointLatencyConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_p95_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ p95 := queryPercentile(ctx, projectId, cfg.Endpoint, from, now, 0.95)++ if p95 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ endpoint := cfg.Endpoint+ if endpoint == "" || endpoint == "*" {+ endpoint = "all endpoints"+ }+ projectName := getProjectName(projectId)+ msg := buildEndpointLatencyMessage("P95", p95, cfg.ThresholdMs, endpoint, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint P99 Threshold ---++func evaluateEndpointP99Threshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointLatencyConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_p99_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ p99 := queryPercentile(ctx, projectId, cfg.Endpoint, from, now, 0.99)++ if p99 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ endpoint := cfg.Endpoint+ if endpoint == "" || endpoint == "*" {+ endpoint = "all endpoints"+ }+ projectName := getProjectName(projectId)+ msg := buildEndpointLatencyMessage("P99", p99, cfg.ThresholdMs, endpoint, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++func queryPercentile(ctx context.Context, projectId uuid.UUID, endpoint string, from, to time.Time, pct float64) float64 {+ query := "SELECT duration FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?"+ args := []interface{}{projectId.String(), from.Format(time.RFC3339Nano), to.Format(time.RFC3339Nano)}+ if endpoint != "" && endpoint != "*" {+ query += " AND endpoint = ?"+ args = append(args, endpoint)+ }+ query += " ORDER BY duration ASC"++ rows, err := db.DB.QueryContext(ctx, query, args...)+ if err != nil {+ return 0+ }+ defer rows.Close()++ var durations []float64+ for rows.Next() {+ var d int64+ if err := rows.Scan(&d); err != nil {+ continue+ }+ durations = append(durations, float64(d)/1000000) // ns to ms+ }++ return computePercentile(durations, pct)+}++func computePercentile(sorted []float64, p float64) float64 {+ n := len(sorted)+ if n == 0 {+ return 0+ }+ if n == 1 {+ return sorted[0]+ }+ idx := p * float64(n-1)+ lower := int(idx)+ frac := idx - float64(lower)+ if lower+1 >= n {+ return sorted[lower]+ }+ return sorted[lower]*(1-frac) + sorted[lower+1]*frac+}++// --- Apdex Drop ---++type apdexConfig struct {+ ThresholdApdex float64 `json:"thresholdApdex"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateApdexDrop(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg apdexConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid apdex_drop config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 15+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var total, satisfied, tolerating int64+ err := db.DB.QueryRowContext(ctx,+ `SELECT COUNT(*) as total,+ SUM(CASE WHEN duration <= 750000000 AND status_code < 500 THEN 1 ELSE 0 END) as satisfied,+ SUM(CASE WHEN duration > 750000000 AND duration <= 1500000000 AND status_code < 500 THEN 1 ELSE 0 END) as tolerating+ FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?`,+ projectId.String(), from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(&total, &satisfied, &tolerating)+ if err != nil {+ return nil, err+ }++ if total < int64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ apdex := (float64(satisfied) + float64(tolerating)/2.0) / float64(total)+ if apdex >= cfg.ThresholdApdex {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildApdexDropMessage(apdex, cfg.ThresholdApdex, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Metric Threshold ---++type metricThresholdConfig struct {+ MetricName string `json:"metricName"`+ Operator string `json:"operator"`+ ThresholdValue float64 `json:"thresholdValue"`+ Aggregation string `json:"aggregation"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateMetricThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg metricThresholdConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid metric_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 5+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var value float64+ var err error++ switch cfg.Aggregation {+ case "p95", "p99":+ pct := 0.95+ if cfg.Aggregation == "p99" {+ pct = 0.99+ }+ rows, qErr := db.DB.QueryContext(ctx,+ "SELECT value FROM metric_points WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY value ASC",+ projectId.String(), cfg.MetricName, from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano))+ if qErr != nil {+ return nil, qErr+ }+ defer rows.Close()+ var vals []float64+ for rows.Next() {+ var v float64+ if err := rows.Scan(&v); err != nil {+ continue+ }+ vals = append(vals, v)+ }+ value = computePercentile(vals, pct)+ default:+ aggFunc := "avg"+ switch cfg.Aggregation {+ case "max":+ aggFunc = "max"+ case "min":+ aggFunc = "min"+ case "sum":+ aggFunc = "sum"+ }+ query := fmt.Sprintf("SELECT COALESCE(%s(value), 0) FROM metric_points WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?", aggFunc)+ err = db.DB.QueryRowContext(ctx, query, projectId.String(), cfg.MetricName, from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(&value)+ if err != nil {+ return nil, err+ }+ }++ fired := false+ switch cfg.Operator {+ case "gt":+ fired = value > cfg.ThresholdValue+ case "gte":+ fired = value >= cfg.ThresholdValue+ case "lt":+ fired = value < cfg.ThresholdValue+ case "lte":+ fired = value <= cfg.ThresholdValue+ case "eq":+ fired = value == cfg.ThresholdValue+ }++ if !fired {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildMetricThresholdMessage(cfg.MetricName, value, cfg.Operator, cfg.ThresholdValue, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- No Data ---++type noDataConfig struct {+ DataType string `json:"dataType"`+ SilenceMinutes int `json:"silenceMinutes"`+}++func evaluateNoData(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg noDataConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid no_data config: %w", err)+ }+ if cfg.SilenceMinutes <= 0 {+ cfg.SilenceMinutes = 10+ }++ threshold := time.Now().UTC().Add(-time.Duration(cfg.SilenceMinutes) * time.Minute)+ thresholdStr := threshold.Format(time.RFC3339Nano)+ pid := projectId.String()++ if cfg.DataType == "any" {+ tables := []string{"endpoints", "exception_stack_traces", "metric_points", "tasks"}+ for _, t := range tables {+ var maxTs string+ err := db.DB.QueryRowContext(ctx,+ fmt.Sprintf("SELECT COALESCE(MAX(recorded_at), '') FROM %s WHERE project_id = ?", t),+ pid).Scan(&maxTs)+ if err == nil && maxTs != "" {+ if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs); pErr == nil && parsed.After(threshold) {+ return &EvalResult{Fired: false}, nil+ }+ }+ }+ projectName := getProjectName(projectId)+ msg := buildNoDataMessage("any", cfg.SilenceMinutes, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+ }++ table := ""+ switch cfg.DataType {+ case "endpoints":+ table = "endpoints"+ case "exceptions":+ table = "exception_stack_traces"+ case "metrics":+ table = "metric_points"+ case "tasks":+ table = "tasks"+ default:+ return nil, fmt.Errorf("unknown data type: %s", cfg.DataType)+ }++ var maxTs string+ err := db.DB.QueryRowContext(ctx,+ fmt.Sprintf("SELECT COALESCE(MAX(recorded_at), '') FROM %s WHERE project_id = ?", table),+ pid).Scan(&maxTs)+ if err != nil {+ return nil, err+ }++ if maxTs != "" {+ if parsed, pErr := time.Parse(time.RFC3339Nano, maxTs); pErr == nil && parsed.After(threshold) {+ return &EvalResult{Fired: false}, nil+ }+ }++ _ = thresholdStr+ projectName := getProjectName(projectId)+ msg := buildNoDataMessage(cfg.DataType, cfg.SilenceMinutes, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Error Count Threshold ---++type errorCountConfig struct {+ ThresholdCount int64 `json:"thresholdCount"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateErrorCountThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg errorCountConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid error_count_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 60+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM exception_stack_traces WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND is_message = 0",+ projectId.String(), from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(&count)+ if err != nil {+ return nil, err+ }++ if count < cfg.ThresholdCount {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildErrorCountMessage(count, cfg.ThresholdCount, cfg.LookbackMinutes, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Task Duration Threshold ---++type taskDurationConfig struct {+ TaskName string `json:"taskName"`+ ThresholdMs float64 `json:"thresholdMs"`+ LookbackMinutes int `json:"lookbackMinutes"`+}++func evaluateTaskDurationThreshold(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg taskDurationConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid task_duration_threshold config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 30+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)++ query := "SELECT duration FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?"+ args := []interface{}{projectId.String(), from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)}+ if cfg.TaskName != "" && cfg.TaskName != "*" {+ query += " AND task_name = ?"+ args = append(args, cfg.TaskName)+ }+ query += " ORDER BY duration ASC"++ rows, err := db.DB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var durations []float64+ for rows.Next() {+ var d int64+ if err := rows.Scan(&d); err != nil {+ continue+ }+ durations = append(durations, float64(d)/1000000) // ns to ms+ }++ p95 := computePercentile(durations, 0.95)++ if p95 < cfg.ThresholdMs {+ return &EvalResult{Fired: false}, nil+ }++ taskName := cfg.TaskName+ if taskName == "" || taskName == "*" {+ taskName = "all tasks"+ }+ projectName := getProjectName(projectId)+ msg := buildTaskDurationMessage(taskName, p95, cfg.ThresholdMs, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Throughput Drop ---++type throughputDropConfig struct {+ DropPercent float64 `json:"dropPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ BaselineWindowMinutes int `json:"baselineWindowMinutes"`+}++func evaluateThroughputDrop(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg throughputDropConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid throughput_drop config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 15+ }+ if cfg.BaselineWindowMinutes <= 0 {+ cfg.BaselineWindowMinutes = 60+ }++ now := time.Now().UTC()+ lookbackFrom := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)+ baselineFrom := lookbackFrom.Add(-time.Duration(cfg.BaselineWindowMinutes) * time.Minute)+ pid := projectId.String()++ var currentCount int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ pid, lookbackFrom.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(¤tCount)+ if err != nil {+ return nil, err+ }++ var baselineCount int64+ err = db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ pid, baselineFrom.Format(time.RFC3339Nano), lookbackFrom.Format(time.RFC3339Nano)).Scan(&baselineCount)+ if err != nil {+ return nil, err+ }++ if baselineCount == 0 {+ return &EvalResult{Fired: false}, nil+ }++ normalizedBaseline := float64(baselineCount) * float64(cfg.LookbackMinutes) / float64(cfg.BaselineWindowMinutes)+ if normalizedBaseline == 0 {+ return &EvalResult{Fired: false}, nil+ }++ dropPercent := (1 - float64(currentCount)/normalizedBaseline) * 100+ if dropPercent < cfg.DropPercent {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildThroughputDropMessage(dropPercent, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Endpoint Error Rate ---++type endpointErrorRateConfig struct {+ Endpoint string `json:"endpoint"`+ ThresholdPercent float64 `json:"thresholdPercent"`+ LookbackMinutes int `json:"lookbackMinutes"`+ MinRequests int `json:"minRequests"`+}++func evaluateEndpointErrorRate(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ var cfg endpointErrorRateConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid endpoint_error_rate config: %w", err)+ }+ if cfg.LookbackMinutes <= 0 {+ cfg.LookbackMinutes = 10+ }++ now := time.Now().UTC()+ from := now.Add(-time.Duration(cfg.LookbackMinutes) * time.Minute)+ pid := projectId.String()++ var total, errors int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) as total, SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) as errors FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?",+ pid, cfg.Endpoint, from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano)).Scan(&total, &errors)+ if err != nil {+ return nil, err+ }++ if total < int64(cfg.MinRequests) {+ return &EvalResult{Fired: false}, nil+ }++ rate := float64(errors) / float64(total) * 100+ if rate < cfg.ThresholdPercent {+ return &EvalResult{Fired: false}, nil+ }++ projectName := getProjectName(projectId)+ msg := buildEndpointErrorRateMessage(cfg.Endpoint, rate, cfg.ThresholdPercent, projectName)+ return &EvalResult{Fired: true, Message: msg}, nil+}++// --- Impact Score ---++var (+ impactStateMu sync.RWMutex+ impactState = make(map[string]map[string]bool)+)++type impactScoreConfig struct {+ MinRequests int `json:"minRequests"`+}++type impactMessageBuilder func(endpoint string, score float64, reason string, projectName string) Message++func evaluateImpactScore(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID, threshold float64, buildMsg impactMessageBuilder) (*EvalResult, error) {+ var cfg impactScoreConfig+ if err := json.Unmarshal(rule.Config, &cfg); err != nil {+ return nil, fmt.Errorf("invalid impact_score config: %w", err)+ }+ if cfg.MinRequests <= 0 {+ cfg.MinRequests = 50+ }++ now := time.Now().UTC()+ from := now.Add(-24 * time.Hour)+ pid := projectId.String()++ // Get all endpoints with basic aggregates+ rows, err := db.DB.QueryContext(ctx, `SELECT+ e.endpoint,+ COUNT(*) as total_count,+ MAX(e.recorded_at) as last_seen,+ COALESCE(s.offset_ms, 0) as offset_ms,+ SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as satisfied_count,+ SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as tolerating_count,+ SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count,+ SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) as client_error_count+ FROM endpoints e+ LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?+ GROUP BY e.endpoint, COALESCE(s.offset_ms, 0)`,+ pid, from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ type impactEndpoint struct {+ endpoint string+ impact float64+ totalCount uint64+ p99 float64+ offsetMs uint32+ satisfied uint64+ tolerating uint64+ bad uint64+ clientErrors uint64+ }++ var candidates []impactEndpoint+ for rows.Next() {+ var ep, lastSeenStr string+ var totalCount, satisfied, tolerating, bad, clientErrors int64+ var offsetMs int64+ if err := rows.Scan(&ep, &totalCount, &lastSeenStr, &offsetMs, &satisfied, &tolerating, &bad, &clientErrors); err != nil {+ return nil, err+ }++ if totalCount < int64(cfg.MinRequests) {+ continue+ }++ candidates = append(candidates, impactEndpoint{+ endpoint: ep,+ totalCount: uint64(totalCount),+ offsetMs: uint32(offsetMs),+ satisfied: uint64(satisfied),+ tolerating: uint64(tolerating),+ bad: uint64(bad),+ clientErrors: uint64(clientErrors),+ })+ }++ // Compute P99 per endpoint and impact score+ currentSet := make(map[string]impactEndpoint)+ for _, c := range candidates {+ dRows, err := db.DB.QueryContext(ctx,+ "SELECT duration FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY duration ASC",+ pid, c.endpoint, from.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano))+ if err != nil {+ continue+ }+ var durations []float64+ for dRows.Next() {+ var d int64+ if err := dRows.Scan(&d); err != nil {+ continue+ }+ durations = append(durations, float64(d))+ }+ dRows.Close()++ p99 := computePercentile(durations, 0.99)+ c.p99 = p99++ totalF := float64(c.totalCount)+ badF := float64(c.bad)+ clientF := float64(c.clientErrors)+ offsetNs := float64(c.offsetMs) * 1_000_000+ badRate := badF / totalF++ apdexScore := 1.0 - (float64(c.satisfied)+float64(c.tolerating)*0.5)/totalF+ var errorRateScore float64+ switch {+ case badRate > 0.33:+ errorRateScore = 0.75+ case badRate > 0.20:+ errorRateScore = 0.50+ case badRate > 0.10:+ errorRateScore = 0.25+ }+ adjustedP99 := p99 - offsetNs+ var p99Score float64+ switch {+ case adjustedP99 > 8_000_000_000:+ p99Score = 0.75+ case adjustedP99 > 6_000_000_000:+ p99Score = 0.50+ case adjustedP99 > 3_000_000_000:+ p99Score = 0.25+ }+ var clientErrorScore float64+ if c.endpoint != "UNMATCHED" && c.totalCount > 10 {+ clientRate := clientF / totalF+ switch {+ case clientRate > 0.50:+ clientErrorScore = 0.75+ case clientRate > 0.25:+ clientErrorScore = 0.50+ }+ }+ var volumeScore float64+ switch {+ case badRate > 0.10 && c.bad >= 500:+ volumeScore = 0.75+ case badRate > 0.10 && c.bad >= 50:+ volumeScore = 0.50+ case badRate > 0.05 && c.bad >= 2000:+ volumeScore = 0.75+ case badRate > 0.05 && c.bad >= 500:+ volumeScore = 0.50+ case badRate > 0.05 && c.bad >= 50:+ volumeScore = 0.25+ case badRate > 0.01 && c.bad >= 10000:+ volumeScore = 0.75+ case badRate > 0.01 && c.bad >= 2000:+ volumeScore = 0.50+ case badRate > 0.01 && c.bad >= 500:+ volumeScore = 0.25+ }++ impact := math.Max(apdexScore, math.Max(errorRateScore, math.Max(p99Score, math.Max(clientErrorScore, volumeScore))))+ if impact >= threshold {+ c.impact = impact+ currentSet[c.endpoint] = c+ }+ }++ stateKey := fmt.Sprintf("%d:%s", rule.Id, projectId.String())++ impactStateMu.RLock()+ prevSet := impactState[stateKey]+ impactStateMu.RUnlock()++ newSet := make(map[string]bool)+ for ep := range currentSet {+ newSet[ep] = true+ }++ impactStateMu.Lock()+ impactState[stateKey] = newSet+ impactStateMu.Unlock()++ projectName := getProjectName(projectId)++ var messages []Message+ if prevSet != nil {+ for ep, data := range currentSet {+ if prevSet[ep] {+ continue+ }+ reason := repositories.ComputeImpactReason(+ ep, data.totalCount, data.satisfied, data.tolerating,+ data.bad, data.clientErrors, data.p99, data.offsetMs,+ )+ messages = append(messages, buildMsg(ep, data.impact, reason, projectName))+ }+ }++ if len(messages) == 0 {+ return &EvalResult{Fired: false}, nil+ }+ return &EvalResult{Fired: true, Messages: messages}, nil+}++func evaluateImpactScoreCritical(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.75, buildImpactScoreCriticalMessage)+}++func evaluateImpactScoreHigh(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.50, buildImpactScoreHighMessage)+}++func evaluateImpactScoreMedium(ctx context.Context, rule *models.NotificationRule, projectId uuid.UUID) (*EvalResult, error) {+ return evaluateImpactScore(ctx, rule, projectId, 0.25, buildImpactScoreMediumMessage)+}++// helper to sort by impact+type byImpact []struct {+ endpoint string+ impact float64+}++func (a byImpact) Len() int { return len(a) }+func (a byImpact) Less(i, j int) bool { return a[i].impact > a[j].impact }+func (a byImpact) Swap(i, j int) { a[i], a[j] = a[j], a[i] }++var _ = sort.Sortdiff --git a/backend/app/repositories/endpoint.repository.go b/backend/app/repositories/endpoint.repository.goindex ed60a363..e093635b 100644--- a/backend/app/repositories/endpoint.repository.go+++ b/backend/app/repositories/endpoint.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/endpoint.repository_sqlite.go b/backend/app/repositories/endpoint.repository_sqlite.gonew file mode 100644index 00000000..7bd188bf--- /dev/null+++ b/backend/app/repositories/endpoint.repository_sqlite.go@@ -0,0 +1,954 @@+//go:build !pgch++package repositories++import (+ "context"+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "math"+ "sort"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type endpointRepository struct{}++func (e *endpointRepository) InsertAsync(ctx context.Context, lines []models.Endpoint) error {+ if len(lines) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx, `INSERT INTO endpoints (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, t := range lines {+ attributesJSON := "{}"+ if len(t.Attributes) != 0 {+ if b, err := json.Marshal(t.Attributes); err == nil {+ attributesJSON = string(b)+ }+ }+ if _, err := stmt.ExecContext(ctx,+ t.Id.String(), t.ProjectId.String(), t.Endpoint,+ int64(t.Duration), t.RecordedAt.UTC().Format(time.RFC3339Nano),+ t.StatusCode, t.BodySize, t.ClientIP, attributesJSON,+ t.AppVersion, t.ServerName,+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (e *endpointRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano)).Scan(&count)+ return count, err+}++func (e *endpointRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Endpoint, int64, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), fromDate.UTC().Format(time.RFC3339Nano), toDate.UTC().Format(time.RFC3339Nano)).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ "status_code": true,+ "body_size": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ ORDER BY ` + orderBy + ` DESC LIMIT ? OFFSET ?`++ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), fromDate.UTC().Format(time.RFC3339Nano), toDate.UTC().Format(time.RFC3339Nano),+ pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ endpoints, err := scanEndpoints(rows)+ if err != nil {+ return nil, 0, err+ }++ return endpoints, count, nil+}++func (e *endpointRepository) FindGroupedByEndpoint(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string, search string) ([]models.EndpointStats, int64, error) {+ fromStr := fromDate.UTC().Format(time.RFC3339Nano)+ toStr := toDate.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ whereClause := "e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?"+ args := []interface{}{pidStr, fromStr, toStr}+ if search != "" {+ whereClause += " AND INSTR(LOWER(e.endpoint), LOWER(?)) > 0"+ args = append(args, search)+ }++ var totalEndpoints int64+ countQuery := "SELECT COUNT(DISTINCT e.endpoint) FROM endpoints e WHERE " + whereClause+ if err := db.DB.QueryRowContext(ctx, countQuery, args...).Scan(&totalEndpoints); err != nil {+ return nil, 0, err+ }++ groupQuery := `SELECT+ e.endpoint,+ COUNT(*) as total_count,+ AVG(e.duration) as avg_duration,+ MAX(e.recorded_at) as last_seen,+ COALESCE(s.offset_ms, 0) as offset_ms,+ SUM(CASE WHEN e.status_code >= 500 THEN 1 ELSE 0 END) as server_error_count,+ SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) as client_error_count,+ SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as satisfied_count,+ SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as tolerating_count,+ SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count+ FROM endpoints e+ LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE ` + whereClause + `+ GROUP BY e.endpoint`++ rows, err := db.DB.QueryContext(ctx, groupQuery, args...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ type groupRow struct {+ endpoint string+ totalCount uint64+ avgDuration float64+ lastSeen string+ offsetMs uint32+ serverErrorCount uint64+ clientErrorCount uint64+ satisfiedCount uint64+ toleratingCount uint64+ badCount uint64+ }++ var groups []groupRow+ for rows.Next() {+ var g groupRow+ if err := rows.Scan(&g.endpoint, &g.totalCount, &g.avgDuration, &g.lastSeen,+ &g.offsetMs, &g.serverErrorCount, &g.clientErrorCount,+ &g.satisfiedCount, &g.toleratingCount, &g.badCount); err != nil {+ return nil, 0, err+ }+ groups = append(groups, g)+ }++ var stats []models.EndpointStats+ for _, g := range groups {+ durations, err := fetchSortedDurations(ctx, pidStr, g.endpoint, fromStr, toStr)+ if err != nil {+ return nil, 0, err+ }++ p50 := computePercentile(durations, 0.5)+ p95 := computePercentile(durations, 0.95)+ p99 := computePercentile(durations, 0.99)++ impact := computeImpactScore(g.endpoint, g.totalCount, g.satisfiedCount, g.toleratingCount, g.badCount, g.clientErrorCount, p99, g.offsetMs)++ lastSeen, _ := time.Parse(time.RFC3339Nano, g.lastSeen)++ s := models.EndpointStats{+ Endpoint: g.endpoint,+ Count: g.totalCount,+ P50Duration: time.Duration(p50),+ P95Duration: time.Duration(p95),+ P99Duration: time.Duration(p99),+ AvgDuration: time.Duration(g.avgDuration),+ LastSeen: lastSeen,+ Impact: impact,+ ImpactReason: ComputeImpactReason(g.endpoint, g.totalCount, g.satisfiedCount, g.toleratingCount,+ g.badCount, g.clientErrorCount, p99, g.offsetMs),+ }+ stats = append(stats, s)+ }++ sortEndpointStats(stats, orderBy, sortDirection)++ start := (page - 1) * pageSize+ if start > len(stats) {+ start = len(stats)+ }+ endIdx := start + pageSize+ if endIdx > len(stats) {+ endIdx = len(stats)+ }+ page_stats := stats[start:endIdx]++ return page_stats, totalEndpoints, nil+}++func (e *endpointRepository) FindByEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Endpoint, int64, error) {+ pidStr := projectId.String()+ fromStr := fromDate.UTC().Format(time.RFC3339Nano)+ toStr := toDate.UTC().Format(time.RFC3339Nano)++ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?",+ pidStr, endpoint, fromStr, toStr).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ "status_code": true,+ "body_size": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name+ FROM endpoints+ WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?+ ORDER BY ` + orderBy + ` ` + sortDir + ` LIMIT ? OFFSET ?`++ rows, err := db.DB.QueryContext(ctx, query, pidStr, endpoint, fromStr, toStr, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ endpoints, err := scanEndpoints(rows)+ if err != nil {+ return nil, 0, err+ }++ return endpoints, count, nil+}++func (e *endpointRepository) FindById(ctx context.Context, projectId, endpointId uuid.UUID) (*models.Endpoint, error) {+ query := `SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip, attributes, app_version, server_name+ FROM endpoints+ WHERE project_id = ? AND id = ?+ LIMIT 1`++ var t models.Endpoint+ var idStr, projectIdStr, recordedAtStr, attributesJSON string+ err := db.DB.QueryRowContext(ctx, query, projectId.String(), endpointId.String()).Scan(+ &idStr, &projectIdStr, &t.Endpoint, &t.Duration, &recordedAtStr,+ &t.StatusCode, &t.BodySize, &t.ClientIP, &attributesJSON, &t.AppVersion, &t.ServerName)+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ return nil, err+ }++ t.Id, _ = uuid.Parse(idStr)+ t.ProjectId, _ = uuid.Parse(projectIdStr)+ t.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)+ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &t.Attributes); err != nil {+ t.Attributes = nil+ }+ }++ return &t, nil+}++func (e *endpointRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ CAST(COUNT(*) AS REAL) as count+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ AVG(duration) / 1000000.0 as avg_duration_ms+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) ErrorRateByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as error_rate+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60+ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,+ CAST(COUNT(*) AS REAL) as count+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`, secs, secs)++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60+ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,+ AVG(duration) / 1000000.0 as avg_duration_ms+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`, secs, secs)++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) ErrorRateByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60+ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,+ SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) as error_rate+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`, secs, secs)++ return queryTimeSeries(ctx, query, projectId.String(), start, end)+}++func (e *endpointRepository) FindWorstEndpoints(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.EndpointStats, error) {+ fromStr := start.UTC().Format(time.RFC3339Nano)+ toStr := end.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ groupQuery := `SELECT+ e.endpoint,+ COUNT(*) as total_count,+ AVG(e.duration) as avg_duration,+ MAX(e.recorded_at) as last_seen,+ COALESCE(s.offset_ms, 0) as offset_ms,+ SUM(CASE WHEN e.status_code >= 500 THEN 1 ELSE 0 END) as server_error_count,+ SUM(CASE WHEN e.status_code >= 400 AND e.status_code < 500 THEN 1 ELSE 0 END) as client_error_count,+ SUM(CASE WHEN e.duration <= (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as satisfied_count,+ SUM(CASE WHEN e.duration > (750000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.duration <= (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) AND e.status_code < 500 THEN 1 ELSE 0 END) as tolerating_count,+ SUM(CASE WHEN e.duration > (1500000000 + COALESCE(s.offset_ms, 0) * 1000000) OR e.status_code >= 500 THEN 1 ELSE 0 END) as bad_count+ FROM endpoints e+ LEFT JOIN slow_endpoints s ON e.endpoint = s.endpoint AND e.project_id = s.project_id+ WHERE e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?+ GROUP BY e.endpoint`++ rows, err := db.DB.QueryContext(ctx, groupQuery, pidStr, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ type groupRow struct {+ endpoint string+ totalCount uint64+ avgDuration float64+ lastSeen string+ offsetMs uint32+ serverErrorCount uint64+ clientErrorCount uint64+ satisfiedCount uint64+ toleratingCount uint64+ badCount uint64+ }++ var groups []groupRow+ for rows.Next() {+ var g groupRow+ if err := rows.Scan(&g.endpoint, &g.totalCount, &g.avgDuration, &g.lastSeen,+ &g.offsetMs, &g.serverErrorCount, &g.clientErrorCount,+ &g.satisfiedCount, &g.toleratingCount, &g.badCount); err != nil {+ return nil, err+ }+ groups = append(groups, g)+ }++ var stats []models.EndpointStats+ for _, g := range groups {+ durations, err := fetchSortedDurations(ctx, pidStr, g.endpoint, fromStr, toStr)+ if err != nil {+ return nil, err+ }++ p50 := computePercentile(durations, 0.5)+ p95 := computePercentile(durations, 0.95)+ p99 := computePercentile(durations, 0.99)++ impact := computeImpactScore(g.endpoint, g.totalCount, g.satisfiedCount, g.toleratingCount, g.badCount, g.clientErrorCount, p99, g.offsetMs)++ lastSeen, _ := time.Parse(time.RFC3339Nano, g.lastSeen)++ s := models.EndpointStats{+ Endpoint: g.endpoint,+ Count: g.totalCount,+ P50Duration: time.Duration(p50),+ P95Duration: time.Duration(p95),+ P99Duration: time.Duration(p99),+ AvgDuration: time.Duration(g.avgDuration),+ LastSeen: lastSeen,+ Impact: impact,+ ImpactReason: ComputeImpactReason(g.endpoint, g.totalCount, g.satisfiedCount, g.toleratingCount,+ g.badCount, g.clientErrorCount, p99, g.offsetMs),+ }+ stats = append(stats, s)+ }++ sort.Slice(stats, func(i, j int) bool {+ return stats[i].Impact > stats[j].Impact+ })++ if limit > 0 && limit < len(stats) {+ stats = stats[:limit]+ }++ return stats, nil+}++func (e *endpointRepository) GetEndpointStats(ctx context.Context, projectId uuid.UUID, endpoint string, start, end time.Time) (*models.EndpointDetailStats, error) {+ pidStr := projectId.String()+ fromStr := start.UTC().Format(time.RFC3339Nano)+ toStr := end.UTC().Format(time.RFC3339Nano)++ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ query := `SELECT+ COUNT(*) as count,+ CASE WHEN COUNT(*) > 0 THEN AVG(duration) / 1000000.0 ELSE 0 END as avg_duration_ms,+ CASE WHEN COUNT(*) > 0 THEN SUM(CASE WHEN status_code >= 500 THEN 1 ELSE 0 END) * 100.0 / COUNT(*) ELSE 0 END as error_rate,+ SUM(CASE WHEN duration <= 500000000 AND status_code < 500 THEN 1 ELSE 0 END) ++ SUM(CASE WHEN duration > 500000000 AND duration <= 2000000000 AND status_code < 500 THEN 1 ELSE 0 END) * 0.5 as satisfied_tolerating+ FROM endpoints+ WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?`++ var stats models.EndpointDetailStats+ var count int64+ var satisfiedTolerating float64++ err := db.DB.QueryRowContext(ctx, query, pidStr, endpoint, fromStr, toStr).Scan(+ &count, &stats.AvgDuration, &stats.ErrorRate, &satisfiedTolerating)+ if err != nil {+ return nil, err+ }++ stats.Count = count+ if count > 0 {+ stats.Apdex = satisfiedTolerating / float64(count)+ }+ stats.Throughput = float64(count) / durationMinutes++ durations, err := fetchSortedDurations(ctx, pidStr, endpoint, fromStr, toStr)+ if err != nil {+ return nil, err+ }++ if len(durations) > 0 {+ stats.MedianDuration = computePercentile(durations, 0.5) / 1000000.0+ stats.P95Duration = computePercentile(durations, 0.95) / 1000000.0+ stats.P99Duration = computePercentile(durations, 0.99) / 1000000.0+ }++ return &stats, nil+}++func (e *endpointRepository) GetEndpointStackedChart(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int, metricType string) (*models.EndpointStackedChartResponse, error) {+ pidStr := projectId.String()+ fromStr := start.UTC().Format(time.RFC3339Nano)+ toStr := end.UTC().Format(time.RFC3339Nano)++ // Step 1: Get top 5 endpoints by metric+ topEndpoints, err := getTopEndpointsByMetric(ctx, pidStr, fromStr, toStr, metricType)+ if err != nil {+ return nil, err+ }++ if len(topEndpoints) == 0 {+ return &models.EndpointStackedChartResponse{+ Endpoints: []string{},+ Series: []models.EndpointTimeSeriesPoint{},+ }, nil+ }++ // Step 2: Build CASE expression for categorization+ caseExpr := "CASE "+ caseArgs := make([]interface{}, 0, len(topEndpoints))+ for _, ep := range topEndpoints {+ caseExpr += "WHEN endpoint = ? THEN ? "+ caseArgs = append(caseArgs, ep, ep)+ }+ caseExpr += "ELSE 'Other' END"++ var metricExpr string+ switch metricType {+ case "total_time":+ metricExpr = "COUNT(*) * AVG(duration) / 1000000.0"+ case "p95":+ metricExpr = "AVG(duration) / 1000000.0"+ case "p99":+ metricExpr = "AVG(duration) / 1000000.0"+ default:+ metricExpr = "AVG(duration) / 1000000.0"+ }++ secs := intervalMinutes * 60+ timeSeriesQuery := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,+ %s as endpoint_category,+ %s as metric_value+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket, endpoint_category+ ORDER BY bucket ASC, endpoint_category ASC`, secs, secs, caseExpr, metricExpr)++ args := make([]interface{}, 0, len(caseArgs)+3)+ args = append(args, caseArgs...)+ args = append(args, pidStr, fromStr, toStr)++ // For p50/p95/p99 we need per-bucket per-category percentile computation+ if metricType == "p50" || metricType == "p95" || metricType == "p99" || metricType == "" {+ return e.getStackedChartWithPercentiles(ctx, pidStr, fromStr, toStr, secs, topEndpoints, metricType)+ }++ rows, err := db.DB.QueryContext(ctx, timeSeriesQuery, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var series []models.EndpointTimeSeriesPoint+ for rows.Next() {+ var p models.EndpointTimeSeriesPoint+ var tsStr string+ if err := rows.Scan(&tsStr, &p.Endpoint, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ series = append(series, p)+ }++ endpointSet := make(map[string]bool)+ for _, p := range series {+ endpointSet[p.Endpoint] = true+ }++ finalEndpoints := make([]string, 0, len(topEndpoints)+1)+ finalEndpoints = append(finalEndpoints, topEndpoints...)+ if endpointSet["Other"] {+ finalEndpoints = append(finalEndpoints, "Other")+ }++ return &models.EndpointStackedChartResponse{+ Endpoints: finalEndpoints,+ Series: series,+ }, nil+}++func (e *endpointRepository) getStackedChartWithPercentiles(ctx context.Context, pidStr, fromStr, toStr string, bucketSecs int, topEndpoints []string, metricType string) (*models.EndpointStackedChartResponse, error) {+ percentile := 0.5+ switch metricType {+ case "p95":+ percentile = 0.95+ case "p99":+ percentile = 0.99+ }++ topSet := make(map[string]bool, len(topEndpoints))+ for _, ep := range topEndpoints {+ topSet[ep] = true+ }++ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') as bucket,+ endpoint,+ duration+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ ORDER BY bucket ASC, endpoint ASC, duration ASC`, bucketSecs, bucketSecs)++ rows, err := db.DB.QueryContext(ctx, query, pidStr, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ type bucketKey struct {+ bucket string+ category string+ }+ durationMap := make(map[bucketKey][]float64)++ for rows.Next() {+ var bucketStr, endpoint string+ var duration float64+ if err := rows.Scan(&bucketStr, &endpoint, &duration); err != nil {+ return nil, err+ }++ category := "Other"+ if topSet[endpoint] {+ category = endpoint+ }++ key := bucketKey{bucket: bucketStr, category: category}+ durationMap[key] = append(durationMap[key], duration)+ }++ var series []models.EndpointTimeSeriesPoint+ for key, durations := range durationMap {+ sort.Float64s(durations)+ val := computePercentile(durations, percentile) / 1000000.0++ ts, _ := time.Parse("2006-01-02 15:04:05", key.bucket)+ series = append(series, models.EndpointTimeSeriesPoint{+ Timestamp: ts,+ Endpoint: key.category,+ Value: val,+ })+ }++ sort.Slice(series, func(i, j int) bool {+ if series[i].Timestamp.Equal(series[j].Timestamp) {+ return series[i].Endpoint < series[j].Endpoint+ }+ return series[i].Timestamp.Before(series[j].Timestamp)+ })++ endpointSet := make(map[string]bool)+ for _, p := range series {+ endpointSet[p.Endpoint] = true+ }++ finalEndpoints := make([]string, 0, len(topEndpoints)+1)+ finalEndpoints = append(finalEndpoints, topEndpoints...)+ if endpointSet["Other"] {+ finalEndpoints = append(finalEndpoints, "Other")+ }++ return &models.EndpointStackedChartResponse{+ Endpoints: finalEndpoints,+ Series: series,+ }, nil+}++func (e *endpointRepository) GetSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string) (uint32, string, error) {+ var offsetMs uint32+ var reason string+ err := db.DB.QueryRowContext(ctx,+ "SELECT offset_ms, reason FROM slow_endpoints WHERE project_id = ? AND endpoint = ?",+ projectId.String(), endpoint).Scan(&offsetMs, &reason)+ return offsetMs, reason, err+}++func (e *endpointRepository) UpsertSlowEndpoint(ctx context.Context, projectId uuid.UUID, endpoint string, offsetMs uint32, reason string) error {+ _, err := db.DB.ExecContext(ctx,+ "INSERT OR REPLACE INTO slow_endpoints (project_id, endpoint, offset_ms, reason) VALUES (?, ?, ?, ?)",+ projectId.String(), endpoint, offsetMs, reason)+ return err+}++// --- helpers ---++func scanEndpoints(rows *sql.Rows) ([]models.Endpoint, error) {+ var endpoints []models.Endpoint+ for rows.Next() {+ var t models.Endpoint+ var idStr, projectIdStr, recordedAtStr, attributesJSON string+ if err := rows.Scan(&idStr, &projectIdStr, &t.Endpoint, &t.Duration, &recordedAtStr,+ &t.StatusCode, &t.BodySize, &t.ClientIP, &attributesJSON, &t.AppVersion, &t.ServerName); err != nil {+ return nil, err+ }+ t.Id, _ = uuid.Parse(idStr)+ t.ProjectId, _ = uuid.Parse(projectIdStr)+ t.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)+ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &t.Attributes); err != nil {+ t.Attributes = nil+ }+ }+ endpoints = append(endpoints, t)+ }+ return endpoints, nil+}++func fetchSortedDurations(ctx context.Context, pidStr, endpoint, fromStr, toStr string) ([]float64, error) {+ rows, err := db.DB.QueryContext(ctx,+ "SELECT duration FROM endpoints WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY duration ASC",+ pidStr, endpoint, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var durations []float64+ for rows.Next() {+ var d float64+ if err := rows.Scan(&d); err != nil {+ return nil, err+ }+ durations = append(durations, d)+ }+ return durations, nil+}++func computeImpactScore(endpoint string, total, satisfiedCount, toleratingCount, badCount, clientErrorCount uint64, p99Ns float64, offsetMs uint32) float64 {+ if total == 0 {+ return 0+ }++ totalF := float64(total)+ badF := float64(badCount)+ clientF := float64(clientErrorCount)+ offsetNs := float64(offsetMs) * 1_000_000++ apdexScore := 1.0 - (float64(satisfiedCount)+float64(toleratingCount)*0.5)/totalF++ badRate := badF / totalF+ var errorRateScore float64+ switch {+ case badRate > 0.33:+ errorRateScore = 0.75+ case badRate > 0.20:+ errorRateScore = 0.50+ case badRate > 0.10:+ errorRateScore = 0.25+ }++ adjustedP99 := p99Ns - offsetNs+ var p99Score float64+ switch {+ case adjustedP99 > 8_000_000_000:+ p99Score = 0.75+ case adjustedP99 > 6_000_000_000:+ p99Score = 0.50+ case adjustedP99 > 3_000_000_000:+ p99Score = 0.25+ }++ var clientErrorScore float64+ if endpoint != "UNMATCHED" && total > 10 {+ clientRate := clientF / totalF+ switch {+ case clientRate > 0.50:+ clientErrorScore = 0.75+ case clientRate > 0.25:+ clientErrorScore = 0.50+ }+ }++ var volumeScore float64+ switch {+ case badRate > 0.10 && badCount >= 500:+ volumeScore = 0.75+ case badRate > 0.10 && badCount >= 50:+ volumeScore = 0.50+ case badRate > 0.05 && badCount >= 2000:+ volumeScore = 0.75+ case badRate > 0.05 && badCount >= 500:+ volumeScore = 0.50+ case badRate > 0.05 && badCount >= 50:+ volumeScore = 0.25+ case badRate > 0.01 && badCount >= 10000:+ volumeScore = 0.75+ case badRate > 0.01 && badCount >= 2000:+ volumeScore = 0.50+ case badRate > 0.01 && badCount >= 500:+ volumeScore = 0.25+ }++ return math.Max(apdexScore, math.Max(errorRateScore, math.Max(p99Score, math.Max(clientErrorScore, volumeScore))))+}++func sortEndpointStats(stats []models.EndpointStats, orderBy string, sortDirection string) {+ desc := sortDirection != "asc"++ sort.Slice(stats, func(i, j int) bool {+ var less bool+ switch orderBy {+ case "count":+ less = stats[i].Count < stats[j].Count+ case "p50_duration":+ less = stats[i].P50Duration < stats[j].P50Duration+ case "p95_duration":+ less = stats[i].P95Duration < stats[j].P95Duration+ case "p99_duration":+ less = stats[i].P99Duration < stats[j].P99Duration+ case "avg_duration":+ less = stats[i].AvgDuration < stats[j].AvgDuration+ case "last_seen":+ less = stats[i].LastSeen.Before(stats[j].LastSeen)+ default:+ less = stats[i].Impact < stats[j].Impact+ }+ if desc {+ return !less+ }+ return less+ })+}++func queryTimeSeries(ctx context.Context, query, pidStr string, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ rows, err := db.DB.QueryContext(ctx, query, pidStr, start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ var tsStr string+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func getTopEndpointsByMetric(ctx context.Context, pidStr, fromStr, toStr, metricType string) ([]string, error) {+ if metricType == "total_time" {+ query := `SELECT endpoint, COUNT(*) * AVG(duration) / 1000000.0 as metric_value+ FROM endpoints+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY endpoint+ ORDER BY metric_value DESC+ LIMIT 5`++ rows, err := db.DB.QueryContext(ctx, query, pidStr, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var endpoints []string+ for rows.Next() {+ var ep string+ var val float64+ if err := rows.Scan(&ep, &val); err != nil {+ return nil, err+ }+ endpoints = append(endpoints, ep)+ }+ return endpoints, nil+ }++ // For p50/p95/p99: need to fetch durations per endpoint, compute percentile, sort+ percentile := 0.5+ switch metricType {+ case "p95":+ percentile = 0.95+ case "p99":+ percentile = 0.99+ }++ epQuery := `SELECT DISTINCT endpoint FROM endpoints WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?`+ rows, err := db.DB.QueryContext(ctx, epQuery, pidStr, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var allEndpoints []string+ for rows.Next() {+ var ep string+ if err := rows.Scan(&ep); err != nil {+ return nil, err+ }+ allEndpoints = append(allEndpoints, ep)+ }++ type epMetric struct {+ endpoint string+ value float64+ }++ var metrics []epMetric+ for _, ep := range allEndpoints {+ durations, err := fetchSortedDurations(ctx, pidStr, ep, fromStr, toStr)+ if err != nil {+ return nil, err+ }+ val := computePercentile(durations, percentile) / 1000000.0+ metrics = append(metrics, epMetric{endpoint: ep, value: val})+ }++ sort.Slice(metrics, func(i, j int) bool {+ return metrics[i].value > metrics[j].value+ })++ limit := 5+ if limit > len(metrics) {+ limit = len(metrics)+ }++ result := make([]string, limit)+ for i := 0; i < limit; i++ {+ result[i] = metrics[i].endpoint+ }++ return result, nil+}++var EndpointRepository = endpointRepository{}diff --git a/backend/app/repositories/endpoint_repository_test.go b/backend/app/repositories/endpoint_repository_test.gonew file mode 100644index 00000000..c532f142--- /dev/null+++ b/backend/app/repositories/endpoint_repository_test.go@@ -0,0 +1,452 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestEndpointRepository_InsertAndCount(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "POST /api/users", 200*time.Millisecond, 201, now.Add(time.Minute)),+ makeEndpoint(projectId, "GET /api/users", 150*time.Millisecond, 200, now.Add(2*time.Minute)),+ }++ err := EndpointRepository.InsertAsync(ctx, endpoints)+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := EndpointRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 3 {+ t.Errorf("expected count 3, got %d", count)+ }+}++func TestEndpointRepository_CountBetween_TimeFilter(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /old", 100*time.Millisecond, 200, now.Add(-2*time.Hour)),+ makeEndpoint(projectId, "GET /new", 100*time.Millisecond, 200, now),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := EndpointRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 1 {+ t.Errorf("expected count 1 (only recent endpoint), got %d", count)+ }+}++func TestEndpointRepository_FindAll(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/a", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/b", 200*time.Millisecond, 200, now.Add(time.Minute)),+ makeEndpoint(projectId, "GET /api/c", 300*time.Millisecond, 200, now.Add(2*time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, total, err := EndpointRepository.FindAll(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at")+ if err != nil {+ t.Fatalf("FindAll failed: %v", err)+ }++ if total != 3 {+ t.Errorf("expected total 3, got %d", total)+ }+ if len(found) != 3 {+ t.Errorf("expected 3 results, got %d", len(found))+ }+}++func TestEndpointRepository_FindAll_Pagination(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := make([]models.Endpoint, 5)+ for i := range endpoints {+ endpoints[i] = makeEndpoint(projectId, "GET /api/test", time.Duration(i+1)*100*time.Millisecond, 200, now.Add(time.Duration(i)*time.Minute))+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ page1, total, err := EndpointRepository.FindAll(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 2, "recorded_at")+ if err != nil {+ t.Fatalf("FindAll page 1 failed: %v", err)+ }+ if total != 5 {+ t.Errorf("expected total 5, got %d", total)+ }+ if len(page1) != 2 {+ t.Errorf("expected 2 results on page 1, got %d", len(page1))+ }+}++func TestEndpointRepository_FindGroupedByEndpoint(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/users", 200*time.Millisecond, 200, now.Add(time.Minute)),+ makeEndpoint(projectId, "GET /api/users", 300*time.Millisecond, 200, now.Add(2*time.Minute)),+ makeEndpoint(projectId, "POST /api/users", 150*time.Millisecond, 201, now.Add(3*time.Minute)),+ }++ 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", "")+ if err != nil {+ t.Fatalf("FindGroupedByEndpoint failed: %v", err)+ }++ if total != 2 {+ t.Errorf("expected 2 distinct endpoints, got %d", total)+ }+ if len(stats) != 2 {+ t.Fatalf("expected 2 grouped stats, got %d", len(stats))+ }++ // Ordered by count DESC: GET /api/users (3) first+ if stats[0].Endpoint != "GET /api/users" {+ t.Errorf("expected first group 'GET /api/users', got %q", stats[0].Endpoint)+ }+ if stats[0].Count != 3 {+ t.Errorf("expected count 3, got %d", stats[0].Count)+ }+}++func TestEndpointRepository_FindGroupedByEndpoint_Search(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/products", 200*time.Millisecond, 200, now.Add(time.Minute)),+ }++ 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", "users")+ if err != nil {+ t.Fatalf("FindGroupedByEndpoint with search failed: %v", err)+ }++ if total != 1 {+ t.Errorf("expected 1 matching endpoint, got %d", total)+ }+ if len(stats) != 1 {+ t.Fatalf("expected 1 grouped stat, got %d", len(stats))+ }+ if stats[0].Endpoint != "GET /api/users" {+ t.Errorf("expected 'GET /api/users', got %q", stats[0].Endpoint)+ }+}++func TestEndpointRepository_FindByEndpoint(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/users", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/users", 200*time.Millisecond, 200, now.Add(time.Minute)),+ makeEndpoint(projectId, "POST /api/users", 300*time.Millisecond, 201, now.Add(2*time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, total, err := EndpointRepository.FindByEndpoint(ctx, projectId, "GET /api/users", now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at", "desc")+ if err != nil {+ t.Fatalf("FindByEndpoint failed: %v", err)+ }++ if total != 2 {+ t.Errorf("expected total 2, got %d", total)+ }+ if len(found) != 2 {+ t.Errorf("expected 2 results, got %d", len(found))+ }+ for _, f := range found {+ if f.Endpoint != "GET /api/users" {+ t.Errorf("expected endpoint 'GET /api/users', got %q", f.Endpoint)+ }+ }+}++func TestEndpointRepository_FindById(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ ep := makeEndpoint(projectId, "GET /api/specific", 250*time.Millisecond, 200, now)++ if err := EndpointRepository.InsertAsync(ctx, []models.Endpoint{ep}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := EndpointRepository.FindById(ctx, projectId, ep.Id)+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found == nil {+ t.Fatal("expected to find endpoint, got nil")+ }+ if found.Endpoint != "GET /api/specific" {+ t.Errorf("expected endpoint 'GET /api/specific', got %q", found.Endpoint)+ }+ if found.Duration != 250*time.Millisecond {+ t.Errorf("expected duration 250ms, got %v", found.Duration)+ }+}++func TestEndpointRepository_FindById_NotFound(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ found, err := EndpointRepository.FindById(ctx, uuid.New(), uuid.New())+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found != nil {+ t.Errorf("expected nil for unknown endpoint, got %+v", found)+ }+}++func TestEndpointRepository_CountByHour(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC()).Truncate(time.Hour)++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /a", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /b", 100*time.Millisecond, 200, now.Add(30*time.Minute)),+ makeEndpoint(projectId, "GET /c", 100*time.Millisecond, 200, now.Add(time.Hour+10*time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ points, err := EndpointRepository.CountByHour(ctx, projectId, now.Add(-time.Minute), now.Add(2*time.Hour))+ if err != nil {+ t.Fatalf("CountByHour failed: %v", err)+ }++ if len(points) != 2 {+ t.Fatalf("expected 2 hourly buckets, got %d", len(points))+ }++ if points[0].Value != 2 {+ t.Errorf("expected 2 endpoints in first hour, got %v", points[0].Value)+ }+ if points[1].Value != 1 {+ t.Errorf("expected 1 endpoint in second hour, got %v", points[1].Value)+ }+}++func TestEndpointRepository_ErrorRateByHour(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC()).Truncate(time.Hour)++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/ok", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/ok", 100*time.Millisecond, 200, now.Add(time.Minute)),+ makeEndpoint(projectId, "GET /api/err", 100*time.Millisecond, 500, now.Add(2*time.Minute)),+ makeEndpoint(projectId, "GET /api/err", 100*time.Millisecond, 503, now.Add(3*time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ points, err := EndpointRepository.ErrorRateByHour(ctx, projectId, now.Add(-time.Minute), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("ErrorRateByHour failed: %v", err)+ }++ if len(points) != 1 {+ t.Fatalf("expected 1 hourly bucket, got %d", len(points))+ }++ // 2 out of 4 are errors = 50%+ assertApproxEqual(t, "error rate", points[0].Value, 50.0, 0.1)+}++func TestEndpointRepository_UpsertAndGetSlowEndpoint(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()++ err := EndpointRepository.UpsertSlowEndpoint(ctx, projectId, "GET /api/slow", 500, "Known slow endpoint")+ if err != nil {+ t.Fatalf("UpsertSlowEndpoint failed: %v", err)+ }++ offsetMs, reason, err := EndpointRepository.GetSlowEndpoint(ctx, projectId, "GET /api/slow")+ if err != nil {+ t.Fatalf("GetSlowEndpoint failed: %v", err)+ }++ if offsetMs != 500 {+ t.Errorf("expected offset 500ms, got %d", offsetMs)+ }+ if reason != "Known slow endpoint" {+ t.Errorf("expected reason 'Known slow endpoint', got %q", reason)+ }++ // Upsert should update existing+ err = EndpointRepository.UpsertSlowEndpoint(ctx, projectId, "GET /api/slow", 1000, "Updated reason")+ if err != nil {+ t.Fatalf("UpsertSlowEndpoint update failed: %v", err)+ }++ offsetMs, reason, err = EndpointRepository.GetSlowEndpoint(ctx, projectId, "GET /api/slow")+ if err != nil {+ t.Fatalf("GetSlowEndpoint after update failed: %v", err)+ }++ if offsetMs != 1000 {+ t.Errorf("expected updated offset 1000ms, got %d", offsetMs)+ }+ if reason != "Updated reason" {+ t.Errorf("expected updated reason, got %q", reason)+ }+}++func TestEndpointRepository_FindWorstEndpoints(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ // Healthy endpoint+ makeEndpoint(projectId, "GET /healthy", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /healthy", 150*time.Millisecond, 200, now.Add(time.Minute)),+ // Unhealthy endpoint (5xx errors)+ makeEndpoint(projectId, "GET /broken", 100*time.Millisecond, 500, now),+ makeEndpoint(projectId, "GET /broken", 200*time.Millisecond, 500, now.Add(time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ worst, err := EndpointRepository.FindWorstEndpoints(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 5)+ if err != nil {+ t.Fatalf("FindWorstEndpoints failed: %v", err)+ }++ if len(worst) != 2 {+ t.Fatalf("expected 2 endpoint groups, got %d", len(worst))+ }++ // /broken should have higher impact (100% error rate)+ if worst[0].Endpoint != "GET /broken" {+ t.Errorf("expected worst endpoint to be 'GET /broken', got %q", worst[0].Endpoint)+ }+}++func TestEndpointRepository_GetEndpointStats(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ endpoints := []models.Endpoint{+ makeEndpoint(projectId, "GET /api/measured", 100*time.Millisecond, 200, now),+ makeEndpoint(projectId, "GET /api/measured", 200*time.Millisecond, 200, now.Add(time.Minute)),+ makeEndpoint(projectId, "GET /api/measured", 300*time.Millisecond, 200, now.Add(2*time.Minute)),+ makeEndpoint(projectId, "GET /api/measured", 400*time.Millisecond, 500, now.Add(3*time.Minute)),+ }++ if err := EndpointRepository.InsertAsync(ctx, endpoints); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ start := now.Add(-time.Hour)+ end := now.Add(time.Hour)+ stats, err := EndpointRepository.GetEndpointStats(ctx, projectId, "GET /api/measured", start, end)+ if err != nil {+ t.Fatalf("GetEndpointStats failed: %v", err)+ }++ if stats.Count != 4 {+ t.Errorf("expected count 4, got %d", stats.Count)+ }++ // avg duration = (100+200+300+400)/4 = 250ms+ assertApproxEqual(t, "AvgDuration", stats.AvgDuration, 250.0, 1.0)++ // 1 out of 4 is error = 25%+ assertApproxEqual(t, "ErrorRate", stats.ErrorRate, 25.0, 0.1)++ if stats.MedianDuration < 100 || stats.MedianDuration > 400 {+ t.Errorf("MedianDuration %v out of expected range", stats.MedianDuration)+ }++ if stats.Throughput <= 0 {+ t.Errorf("expected positive throughput, got %v", stats.Throughput)+ }+}++func TestEndpointRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := EndpointRepository.InsertAsync(ctx, []models.Endpoint{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}diff --git a/backend/app/repositories/exception_repository_test.go b/backend/app/repositories/exception_repository_test.gonew file mode 100644index 00000000..3ad62411--- /dev/null+++ b/backend/app/repositories/exception_repository_test.go@@ -0,0 +1,337 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestExceptionRepository_InsertAndCount(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "hash-a", "RuntimeError: something failed\n at main.go:42", now),+ makeException(projectId, "hash-a", "RuntimeError: something failed\n at main.go:42", now.Add(time.Minute)),+ makeException(projectId, "hash-b", "NullPointerError: nil reference\n at handler.go:10", now.Add(2*time.Minute)),+ }++ err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions)+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := ExceptionStackTraceRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 3 {+ t.Errorf("expected count 3, got %d", count)+ }+}++func TestExceptionRepository_CountBetween_TimeFilter(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "old-hash", "old error", now.Add(-2*time.Hour)),+ makeException(projectId, "new-hash", "new error", now),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := ExceptionStackTraceRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 1 {+ t.Errorf("expected count 1 (only recent exception), got %d", count)+ }+}++func TestExceptionRepository_FindGrouped(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "hash-a", "Error A\n at main.go:1", now),+ makeException(projectId, "hash-a", "Error A\n at main.go:1", now.Add(time.Minute)),+ makeException(projectId, "hash-a", "Error A\n at main.go:1", now.Add(2*time.Minute)),+ makeException(projectId, "hash-b", "Error B\n at handler.go:5", now.Add(3*time.Minute)),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ groups, total, err := ExceptionStackTraceRepository.FindGrouped(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "count", "", "", false)+ if err != nil {+ t.Fatalf("FindGrouped failed: %v", err)+ }++ if total != 2 {+ t.Errorf("expected 2 groups, got %d", total)+ }+ if len(groups) != 2 {+ t.Fatalf("expected 2 group entries, got %d", len(groups))+ }++ // Ordered by count DESC: hash-a (3) first+ if groups[0].ExceptionHash != "hash-a" {+ t.Errorf("expected first group hash 'hash-a', got %q", groups[0].ExceptionHash)+ }+ if groups[0].Count != 3 {+ t.Errorf("expected count 3, got %d", groups[0].Count)+ }+}++func TestExceptionRepository_FindGrouped_Search(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "hash-db", "DatabaseError: connection refused\n at db.go:42", now),+ makeException(projectId, "hash-nil", "NilPointerError: nil reference\n at handler.go:10", now.Add(time.Minute)),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ groups, total, err := ExceptionStackTraceRepository.FindGrouped(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "count", "Database", "", false)+ if err != nil {+ t.Fatalf("FindGrouped with search failed: %v", err)+ }++ if total != 1 {+ t.Errorf("expected 1 group matching search, got %d", total)+ }+ if len(groups) != 1 {+ t.Fatalf("expected 1 group entry, got %d", len(groups))+ }+ if groups[0].ExceptionHash != "hash-db" {+ t.Errorf("expected hash 'hash-db', got %q", groups[0].ExceptionHash)+ }+}++func TestExceptionRepository_FindByHash(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "target-hash", "RuntimeError: fail\n at main.go:1", now),+ makeException(projectId, "target-hash", "RuntimeError: fail\n at main.go:1", now.Add(time.Minute)),+ makeException(projectId, "other-hash", "OtherError: other\n at other.go:1", now.Add(2*time.Minute)),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ group, occurrences, total, err := ExceptionStackTraceRepository.FindByHash(ctx, projectId, "target-hash", 1, 10)+ if err != nil {+ t.Fatalf("FindByHash failed: %v", err)+ }++ if group == nil {+ t.Fatal("expected group, got nil")+ }+ if group.Count != 2 {+ t.Errorf("expected group count 2, got %d", group.Count)+ }+ if total != 2 {+ t.Errorf("expected total 2, got %d", total)+ }+ if len(occurrences) != 2 {+ t.Errorf("expected 2 occurrences, got %d", len(occurrences))+ }+}++func TestExceptionRepository_ArchiveAndUnarchive(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "archive-hash", "Error to archive", now),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ // Initially not archived+ archived, err := ExceptionStackTraceRepository.IsArchived(ctx, projectId, "archive-hash")+ if err != nil {+ t.Fatalf("IsArchived failed: %v", err)+ }+ if archived {+ t.Error("expected not archived initially")+ }++ // Archive+ if err := ExceptionStackTraceRepository.ArchiveByHashes(ctx, projectId, []string{"archive-hash"}); err != nil {+ t.Fatalf("ArchiveByHashes failed: %v", err)+ }++ archived, err = ExceptionStackTraceRepository.IsArchived(ctx, projectId, "archive-hash")+ if err != nil {+ t.Fatalf("IsArchived after archive failed: %v", err)+ }+ if !archived {+ t.Error("expected archived after ArchiveByHashes")+ }++ // Unarchive+ if err := ExceptionStackTraceRepository.UnarchiveByHashes(ctx, projectId, []string{"archive-hash"}); err != nil {+ t.Fatalf("UnarchiveByHashes failed: %v", err)+ }++ archived, err = ExceptionStackTraceRepository.IsArchived(ctx, projectId, "archive-hash")+ if err != nil {+ t.Fatalf("IsArchived after unarchive failed: %v", err)+ }+ if archived {+ t.Error("expected not archived after UnarchiveByHashes")+ }+}++func TestExceptionRepository_FindGrouped_ExcludesArchived(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "active-hash", "Active error", now),+ makeException(projectId, "archived-hash", "Archived error", now.Add(-time.Minute)),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ if err := ExceptionStackTraceRepository.ArchiveByHashes(ctx, projectId, []string{"archived-hash"}); err != nil {+ t.Fatalf("ArchiveByHashes failed: %v", err)+ }++ // With includeArchived=false, should only see active+ groups, total, err := ExceptionStackTraceRepository.FindGrouped(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "count", "", "", false)+ if err != nil {+ t.Fatalf("FindGrouped failed: %v", err)+ }++ if total != 1 {+ t.Errorf("expected 1 group (excluding archived), got %d", total)+ }+ if len(groups) != 1 {+ t.Fatalf("expected 1 group entry, got %d", len(groups))+ }+ if groups[0].ExceptionHash != "active-hash" {+ t.Errorf("expected 'active-hash', got %q", groups[0].ExceptionHash)+ }+}++func TestExceptionRepository_FindById(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ exc := makeException(projectId, "find-id-hash", "Error for FindById", now)++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, []models.ExceptionStackTrace{exc}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := ExceptionStackTraceRepository.FindById(ctx, projectId, exc.Id)+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found == nil {+ t.Fatal("expected to find exception, got nil")+ }+ if found.ExceptionHash != "find-id-hash" {+ t.Errorf("expected hash 'find-id-hash', got %q", found.ExceptionHash)+ }+}++func TestExceptionRepository_FindById_NotFound(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ found, err := ExceptionStackTraceRepository.FindById(ctx, uuid.New(), uuid.New())+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found != nil {+ t.Errorf("expected nil for unknown exception, got %+v", found)+ }+}++func TestExceptionRepository_GetHourlyTrendForHashes(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Date(2025, 1, 15, 10, 0, 0, 0, time.UTC)++ exceptions := []models.ExceptionStackTrace{+ makeException(projectId, "trend-hash", "Error trend", base),+ makeException(projectId, "trend-hash", "Error trend", base.Add(30*time.Minute)),+ makeException(projectId, "trend-hash", "Error trend", base.Add(time.Hour+10*time.Minute)),+ }++ if err := ExceptionStackTraceRepository.InsertAsync(ctx, exceptions); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ trends, err := ExceptionStackTraceRepository.GetHourlyTrendForHashes(ctx, projectId, []string{"trend-hash"}, base.Add(-time.Minute), base.Add(2*time.Hour))+ if err != nil {+ t.Fatalf("GetHourlyTrendForHashes failed: %v", err)+ }++ points, ok := trends["trend-hash"]+ if !ok {+ t.Fatal("expected trend data for 'trend-hash'")+ }++ if len(points) != 2 {+ t.Fatalf("expected 2 hourly trend points, got %d", len(points))+ }++ if points[0].Count != 2 {+ t.Errorf("expected 2 exceptions in first hour, got %d", points[0].Count)+ }+ if points[1].Count != 1 {+ t.Errorf("expected 1 exception in second hour, got %d", points[1].Count)+ }+}++func TestExceptionRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := ExceptionStackTraceRepository.InsertAsync(ctx, []models.ExceptionStackTrace{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.goindex ab36f54a..0c1be8e7 100644--- a/backend/app/repositories/exception_stack_trace.repository.go+++ b/backend/app/repositories/exception_stack_trace.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (@@ -304,7 +306,8 @@ func (e *exceptionStackTraceRepository) UnarchiveByHashes(ctx context.Context, p}// In ClickHouse, we use ALTER TABLE DELETE for removing rows- query := "ALTER TABLE archived_exceptions DELETE WHERE project_id = ? AND exception_hash IN (?)"+ // mutations_sync = 1 ensures the mutation completes before returning+ query := "ALTER TABLE archived_exceptions DELETE WHERE project_id = ? AND exception_hash IN (?) SETTINGS mutations_sync = 1"return chdb.Conn.Exec(ctx, query, projectId, hashes)}diff --git a/backend/app/repositories/exception_stack_trace.repository_sqlite.go b/backend/app/repositories/exception_stack_trace.repository_sqlite.gonew file mode 100644index 00000000..4fd99093--- /dev/null+++ b/backend/app/repositories/exception_stack_trace.repository_sqlite.go@@ -0,0 +1,497 @@+//go:build !pgch++package repositories++import (+ "context"+ "database/sql"+ "encoding/json"+ "errors"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type exceptionStackTraceRepository struct{}++func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines []models.ExceptionStackTrace) error {+ if len(lines) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx,+ `INSERT INTO exception_stack_traces (id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, est := range lines {+ attributesJSON := "{}"+ if len(est.Attributes) != 0 {+ if attributesBytes, err := json.Marshal(est.Attributes); err == nil {+ attributesJSON = string(attributesBytes)+ }+ }++ isMessage := 0+ if est.IsMessage {+ isMessage = 1+ }++ traceType := est.TraceType+ if traceType == "" {+ traceType = "endpoint"+ }++ traceIdStr := ""+ if est.TraceId != nil {+ traceIdStr = est.TraceId.String()+ }++ if _, err := stmt.ExecContext(ctx,+ est.Id.String(),+ est.ProjectId.String(),+ traceIdStr,+ traceType,+ est.ExceptionHash,+ est.StackTrace,+ est.RecordedAt.UTC().Format(time.RFC3339Nano),+ attributesJSON,+ est.AppVersion,+ est.ServerName,+ isMessage,+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM exception_stack_traces WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano)).Scan(&count)+ return count, err+}++func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, search string, searchType string, includeArchived bool) ([]models.ExceptionGroup, int64, error) {+ offset := (page - 1) * pageSize++ sortDirection := "DESC"+ if strings.HasSuffix(orderBy, "_asc") {+ orderBy = strings.TrimSuffix(orderBy, "_asc")+ sortDirection = "ASC"+ }++ allowedOrderBy := map[string]bool{+ "last_seen": true,+ "first_seen": true,+ "count": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "count"+ }++ whereClause := "e.project_id = ? AND e.recorded_at >= ? AND e.recorded_at <= ?"+ args := []interface{}{projectId.String(), fromDate.UTC().Format(time.RFC3339Nano), toDate.UTC().Format(time.RFC3339Nano)}++ if search != "" {+ whereClause += " AND INSTR(LOWER(e.stack_trace), LOWER(?)) > 0"+ args = append(args, search)+ }++ if searchType == "issues" {+ whereClause += " AND e.is_message = 0"+ } else if searchType == "messages" {+ whereClause += " AND e.is_message = 1"+ }++ havingClause := ""+ if !includeArchived {+ havingClause = " HAVING max_archived_at IS NULL OR MAX(e.recorded_at) > max_archived_at"+ }++ archiveSubquery := `LEFT JOIN (+ SELECT exception_hash, MAX(archived_at) as archived_at+ FROM archived_exceptions+ WHERE project_id = ?+ GROUP BY exception_hash+ ) a ON e.exception_hash = a.exception_hash`++ countQuery := `SELECT COUNT(*) FROM (+ SELECT e.exception_hash, MAX(a.archived_at) as max_archived_at+ FROM exception_stack_traces e+ ` + archiveSubquery + `+ WHERE ` + whereClause + `+ GROUP BY e.exception_hash` + havingClause + `+ )`++ countArgs := append([]interface{}{projectId.String()}, args...)+ var count int64+ err := db.DB.QueryRowContext(ctx, countQuery, countArgs...).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ fullQuery := `SELECT e.exception_hash, e.stack_trace, MAX(e.recorded_at) as last_seen, MIN(e.recorded_at) as first_seen, COUNT(*) as count, MAX(a.archived_at) as max_archived_at+ FROM exception_stack_traces e+ ` + archiveSubquery + `+ WHERE ` + whereClause + `+ GROUP BY e.exception_hash` + havingClause + `+ ORDER BY ` + orderBy + ` ` + sortDirection + ` LIMIT ? OFFSET ?`++ queryArgs := append([]interface{}{projectId.String()}, args...)+ queryArgs = append(queryArgs, pageSize, offset)+ rows, err := db.DB.QueryContext(ctx, fullQuery, queryArgs...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var groups []models.ExceptionGroup+ for rows.Next() {+ var g models.ExceptionGroup+ var lastSeenStr, firstSeenStr string+ var maxArchivedAt sql.NullString+ if err := rows.Scan(&g.ExceptionHash, &g.StackTrace, &lastSeenStr, &firstSeenStr, &g.Count, &maxArchivedAt); err != nil {+ return nil, 0, err+ }+ g.LastSeen, _ = time.Parse(time.RFC3339Nano, lastSeenStr)+ g.FirstSeen, _ = time.Parse(time.RFC3339Nano, firstSeenStr)+ groups = append(groups, g)+ }++ return groups, count, nil+}++func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectId uuid.UUID, exceptionHash string, page, pageSize int) (*models.ExceptionGroup, []models.ExceptionStackTrace, int64, error) {+ offset := (page - 1) * pageSize++ var group models.ExceptionGroup+ var lastSeenStr, firstSeenStr string+ err := db.DB.QueryRowContext(ctx,+ `SELECT exception_hash, stack_trace, MAX(recorded_at) as last_seen, MIN(recorded_at) as first_seen, COUNT(*) as count+ FROM exception_stack_traces+ WHERE project_id = ? AND exception_hash = ?+ GROUP BY exception_hash`,+ projectId.String(), exceptionHash).Scan(&group.ExceptionHash, &group.StackTrace, &lastSeenStr, &firstSeenStr, &group.Count)+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil, 0, nil+ }+ return nil, nil, 0, err+ }+ group.LastSeen, _ = time.Parse(time.RFC3339Nano, lastSeenStr)+ group.FirstSeen, _ = time.Parse(time.RFC3339Nano, firstSeenStr)++ rows, err := db.DB.QueryContext(ctx,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message+ FROM exception_stack_traces+ WHERE project_id = ? AND exception_hash = ?+ ORDER BY recorded_at DESC LIMIT ? OFFSET ?`,+ projectId.String(), exceptionHash, pageSize, offset)+ if err != nil {+ return nil, nil, 0, err+ }+ defer rows.Close()++ var occurrences []models.ExceptionStackTrace+ for rows.Next() {+ o := scanExceptionStackTrace(rows)+ if o == nil {+ return nil, nil, 0, fmt.Errorf("failed to scan exception stack trace row")+ }+ occurrences = append(occurrences, *o)+ }++ return &group, occurrences, int64(group.Count), nil+}++func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ CAST(COUNT(*) AS REAL) as count+ FROM exception_stack_traces+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := db.DB.QueryContext(ctx, query, projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ var tsStr string+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *exceptionStackTraceRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ intervalSeconds := intervalMinutes * 60++ query := `SELECT+ datetime((strftime('%s', recorded_at) / ?) * ?, 'unixepoch') as bucket,+ CAST(COUNT(*) AS REAL) as count+ FROM exception_stack_traces+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`++ rows, err := db.DB.QueryContext(ctx, query, intervalSeconds, intervalSeconds, projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var p models.TimeSeriesPoint+ var tsStr string+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *exceptionStackTraceRepository) GetHourlyTrendForHashes(ctx context.Context, projectId uuid.UUID, hashes []string, start, end time.Time) (map[string][]models.ExceptionTrendPoint, error) {+ if len(hashes) == 0 {+ return make(map[string][]models.ExceptionTrendPoint), nil+ }++ placeholders := strings.TrimRight(strings.Repeat("?,", len(hashes)), ",")++ query := `SELECT+ exception_hash,+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ COUNT(*) as count+ FROM exception_stack_traces+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? AND exception_hash IN (` + placeholders + `)+ GROUP BY exception_hash, hour+ ORDER BY exception_hash, hour ASC`++ args := []interface{}{projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano)}+ for _, h := range hashes {+ args = append(args, h)+ }++ rows, err := db.DB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.ExceptionTrendPoint)+ for rows.Next() {+ var hash string+ var point models.ExceptionTrendPoint+ var tsStr string+ if err := rows.Scan(&hash, &tsStr, &point.Count); err != nil {+ return nil, err+ }+ point.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ result[hash] = append(result[hash], point)+ }++ return result, nil+}++func (e *exceptionStackTraceRepository) ArchiveByHashes(ctx context.Context, projectId uuid.UUID, hashes []string) error {+ if len(hashes) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx,+ "INSERT OR REPLACE INTO archived_exceptions (project_id, exception_hash, archived_at) VALUES (?, ?, ?)")+ if err != nil {+ return err+ }+ defer stmt.Close()++ now := time.Now().UTC().Format(time.RFC3339Nano)+ for _, hash := range hashes {+ if _, err := stmt.ExecContext(ctx, projectId.String(), hash, now); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (e *exceptionStackTraceRepository) UnarchiveByHashes(ctx context.Context, projectId uuid.UUID, hashes []string) error {+ if len(hashes) == 0 {+ return nil+ }++ placeholders := strings.TrimRight(strings.Repeat("?,", len(hashes)), ",")+ query := "DELETE FROM archived_exceptions WHERE project_id = ? AND exception_hash IN (" + placeholders + ")"++ args := []interface{}{projectId.String()}+ for _, h := range hashes {+ args = append(args, h)+ }++ _, err := db.DB.ExecContext(ctx, query, args...)+ return err+}++func (e *exceptionStackTraceRepository) IsArchived(ctx context.Context, projectId uuid.UUID, hash string) (bool, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM archived_exceptions WHERE project_id = ? AND exception_hash = ?",+ projectId.String(), hash).Scan(&count)+ if err != nil {+ return false, err+ }+ return count > 0, nil+}++func (e *exceptionStackTraceRepository) FindExceptionByTraceId(ctx context.Context, projectId uuid.UUID, traceId uuid.UUID) (*models.ExceptionStackTrace, error) {+ row := db.DB.QueryRowContext(ctx,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message+ FROM exception_stack_traces+ WHERE project_id = ? AND trace_id = ? AND is_message = 0+ LIMIT 1`,+ projectId.String(), traceId.String())++ est := scanExceptionStackTraceRow(row)+ return est, nil+}++func (e *exceptionStackTraceRepository) FindAllByTraceId(ctx context.Context, projectId uuid.UUID, traceId uuid.UUID) ([]models.ExceptionStackTrace, error) {+ rows, err := db.DB.QueryContext(ctx,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message+ FROM exception_stack_traces+ WHERE project_id = ? AND trace_id = ?+ ORDER BY recorded_at ASC`,+ projectId.String(), traceId.String())+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var results []models.ExceptionStackTrace+ for rows.Next() {+ o := scanExceptionStackTrace(rows)+ if o == nil {+ return nil, fmt.Errorf("failed to scan exception stack trace row")+ }+ results = append(results, *o)+ }++ return results, nil+}++func (e *exceptionStackTraceRepository) FindById(ctx context.Context, projectId uuid.UUID, id uuid.UUID) (*models.ExceptionStackTrace, error) {+ row := db.DB.QueryRowContext(ctx,+ `SELECT id, project_id, trace_id, trace_type, exception_hash, stack_trace, recorded_at, attributes, app_version, server_name, is_message+ FROM exception_stack_traces+ WHERE project_id = ? AND id = ?+ LIMIT 1`,+ projectId.String(), id.String())++ est := scanExceptionStackTraceRow(row)+ if est == nil {+ return nil, nil+ }+ return est, nil+}++func scanExceptionStackTraceRow(row *sql.Row) *models.ExceptionStackTrace {+ var est models.ExceptionStackTrace+ var idStr, projectIdStr, traceIdStr string+ var recordedAtStr, attributesJSON string+ var isMessage int++ err := row.Scan(&idStr, &projectIdStr, &traceIdStr, &est.TraceType, &est.ExceptionHash, &est.StackTrace,+ &recordedAtStr, &attributesJSON, &est.AppVersion, &est.ServerName, &isMessage)+ if err != nil {+ return nil+ }++ est.Id, _ = uuid.Parse(idStr)+ est.ProjectId, _ = uuid.Parse(projectIdStr)+ if traceIdStr != "" {+ parsed, err := uuid.Parse(traceIdStr)+ if err == nil {+ est.TraceId = &parsed+ }+ }+ est.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)+ est.IsMessage = isMessage == 1++ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &est.Attributes); err != nil {+ est.Attributes = nil+ }+ }++ return &est+}++func scanExceptionStackTrace(rows *sql.Rows) *models.ExceptionStackTrace {+ var est models.ExceptionStackTrace+ var idStr, projectIdStr, traceIdStr string+ var recordedAtStr, attributesJSON string+ var isMessage int++ err := rows.Scan(&idStr, &projectIdStr, &traceIdStr, &est.TraceType, &est.ExceptionHash, &est.StackTrace,+ &recordedAtStr, &attributesJSON, &est.AppVersion, &est.ServerName, &isMessage)+ if err != nil {+ return nil+ }++ est.Id, _ = uuid.Parse(idStr)+ est.ProjectId, _ = uuid.Parse(projectIdStr)+ if traceIdStr != "" {+ parsed, err := uuid.Parse(traceIdStr)+ if err == nil {+ est.TraceId = &parsed+ }+ }+ est.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)+ est.IsMessage = isMessage == 1++ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &est.Attributes); err != nil {+ est.Attributes = nil+ }+ }++ return &est+}++var ExceptionStackTraceRepository = exceptionStackTraceRepository{}diff --git a/backend/app/repositories/fired_notification.repository.go b/backend/app/repositories/fired_notification.repository.goindex a57d9c88..ca6e0ae6 100644--- a/backend/app/repositories/fired_notification.repository.go+++ b/backend/app/repositories/fired_notification.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/fired_notification.repository_sqlite.go b/backend/app/repositories/fired_notification.repository_sqlite.gonew file mode 100644index 00000000..0b8031af--- /dev/null+++ b/backend/app/repositories/fired_notification.repository_sqlite.go@@ -0,0 +1,42 @@+//go:build !pgch++package repositories++import (+ "context"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+)++type FiredNotification struct {+ ProjectId uuid.UUID+ RuleId int+ RuleType string+ RuleName string+ ChannelType string+ ChannelName string+ Severity string+ Subject string+ Body string+ Status string+ ErrorMsg string+ Endpoint string+ FiredAt time.Time+}++type firedNotificationRepository struct{}++func (r *firedNotificationRepository) Insert(ctx context.Context, n FiredNotification) error {+ _, err := db.DB.ExecContext(ctx,+ `INSERT INTO fired_notifications (project_id, rule_id, rule_type, rule_name, channel_type, channel_name, severity, subject, body, status, error_message, endpoint, fired_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+ n.ProjectId.String(), n.RuleId, n.RuleType, n.RuleName,+ n.ChannelType, n.ChannelName, n.Severity, n.Subject, n.Body,+ n.Status, n.ErrorMsg, n.Endpoint, n.FiredAt.UTC().Format(time.RFC3339Nano),+ )+ return err+}++var FiredNotificationRepository = firedNotificationRepository{}diff --git a/backend/app/repositories/fired_notification_repository_test.go b/backend/app/repositories/fired_notification_repository_test.gonew file mode 100644index 00000000..6a82c688--- /dev/null+++ b/backend/app/repositories/fired_notification_repository_test.go@@ -0,0 +1,37 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+)++func TestFiredNotificationRepository_Insert(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ n := makeFiredNotification(projectId, "High Error Rate", "sent", now)++ err := FiredNotificationRepository.Insert(ctx, n)+ if err != nil {+ t.Fatalf("Insert failed: %v", err)+ }+}++func TestFiredNotificationRepository_InsertMultiple(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ for i := 0; i < 5; i++ {+ n := makeFiredNotification(projectId, "Alert Rule", "sent", now.Add(time.Duration(i)*time.Minute))+ if err := FiredNotificationRepository.Insert(ctx, n); err != nil {+ t.Fatalf("Insert %d failed: %v", i, err)+ }+ }+}diff --git a/backend/app/repositories/helpers_test.go b/backend/app/repositories/helpers_test.gonew file mode 100644index 00000000..417f8691--- /dev/null+++ b/backend/app/repositories/helpers_test.go@@ -0,0 +1,114 @@+package repositories++import (+ "math"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func assertApproxEqual(t *testing.T, name string, got, want, tolerance float64) {+ t.Helper()+ if math.Abs(got-want) > tolerance {+ t.Errorf("%s: got %v, want %v (tolerance %v)", name, got, want, tolerance)+ }+}++func makeEndpoint(projectId uuid.UUID, endpoint string, duration time.Duration, statusCode int16, recordedAt time.Time) models.Endpoint {+ return models.Endpoint{+ Id: uuid.New(),+ ProjectId: projectId,+ Endpoint: endpoint,+ Duration: duration,+ RecordedAt: recordedAt,+ StatusCode: statusCode,+ BodySize: 100,+ ClientIP: "127.0.0.1",+ AppVersion: "1.0.0",+ ServerName: "test-server",+ }+}++func makeTask(projectId uuid.UUID, taskName string, duration time.Duration, recordedAt time.Time) models.Task {+ return models.Task{+ Id: uuid.New(),+ ProjectId: projectId,+ TaskName: taskName,+ Duration: duration,+ RecordedAt: recordedAt,+ ClientIP: "127.0.0.1",+ AppVersion: "1.0.0",+ ServerName: "test-server",+ }+}++func makeException(projectId uuid.UUID, hash, stackTrace string, recordedAt time.Time) models.ExceptionStackTrace {+ return models.ExceptionStackTrace{+ Id: uuid.New(),+ ProjectId: projectId,+ TraceType: "endpoint",+ ExceptionHash: hash,+ StackTrace: stackTrace,+ RecordedAt: recordedAt,+ AppVersion: "1.0.0",+ ServerName: "test-server",+ }+}++func makeSpan(projectId, traceId uuid.UUID, name string, startTime time.Time, duration time.Duration) models.Span {+ return models.Span{+ Id: uuid.New(),+ TraceId: traceId,+ ProjectId: projectId,+ Name: name,+ StartTime: startTime,+ Duration: duration,+ RecordedAt: startTime,+ }+}++func makeSessionRecording(projectId, exceptionId uuid.UUID, filePath string, recordedAt time.Time) models.SessionRecording {+ return models.SessionRecording{+ Id: uuid.New(),+ ProjectId: projectId,+ ExceptionId: exceptionId,+ FilePath: filePath,+ RecordedAt: recordedAt,+ }+}++func makeMetricPoint(projectId uuid.UUID, name string, value float64, tags map[string]string, recordedAt time.Time) models.MetricPoint {+ if tags == nil {+ tags = map[string]string{}+ }+ return models.MetricPoint{+ ProjectId: projectId,+ Name: name,+ Value: value,+ Tags: tags,+ RecordedAt: recordedAt,+ }+}++func makeFiredNotification(projectId uuid.UUID, ruleName, status string, firedAt time.Time) FiredNotification {+ return FiredNotification{+ ProjectId: projectId,+ RuleId: 1,+ RuleType: "event",+ RuleName: ruleName,+ ChannelType: "slack",+ ChannelName: "alerts",+ Severity: "warning",+ Subject: "Test Alert",+ Body: "Test alert body",+ Status: status,+ Endpoint: "GET /api/test",+ FiredAt: firedAt,+ }+}++func truncateMs(t time.Time) time.Time {+ return t.Truncate(time.Millisecond)+}diff --git a/backend/app/repositories/metric_point.repository.go b/backend/app/repositories/metric_point.repository.goindex f1844d09..d931385f 100644--- a/backend/app/repositories/metric_point.repository.go+++ b/backend/app/repositories/metric_point.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/metric_point.repository_sqlite.go b/backend/app/repositories/metric_point.repository_sqlite.gonew file mode 100644index 00000000..ce8ccf2e--- /dev/null+++ b/backend/app/repositories/metric_point.repository_sqlite.go@@ -0,0 +1,306 @@+//go:build !pgch++package repositories++import (+ "context"+ "encoding/json"+ "fmt"+ "strings"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type metricPointRepository struct{}++func (r *metricPointRepository) InsertAsync(ctx context.Context, points []models.MetricPoint) error {+ if len(points) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx, "INSERT INTO metric_points (project_id, name, value, tags, recorded_at) VALUES (?, ?, ?, ?, ?)")+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, p := range points {+ tags := p.Tags+ if tags == nil {+ tags = map[string]string{}+ }+ tagsJSON, err := json.Marshal(tags)+ if err != nil {+ return err+ }++ if _, err := stmt.ExecContext(ctx,+ p.ProjectId.String(),+ p.Name,+ p.Value,+ string(tagsJSON),+ p.RecordedAt.UTC().Format(time.RFC3339Nano),+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (r *metricPointRepository) QueryTimeSeries(ctx context.Context, projectId uuid.UUID, name string, from, to time.Time, intervalMinutes int, aggregation string, tagFilters map[string]string, groupBy string) (map[string][]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60++ aggFunc := sqliteAggregationFunc(aggregation)++ query := fmt.Sprintf("SELECT datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') AS bucket", secs, secs)++ args := []interface{}{}++ hasGroupBy := groupBy != ""+ if hasGroupBy {+ query += ", json_extract(tags, '$.' || ?) AS group_key"+ args = append(args, groupBy)+ }++ query += ", " + aggFunc + " AS agg_value FROM metric_points WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?"+ args = append(args, projectId.String(), name, from.UTC().Format(time.RFC3339Nano), to.UTC().Format(time.RFC3339Nano))++ for k, v := range tagFilters {+ query += " AND json_extract(tags, '$.' || ?) = ?"+ args = append(args, k, v)+ }++ query += " GROUP BY bucket"+ if hasGroupBy {+ query += ", group_key"+ }+ query += " ORDER BY bucket ASC"++ rows, err := db.DB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.TimeSeriesPoint)+ for rows.Next() {+ var bucketStr string+ var value float64+ groupKey := "__all__"++ if hasGroupBy {+ var groupKeyNullable *string+ if err := rows.Scan(&bucketStr, &groupKeyNullable, &value); err != nil {+ return nil, err+ }+ if groupKeyNullable != nil {+ groupKey = *groupKeyNullable+ }+ } else {+ if err := rows.Scan(&bucketStr, &value); err != nil {+ return nil, err+ }+ }++ bucket, err := time.Parse("2006-01-02 15:04:05", bucketStr)+ if err != nil {+ return nil, fmt.Errorf("failed to parse bucket time %q: %w", bucketStr, err)+ }++ if groupKey == "" {+ groupKey = "(empty)"+ }+ result[groupKey] = append(result[groupKey], models.TimeSeriesPoint{+ Timestamp: bucket,+ Value: value,+ })+ }+ return result, nil+}++func (r *metricPointRepository) DiscoverMetrics(ctx context.Context, projectId uuid.UUID, from, to time.Time) ([]models.DiscoveredMetric, error) {+ nameRows, err := db.DB.QueryContext(ctx,+ "SELECT DISTINCT name FROM metric_points WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY name ASC",+ projectId.String(), from.UTC().Format(time.RFC3339Nano), to.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer nameRows.Close()++ var names []string+ for nameRows.Next() {+ var name string+ if err := nameRows.Scan(&name); err != nil {+ return nil, err+ }+ names = append(names, name)+ }++ var metrics []models.DiscoveredMetric+ for _, name := range names {+ tagRows, err := db.DB.QueryContext(ctx,+ `SELECT DISTINCT j.key FROM metric_points, json_each(tags) j+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?+ ORDER BY j.key ASC`,+ projectId.String(), name, from.UTC().Format(time.RFC3339Nano), to.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }++ var tagKeys []string+ for tagRows.Next() {+ var key string+ if err := tagRows.Scan(&key); err != nil {+ tagRows.Close()+ return nil, err+ }+ tagKeys = append(tagKeys, key)+ }+ tagRows.Close()++ metrics = append(metrics, models.DiscoveredMetric{+ Name: name,+ TagKeys: tagKeys,+ })+ }++ return metrics, nil+}++func (r *metricPointRepository) DiscoverTagValues(ctx context.Context, projectId uuid.UUID, metricName, tagKey string, from, to time.Time) ([]string, error) {+ rows, err := db.DB.QueryContext(ctx,+ `SELECT DISTINCT json_extract(tags, '$.' || ?) AS tag_value+ FROM metric_points+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?+ AND json_extract(tags, '$.' || ?) IS NOT NULL+ AND json_extract(tags, '$.' || ?) != ''+ ORDER BY tag_value ASC`,+ tagKey, projectId.String(), metricName, from.UTC().Format(time.RFC3339Nano), to.UTC().Format(time.RFC3339Nano), tagKey, tagKey)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var values []string+ for rows.Next() {+ var v string+ if err := rows.Scan(&v); err != nil {+ return nil, err+ }+ values = append(values, v)+ }+ return values, nil+}++func (r *metricPointRepository) GetAverageBetween(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time) (float64, error) {+ var avg float64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COALESCE(avg(value), 0) FROM metric_points WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), name, start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano)).Scan(&avg)+ return avg, err+}++func (r *metricPointRepository) GetDistinctServers(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]string, error) {+ rows, err := db.DB.QueryContext(ctx,+ `SELECT DISTINCT json_extract(tags, '$.server_name') AS sn+ FROM metric_points+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ AND json_extract(tags, '$.server_name') IS NOT NULL+ AND json_extract(tags, '$.server_name') != ''+ ORDER BY sn ASC`,+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano))+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var servers []string+ for rows.Next() {+ var s string+ if err := rows.Scan(&s); err != nil {+ return nil, err+ }+ servers = append(servers, s)+ }+ return servers, nil+}++func (r *metricPointRepository) GetAverageByIntervalPerServer(ctx context.Context, projectId uuid.UUID, name string, start, end time.Time, intervalMinutes int, servers []string) (map[string][]models.TimeSeriesPoint, error) {+ secs := intervalMinutes * 60++ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / %d) * %d, 'unixepoch') AS bucket,+ json_extract(tags, '$.server_name') AS sn,+ avg(value) AS avg_value+ FROM metric_points+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?`, secs, secs)++ args := []interface{}{projectId.String(), name, start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano)}++ if len(servers) > 0 {+ placeholders := make([]string, len(servers))+ for i, s := range servers {+ placeholders[i] = "?"+ args = append(args, s)+ }+ query += " AND json_extract(tags, '$.server_name') IN (" + strings.Join(placeholders, ", ") + ")"+ } else {+ query += " AND json_extract(tags, '$.server_name') IS NOT NULL AND json_extract(tags, '$.server_name') != ''"+ }++ query += " GROUP BY bucket, sn ORDER BY bucket ASC, sn ASC"++ rows, err := db.DB.QueryContext(ctx, query, args...)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ result := make(map[string][]models.TimeSeriesPoint)+ for rows.Next() {+ var bucketStr string+ var serverName string+ var value float64+ if err := rows.Scan(&bucketStr, &serverName, &value); err != nil {+ return nil, err+ }++ bucket, err := time.Parse("2006-01-02 15:04:05", bucketStr)+ if err != nil {+ return nil, fmt.Errorf("failed to parse bucket time %q: %w", bucketStr, err)+ }++ result[serverName] = append(result[serverName], models.TimeSeriesPoint{+ Timestamp: bucket,+ Value: value,+ })+ }+ return result, nil+}++func sqliteAggregationFunc(agg string) string {+ switch agg {+ case "min":+ return "min(value)"+ case "max":+ return "max(value)"+ case "sum":+ return "sum(value)"+ case "count":+ return "CAST(COUNT(*) AS REAL)"+ default:+ return "avg(value)"+ }+}++var MetricPointRepository = metricPointRepository{}diff --git a/backend/app/repositories/metric_point_repository_test.go b/backend/app/repositories/metric_point_repository_test.gonew file mode 100644index 00000000..fd3ba17c--- /dev/null+++ b/backend/app/repositories/metric_point_repository_test.go@@ -0,0 +1,314 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestMetricPointRepository_InsertAndQueryTimeSeries(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 60.0, map[string]string{"server_name": "web-1"}, base.Add(5*time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 70.0, map[string]string{"server_name": "web-1"}, base.Add(35*time.Minute)),+ }++ err := MetricPointRepository.InsertAsync(ctx, points)+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "cpu.used_pcnt", base.Add(-time.Minute), base.Add(time.Hour), 30, "avg", nil, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries failed: %v", err)+ }++ series, ok := result["__all__"]+ if !ok {+ t.Fatal("expected '__all__' series key")+ }++ if len(series) != 2 {+ t.Fatalf("expected 2 time series buckets, got %d", len(series))+ }++ // First bucket avg = (50+60)/2 = 55+ assertApproxEqual(t, "first bucket avg", series[0].Value, 55.0, 0.1)+ // Second bucket avg = 70+ assertApproxEqual(t, "second bucket avg", series[1].Value, 70.0, 0.1)+}++func TestMetricPointRepository_QueryTimeSeries_WithGroupBy(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 80.0, map[string]string{"server_name": "web-2"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 60.0, map[string]string{"server_name": "web-1"}, base.Add(5*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "cpu.used_pcnt", base.Add(-time.Minute), base.Add(time.Hour), 60, "avg", nil, "server_name")+ if err != nil {+ t.Fatalf("QueryTimeSeries with groupBy failed: %v", err)+ }++ web1, ok := result["web-1"]+ if !ok {+ t.Fatal("expected 'web-1' series")+ }+ if len(web1) != 1 {+ t.Fatalf("expected 1 bucket for web-1, got %d", len(web1))+ }+ // avg of 50 and 60 = 55+ assertApproxEqual(t, "web-1 avg", web1[0].Value, 55.0, 0.1)++ web2, ok := result["web-2"]+ if !ok {+ t.Fatal("expected 'web-2' series")+ }+ if len(web2) != 1 {+ t.Fatalf("expected 1 bucket for web-2, got %d", len(web2))+ }+ assertApproxEqual(t, "web-2 avg", web2[0].Value, 80.0, 0.1)+}++func TestMetricPointRepository_QueryTimeSeries_WithTagFilter(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 80.0, map[string]string{"server_name": "web-2"}, base),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ filters := map[string]string{"server_name": "web-1"}+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "cpu.used_pcnt", base.Add(-time.Minute), base.Add(time.Hour), 60, "avg", filters, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries with tag filter failed: %v", err)+ }++ series, ok := result["__all__"]+ if !ok {+ t.Fatal("expected '__all__' series key")+ }+ if len(series) != 1 {+ t.Fatalf("expected 1 bucket (filtered to web-1 only), got %d", len(series))+ }+ assertApproxEqual(t, "filtered value", series[0].Value, 50.0, 0.1)+}++func TestMetricPointRepository_DiscoverMetrics(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "mem.used", 1024.0, map[string]string{"server_name": "web-1", "region": "us-east"}, base),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ metrics, err := MetricPointRepository.DiscoverMetrics(ctx, projectId, base.Add(-time.Minute), base.Add(time.Hour))+ if err != nil {+ t.Fatalf("DiscoverMetrics failed: %v", err)+ }++ if len(metrics) != 2 {+ t.Fatalf("expected 2 discovered metrics, got %d", len(metrics))+ }++ // Ordered by name ASC+ if metrics[0].Name != "cpu.used_pcnt" {+ t.Errorf("expected first metric 'cpu.used_pcnt', got %q", metrics[0].Name)+ }+ if metrics[1].Name != "mem.used" {+ t.Errorf("expected second metric 'mem.used', got %q", metrics[1].Name)+ }++ // mem.used should have 2 tag keys+ if len(metrics[1].TagKeys) != 2 {+ t.Errorf("expected 2 tag keys for mem.used, got %d", len(metrics[1].TagKeys))+ }+}++func TestMetricPointRepository_DiscoverTagValues(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 60.0, map[string]string{"server_name": "web-2"}, base.Add(time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 70.0, map[string]string{"server_name": "web-1"}, base.Add(2*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ values, err := MetricPointRepository.DiscoverTagValues(ctx, projectId, "cpu.used_pcnt", "server_name", base.Add(-time.Minute), base.Add(time.Hour))+ if err != nil {+ t.Fatalf("DiscoverTagValues failed: %v", err)+ }++ if len(values) != 2 {+ t.Fatalf("expected 2 tag values, got %d", len(values))+ }++ // Ordered ASC+ if values[0] != "web-1" {+ t.Errorf("expected first value 'web-1', got %q", values[0])+ }+ if values[1] != "web-2" {+ t.Errorf("expected second value 'web-2', got %q", values[1])+ }+}++func TestMetricPointRepository_GetAverageBetween(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 40.0, nil, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 60.0, nil, base.Add(time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 80.0, nil, base.Add(2*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ avg, err := MetricPointRepository.GetAverageBetween(ctx, projectId, "cpu.used_pcnt", base.Add(-time.Minute), base.Add(time.Hour))+ if err != nil {+ t.Fatalf("GetAverageBetween failed: %v", err)+ }++ // avg = (40+60+80)/3 = 60+ assertApproxEqual(t, "average", avg, 60.0, 0.1)+}++func TestMetricPointRepository_GetAverageBetween_NoData(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ avg, err := MetricPointRepository.GetAverageBetween(ctx, projectId, "nonexistent.metric", base.Add(-time.Minute), base.Add(time.Hour))+ if err != nil {+ t.Fatalf("GetAverageBetween failed: %v", err)+ }++ assertApproxEqual(t, "average with no data", avg, 0.0, 0.001)+}++func TestMetricPointRepository_GetDistinctServers(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "cpu.used_pcnt", 50.0, map[string]string{"server_name": "web-1"}, base),+ makeMetricPoint(projectId, "cpu.used_pcnt", 60.0, map[string]string{"server_name": "web-2"}, base.Add(time.Minute)),+ makeMetricPoint(projectId, "cpu.used_pcnt", 70.0, map[string]string{"server_name": "web-1"}, base.Add(2*time.Minute)),+ makeMetricPoint(projectId, "mem.used", 1024.0, map[string]string{"server_name": "web-3"}, base.Add(3*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ servers, err := MetricPointRepository.GetDistinctServers(ctx, projectId, base.Add(-time.Minute), base.Add(time.Hour))+ if err != nil {+ t.Fatalf("GetDistinctServers failed: %v", err)+ }++ if len(servers) != 3 {+ t.Fatalf("expected 3 distinct servers, got %d: %v", len(servers), servers)+ }+}++func TestMetricPointRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := MetricPointRepository.InsertAsync(ctx, []models.MetricPoint{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}++func TestMetricPointRepository_QueryTimeSeries_Aggregations(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Now().UTC().Truncate(time.Hour)++ points := []models.MetricPoint{+ makeMetricPoint(projectId, "response_time", 100.0, nil, base),+ makeMetricPoint(projectId, "response_time", 200.0, nil, base.Add(time.Minute)),+ makeMetricPoint(projectId, "response_time", 300.0, nil, base.Add(2*time.Minute)),+ }++ if err := MetricPointRepository.InsertAsync(ctx, points); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ from := base.Add(-time.Minute)+ to := base.Add(time.Hour)++ // Test min aggregation+ result, err := MetricPointRepository.QueryTimeSeries(ctx, projectId, "response_time", from, to, 60, "min", nil, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries min failed: %v", err)+ }+ series := result["__all__"]+ if len(series) != 1 {+ t.Fatalf("expected 1 bucket, got %d", len(series))+ }+ assertApproxEqual(t, "min", series[0].Value, 100.0, 0.1)++ // Test max aggregation+ result, err = MetricPointRepository.QueryTimeSeries(ctx, projectId, "response_time", from, to, 60, "max", nil, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries max failed: %v", err)+ }+ series = result["__all__"]+ assertApproxEqual(t, "max", series[0].Value, 300.0, 0.1)++ // Test sum aggregation+ result, err = MetricPointRepository.QueryTimeSeries(ctx, projectId, "response_time", from, to, 60, "sum", nil, "")+ if err != nil {+ t.Fatalf("QueryTimeSeries sum failed: %v", err)+ }+ series = result["__all__"]+ assertApproxEqual(t, "sum", series[0].Value, 600.0, 0.1)+}diff --git a/backend/app/repositories/percentile.go b/backend/app/repositories/percentile.gonew file mode 100644index 00000000..1dd167bc--- /dev/null+++ b/backend/app/repositories/percentile.go@@ -0,0 +1,18 @@+package repositories++func computePercentile(sorted []float64, p float64) float64 {+ n := len(sorted)+ if n == 0 {+ return 0+ }+ if n == 1 {+ return sorted[0]+ }+ idx := p * float64(n-1)+ lower := int(idx)+ frac := idx - float64(lower)+ if lower+1 >= n {+ return sorted[lower]+ }+ return sorted[lower]*(1-frac) + sorted[lower+1]*frac+}diff --git a/backend/app/repositories/session_recording.repository.go b/backend/app/repositories/session_recording.repository.goindex 71c5c975..7f139f19 100644--- a/backend/app/repositories/session_recording.repository.go+++ b/backend/app/repositories/session_recording.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/session_recording.repository_sqlite.go b/backend/app/repositories/session_recording.repository_sqlite.gonew file mode 100644index 00000000..25460d69--- /dev/null+++ b/backend/app/repositories/session_recording.repository_sqlite.go@@ -0,0 +1,61 @@+//go:build !pgch++package repositories++import (+ "context"+ "database/sql"+ "errors"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type sessionRecordingRepository struct{}++func (r *sessionRecordingRepository) InsertAsync(ctx context.Context, recordings []models.SessionRecording) error {+ if len(recordings) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx, "INSERT INTO session_recordings (id, project_id, exception_id, file_path, recorded_at) VALUES (?, ?, ?, ?, ?)")+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, rec := range recordings {+ if _, err := stmt.ExecContext(ctx,+ rec.Id.String(), rec.ProjectId.String(), rec.ExceptionId.String(),+ rec.FilePath, rec.RecordedAt.UTC().Format(time.RFC3339Nano),+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (r *sessionRecordingRepository) FindByExceptionId(ctx context.Context, projectId uuid.UUID, exceptionId uuid.UUID) (string, error) {+ var filePath string+ err := db.DB.QueryRowContext(ctx,+ "SELECT file_path FROM session_recordings WHERE project_id = ? AND exception_id = ? ORDER BY recorded_at DESC LIMIT 1",+ projectId.String(), exceptionId.String()).Scan(&filePath)+ if err != nil {+ if errors.Is(err, sql.ErrNoRows) {+ return "", sql.ErrNoRows+ }+ return "", err+ }+ return filePath, nil+}++var SessionRecordingRepository = sessionRecordingRepository{}diff --git a/backend/app/repositories/session_recording_repository_test.go b/backend/app/repositories/session_recording_repository_test.gonew file mode 100644index 00000000..4bf3b0ca--- /dev/null+++ b/backend/app/repositories/session_recording_repository_test.go@@ -0,0 +1,81 @@+package repositories++import (+ "context"+ "database/sql"+ "errors"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestSessionRecordingRepository_InsertAndFind(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ exceptionId := uuid.New()+ now := truncateMs(time.Now().UTC())++ rec := makeSessionRecording(projectId, exceptionId, "/recordings/session-1.json", now)++ err := SessionRecordingRepository.InsertAsync(ctx, []models.SessionRecording{rec})+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ filePath, err := SessionRecordingRepository.FindByExceptionId(ctx, projectId, exceptionId)+ if err != nil {+ t.Fatalf("FindByExceptionId failed: %v", err)+ }++ if filePath != "/recordings/session-1.json" {+ t.Errorf("expected file path '/recordings/session-1.json', got %q", filePath)+ }+}++func TestSessionRecordingRepository_FindByExceptionId_NotFound(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ _, err := SessionRecordingRepository.FindByExceptionId(ctx, uuid.New(), uuid.New())+ if !errors.Is(err, sql.ErrNoRows) {+ t.Errorf("expected sql.ErrNoRows for unknown exception, got %v", err)+ }+}++func TestSessionRecordingRepository_ReturnsLatest(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ exceptionId := uuid.New()+ now := truncateMs(time.Now().UTC())++ rec1 := makeSessionRecording(projectId, exceptionId, "/recordings/old.json", now.Add(-time.Hour))+ rec2 := makeSessionRecording(projectId, exceptionId, "/recordings/new.json", now)++ err := SessionRecordingRepository.InsertAsync(ctx, []models.SessionRecording{rec1, rec2})+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ filePath, err := SessionRecordingRepository.FindByExceptionId(ctx, projectId, exceptionId)+ if err != nil {+ t.Fatalf("FindByExceptionId failed: %v", err)+ }++ if filePath != "/recordings/new.json" {+ t.Errorf("expected latest recording '/recordings/new.json', got %q", filePath)+ }+}++func TestSessionRecordingRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := SessionRecordingRepository.InsertAsync(ctx, []models.SessionRecording{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}diff --git a/backend/app/repositories/span.repository.go b/backend/app/repositories/span.repository.goindex 9f6601e3..945895c3 100644--- a/backend/app/repositories/span.repository.go+++ b/backend/app/repositories/span.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/span.repository_sqlite.go b/backend/app/repositories/span.repository_sqlite.gonew file mode 100644index 00000000..b378e388--- /dev/null+++ b/backend/app/repositories/span.repository_sqlite.go@@ -0,0 +1,77 @@+//go:build !pgch++package repositories++import (+ "context"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type spanRepository struct{}++func (r *spanRepository) InsertAsync(ctx context.Context, spans []models.Span) error {+ if len(spans) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx, "INSERT INTO spans (id, trace_id, project_id, name, start_time, duration, recorded_at) VALUES (?, ?, ?, ?, ?, ?, ?)")+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, s := range spans {+ if _, err := stmt.ExecContext(ctx,+ s.Id.String(), s.TraceId.String(), s.ProjectId.String(),+ s.Name, s.StartTime.UTC().Format(time.RFC3339Nano),+ int64(s.Duration), s.RecordedAt.UTC().Format(time.RFC3339Nano),+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (r *spanRepository) FindByTraceId(ctx context.Context, projectId, traceId uuid.UUID) ([]models.Span, error) {+ rows, err := db.DB.QueryContext(ctx,+ `SELECT id, trace_id, project_id, name, start_time, duration, recorded_at+ FROM spans+ WHERE project_id = ? AND trace_id = ?+ ORDER BY start_time ASC`,+ projectId.String(), traceId.String())+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var spans []models.Span+ for rows.Next() {+ var s models.Span+ var idStr, traceIdStr, projectIdStr string+ var startTimeStr, recordedAtStr string+ if err := rows.Scan(&idStr, &traceIdStr, &projectIdStr, &s.Name, &startTimeStr, &s.Duration, &recordedAtStr); err != nil {+ return nil, err+ }+ s.Id, _ = uuid.Parse(idStr)+ s.TraceId, _ = uuid.Parse(traceIdStr)+ s.ProjectId, _ = uuid.Parse(projectIdStr)+ s.StartTime, _ = time.Parse(time.RFC3339Nano, startTimeStr)+ s.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)+ spans = append(spans, s)+ }++ return spans, nil+}++var SpanRepository = spanRepository{}diff --git a/backend/app/repositories/span_repository_test.go b/backend/app/repositories/span_repository_test.gonew file mode 100644index 00000000..afc29ec8--- /dev/null+++ b/backend/app/repositories/span_repository_test.go@@ -0,0 +1,102 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestSpanRepository_InsertAndFindByTraceId(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ traceId := uuid.New()+ now := truncateMs(time.Now().UTC())++ s1 := makeSpan(projectId, traceId, "db.query", now, 100*time.Millisecond)+ s2 := makeSpan(projectId, traceId, "http.request", now.Add(10*time.Millisecond), 200*time.Millisecond)+ s3 := makeSpan(projectId, traceId, "cache.get", now.Add(20*time.Millisecond), 50*time.Millisecond)++ err := SpanRepository.InsertAsync(ctx, []models.Span{s1, s2, s3})+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := SpanRepository.FindByTraceId(ctx, projectId, traceId)+ if err != nil {+ t.Fatalf("FindByTraceId failed: %v", err)+ }++ if len(found) != 3 {+ t.Fatalf("expected 3 spans, got %d", len(found))+ }++ // Ordered by start_time ASC+ if found[0].Name != "db.query" {+ t.Errorf("expected first span name 'db.query', got %q", found[0].Name)+ }+ if found[1].Name != "http.request" {+ t.Errorf("expected second span name 'http.request', got %q", found[1].Name)+ }+ if found[2].Name != "cache.get" {+ t.Errorf("expected third span name 'cache.get', got %q", found[2].Name)+ }++ if found[0].Duration != 100*time.Millisecond {+ t.Errorf("expected duration 100ms, got %v", found[0].Duration)+ }+}++func TestSpanRepository_FindByTraceId_Empty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ found, err := SpanRepository.FindByTraceId(ctx, uuid.New(), uuid.New())+ if err != nil {+ t.Fatalf("FindByTraceId failed: %v", err)+ }++ if len(found) != 0 {+ t.Errorf("expected 0 spans for unknown trace, got %d", len(found))+ }+}++func TestSpanRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := SpanRepository.InsertAsync(ctx, []models.Span{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}++func TestSpanRepository_ProjectIsolation(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ project1 := uuid.New()+ project2 := uuid.New()+ traceId := uuid.New()+ now := truncateMs(time.Now().UTC())++ s1 := makeSpan(project1, traceId, "span-p1", now, 100*time.Millisecond)+ s2 := makeSpan(project2, traceId, "span-p2", now, 200*time.Millisecond)++ if err := SpanRepository.InsertAsync(ctx, []models.Span{s1, s2}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := SpanRepository.FindByTraceId(ctx, project1, traceId)+ if err != nil {+ t.Fatalf("FindByTraceId failed: %v", err)+ }+ if len(found) != 1 {+ t.Fatalf("expected 1 span for project1, got %d", len(found))+ }+ if found[0].Name != "span-p1" {+ t.Errorf("expected span name 'span-p1', got %q", found[0].Name)+ }+}diff --git a/backend/app/repositories/task.repository.go b/backend/app/repositories/task.repository.goindex 73840151..b86064ee 100644--- a/backend/app/repositories/task.repository.go+++ b/backend/app/repositories/task.repository.go@@ -1,3 +1,5 @@+//go:build pgch+package repositoriesimport (diff --git a/backend/app/repositories/task.repository_sqlite.go b/backend/app/repositories/task.repository_sqlite.gonew file mode 100644index 00000000..887768a8--- /dev/null+++ b/backend/app/repositories/task.repository_sqlite.go@@ -0,0 +1,613 @@+//go:build !pgch++package repositories++import (+ "context"+ "database/sql"+ "encoding/json"+ "fmt"+ "sort"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+)++type taskRepository struct{}++func (e *taskRepository) InsertAsync(ctx context.Context, lines []models.Task) error {+ if len(lines) == 0 {+ return nil+ }++ tx, err := db.DB.BeginTx(ctx, nil)+ if err != nil {+ return err+ }+ defer tx.Rollback()++ stmt, err := tx.PrepareContext(ctx, "INSERT INTO tasks (id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")+ if err != nil {+ return err+ }+ defer stmt.Close()++ for _, t := range lines {+ attributesJSON := "{}"+ if len(t.Attributes) != 0 {+ if attributesBytes, err := json.Marshal(t.Attributes); err == nil {+ attributesJSON = string(attributesBytes)+ }+ }+ if _, err := stmt.ExecContext(ctx,+ t.Id.String(), t.ProjectId.String(), t.TaskName,+ int64(t.Duration), t.RecordedAt.UTC().Format(time.RFC3339Nano),+ t.ClientIP, attributesJSON, t.AppVersion, t.ServerName,+ ); err != nil {+ return err+ }+ }++ return tx.Commit()+}++func (e *taskRepository) CountBetween(ctx context.Context, projectId uuid.UUID, start, end time.Time) (int64, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano),+ ).Scan(&count)+ return count, err+}++func (e *taskRepository) FindAll(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Task, int64, error) {+ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ projectId.String(), fromDate.UTC().Format(time.RFC3339Nano), toDate.UTC().Format(time.RFC3339Nano),+ ).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ query := "SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"+ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), fromDate.UTC().Format(time.RFC3339Nano), toDate.UTC().Format(time.RFC3339Nano),+ pageSize, offset,+ )+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var tasks []models.Task+ for rows.Next() {+ t, err := scanTask(rows)+ if err != nil {+ return nil, 0, err+ }+ tasks = append(tasks, t)+ }++ return tasks, count, nil+}++func (e *taskRepository) FindGroupedByTaskName(ctx context.Context, projectId uuid.UUID, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.TaskStats, int64, error) {+ fromStr := fromDate.UTC().Format(time.RFC3339Nano)+ toStr := toDate.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ var totalCount int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(DISTINCT task_name) FROM tasks WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?",+ pidStr, fromStr, toStr,+ ).Scan(&totalCount)+ if err != nil {+ return nil, 0, err+ }++ needsGoSort := orderBy == "p50_duration" || orderBy == "p95_duration" || orderBy == "impact"++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ offset := (page - 1) * pageSize++ var baseQuery string+ var baseArgs []interface{}++ if needsGoSort {+ baseQuery = `SELECT task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY task_name`+ baseArgs = []interface{}{pidStr, fromStr, toStr}+ } else {+ orderExpr := map[string]string{+ "count": "count",+ "last_seen": "last_seen",+ }+ expr, ok := orderExpr[orderBy]+ if !ok {+ expr = "count"+ }+ baseQuery = `SELECT task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY task_name+ ORDER BY ` + expr + ` ` + sortDir + `+ LIMIT ? OFFSET ?`+ baseArgs = []interface{}{pidStr, fromStr, toStr, pageSize, offset}+ }++ rows, err := db.DB.QueryContext(ctx, baseQuery, baseArgs...)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ type intermediate struct {+ taskName string+ count uint64+ avgDuration float64+ lastSeen string+ }++ var intermediates []intermediate+ for rows.Next() {+ var it intermediate+ if err := rows.Scan(&it.taskName, &it.count, &it.avgDuration, &it.lastSeen); err != nil {+ return nil, 0, err+ }+ intermediates = append(intermediates, it)+ }++ var stats []models.TaskStats+ for _, it := range intermediates {+ durRows, err := db.DB.QueryContext(ctx,+ "SELECT duration FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY duration ASC",+ pidStr, it.taskName, fromStr, toStr,+ )+ if err != nil {+ return nil, 0, err+ }++ var sorted []float64+ for durRows.Next() {+ var d float64+ if err := durRows.Scan(&d); err != nil {+ durRows.Close()+ return nil, 0, err+ }+ sorted = append(sorted, d)+ }+ durRows.Close()++ ls, _ := time.Parse(time.RFC3339Nano, it.lastSeen)+ stats = append(stats, models.TaskStats{+ TaskName: it.taskName,+ Count: it.count,+ P50Duration: time.Duration(computePercentile(sorted, 0.5)),+ P95Duration: time.Duration(computePercentile(sorted, 0.95)),+ AvgDuration: time.Duration(it.avgDuration),+ LastSeen: ls,+ })+ }++ if needsGoSort {+ switch orderBy {+ case "p50_duration":+ sort.Slice(stats, func(i, j int) bool {+ if sortDir == "ASC" {+ return stats[i].P50Duration < stats[j].P50Duration+ }+ return stats[i].P50Duration > stats[j].P50Duration+ })+ case "p95_duration":+ sort.Slice(stats, func(i, j int) bool {+ if sortDir == "ASC" {+ return stats[i].P95Duration < stats[j].P95Duration+ }+ return stats[i].P95Duration > stats[j].P95Duration+ })+ case "impact":+ sort.Slice(stats, func(i, j int) bool {+ impactI := float64(stats[i].Count) * float64(stats[i].P95Duration-stats[i].P50Duration)+ impactJ := float64(stats[j].Count) * float64(stats[j].P95Duration-stats[j].P50Duration)+ if sortDir == "ASC" {+ return impactI < impactJ+ }+ return impactI > impactJ+ })+ }++ end := offset + pageSize+ if end > len(stats) {+ end = len(stats)+ }+ if offset > len(stats) {+ stats = nil+ } else {+ stats = stats[offset:end]+ }+ }++ return stats, totalCount, nil+}++func (e *taskRepository) FindByTaskName(ctx context.Context, projectId uuid.UUID, taskName string, fromDate, toDate time.Time, page, pageSize int, orderBy string, sortDirection string) ([]models.Task, int64, error) {+ fromStr := fromDate.UTC().Format(time.RFC3339Nano)+ toStr := toDate.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ var count int64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*) FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ?",+ pidStr, taskName, fromStr, toStr,+ ).Scan(&count)+ if err != nil {+ return nil, 0, err+ }++ offset := (page - 1) * pageSize++ allowedOrderBy := map[string]bool{+ "recorded_at": true,+ "duration": true,+ }+ if !allowedOrderBy[orderBy] {+ orderBy = "recorded_at"+ }++ sortDir := "DESC"+ if sortDirection == "asc" {+ sortDir = "ASC"+ }++ query := "SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " " + sortDir + " LIMIT ? OFFSET ?"+ rows, err := db.DB.QueryContext(ctx, query, pidStr, taskName, fromStr, toStr, pageSize, offset)+ if err != nil {+ return nil, 0, err+ }+ defer rows.Close()++ var tasks []models.Task+ for rows.Next() {+ t, err := scanTask(rows)+ if err != nil {+ return nil, 0, err+ }+ tasks = append(tasks, t)+ }++ return tasks, count, nil+}++func (e *taskRepository) FindById(ctx context.Context, projectId, taskId uuid.UUID) (*models.Task, error) {+ row := db.DB.QueryRowContext(ctx,+ `SELECT id, project_id, task_name, duration, recorded_at, client_ip, attributes, app_version, server_name+ FROM tasks+ WHERE project_id = ? AND id = ?+ LIMIT 1`,+ projectId.String(), taskId.String(),+ )++ var t models.Task+ var idStr, projectIdStr string+ var recordedAtStr string+ var dur int64+ var attributesJSON string++ err := row.Scan(&idStr, &projectIdStr, &t.TaskName, &dur, &recordedAtStr, &t.ClientIP, &attributesJSON, &t.AppVersion, &t.ServerName)+ if err != nil {+ if err == sql.ErrNoRows {+ return nil, nil+ }+ return nil, err+ }++ t.Id, _ = uuid.Parse(idStr)+ t.ProjectId, _ = uuid.Parse(projectIdStr)+ t.Duration = time.Duration(dur)+ t.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)++ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &t.Attributes); err != nil {+ t.Attributes = nil+ }+ }++ return &t, nil+}++func (e *taskRepository) CountByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ CAST(COUNT(*) AS REAL) as count+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano),+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var tsStr string+ var p models.TimeSeriesPoint+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *taskRepository) AvgDurationByHour(ctx context.Context, projectId uuid.UUID, start, end time.Time) ([]models.TimeSeriesPoint, error) {+ query := `SELECT+ strftime('%Y-%m-%d %H:00:00', recorded_at) as hour,+ AVG(duration) / 1000000.0 as avg_duration_ms+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY hour+ ORDER BY hour ASC`++ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano),+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var tsStr string+ var p models.TimeSeriesPoint+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *taskRepository) CountByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / (%d * 60)) * (%d * 60), 'unixepoch') as bucket,+ CAST(COUNT(*) AS REAL) as count+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`, intervalMinutes, intervalMinutes)++ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano),+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var tsStr string+ var p models.TimeSeriesPoint+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *taskRepository) AvgDurationByInterval(ctx context.Context, projectId uuid.UUID, start, end time.Time, intervalMinutes int) ([]models.TimeSeriesPoint, error) {+ query := fmt.Sprintf(`SELECT+ datetime((strftime('%%s', recorded_at) / (%d * 60)) * (%d * 60), 'unixepoch') as bucket,+ AVG(duration) / 1000000.0 as avg_duration_ms+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY bucket+ ORDER BY bucket ASC`, intervalMinutes, intervalMinutes)++ rows, err := db.DB.QueryContext(ctx, query,+ projectId.String(), start.UTC().Format(time.RFC3339Nano), end.UTC().Format(time.RFC3339Nano),+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var points []models.TimeSeriesPoint+ for rows.Next() {+ var tsStr string+ var p models.TimeSeriesPoint+ if err := rows.Scan(&tsStr, &p.Value); err != nil {+ return nil, err+ }+ p.Timestamp, _ = time.Parse("2006-01-02 15:04:05", tsStr)+ points = append(points, p)+ }++ return points, nil+}++func (e *taskRepository) FindWorstTasks(ctx context.Context, projectId uuid.UUID, start, end time.Time, limit int) ([]models.TaskStats, error) {+ fromStr := start.UTC().Format(time.RFC3339Nano)+ toStr := end.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ rows, err := db.DB.QueryContext(ctx,+ `SELECT task_name, COUNT(*) as count, AVG(duration) as avg_duration, MAX(recorded_at) as last_seen+ FROM tasks+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?+ GROUP BY task_name`,+ pidStr, fromStr, toStr,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ type intermediate struct {+ taskName string+ count uint64+ avgDuration float64+ lastSeen string+ }++ var intermediates []intermediate+ for rows.Next() {+ var it intermediate+ if err := rows.Scan(&it.taskName, &it.count, &it.avgDuration, &it.lastSeen); err != nil {+ return nil, err+ }+ intermediates = append(intermediates, it)+ }++ var stats []models.TaskStats+ for _, it := range intermediates {+ durRows, err := db.DB.QueryContext(ctx,+ "SELECT duration FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY duration ASC",+ pidStr, it.taskName, fromStr, toStr,+ )+ if err != nil {+ return nil, err+ }++ var sorted []float64+ for durRows.Next() {+ var d float64+ if err := durRows.Scan(&d); err != nil {+ durRows.Close()+ return nil, err+ }+ sorted = append(sorted, d)+ }+ durRows.Close()++ ls, _ := time.Parse(time.RFC3339Nano, it.lastSeen)+ stats = append(stats, models.TaskStats{+ TaskName: it.taskName,+ Count: it.count,+ P50Duration: time.Duration(computePercentile(sorted, 0.5)),+ P95Duration: time.Duration(computePercentile(sorted, 0.95)),+ AvgDuration: time.Duration(it.avgDuration),+ LastSeen: ls,+ })+ }++ sort.Slice(stats, func(i, j int) bool {+ impactI := float64(stats[i].Count) * float64(stats[i].P95Duration-stats[i].P50Duration)+ impactJ := float64(stats[j].Count) * float64(stats[j].P95Duration-stats[j].P50Duration)+ return impactI > impactJ+ })++ if limit > len(stats) {+ limit = len(stats)+ }+ return stats[:limit], nil+}++func (e *taskRepository) GetTaskStats(ctx context.Context, projectId uuid.UUID, taskName string, start, end time.Time) (*models.TaskDetailStats, error) {+ fromStr := start.UTC().Format(time.RFC3339Nano)+ toStr := end.UTC().Format(time.RFC3339Nano)+ pidStr := projectId.String()++ durationMinutes := end.Sub(start).Minutes()+ if durationMinutes < 1 {+ durationMinutes = 1+ }++ var count int64+ var avgDur float64+ err := db.DB.QueryRowContext(ctx,+ "SELECT COUNT(*), AVG(duration) / 1000000.0 FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ?",+ pidStr, taskName, fromStr, toStr,+ ).Scan(&count, &avgDur)+ if err != nil {+ return nil, err+ }++ durRows, err := db.DB.QueryContext(ctx,+ "SELECT duration FROM tasks WHERE project_id = ? AND task_name = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY duration ASC",+ pidStr, taskName, fromStr, toStr,+ )+ if err != nil {+ return nil, err+ }+ defer durRows.Close()++ var sorted []float64+ for durRows.Next() {+ var d float64+ if err := durRows.Scan(&d); err != nil {+ return nil, err+ }+ sorted = append(sorted, d)+ }++ nsToMs := 1000000.0++ return &models.TaskDetailStats{+ Count: count,+ AvgDuration: avgDur,+ MedianDuration: computePercentile(sorted, 0.5) / nsToMs,+ P95Duration: computePercentile(sorted, 0.95) / nsToMs,+ P99Duration: computePercentile(sorted, 0.99) / nsToMs,+ Throughput: float64(count) / durationMinutes,+ }, nil+}++func scanTask(rows *sql.Rows) (models.Task, error) {+ var t models.Task+ var idStr, projectIdStr string+ var recordedAtStr string+ var dur int64+ var attributesJSON string++ if err := rows.Scan(&idStr, &projectIdStr, &t.TaskName, &dur, &recordedAtStr, &t.ClientIP, &attributesJSON, &t.AppVersion, &t.ServerName); err != nil {+ return t, err+ }++ t.Id, _ = uuid.Parse(idStr)+ t.ProjectId, _ = uuid.Parse(projectIdStr)+ t.Duration = time.Duration(dur)+ t.RecordedAt, _ = time.Parse(time.RFC3339Nano, recordedAtStr)++ if attributesJSON != "" && attributesJSON != "{}" {+ if err := json.Unmarshal([]byte(attributesJSON), &t.Attributes); err != nil {+ t.Attributes = nil+ }+ }++ return t, nil+}++var TaskRepository = taskRepository{}diff --git a/backend/app/repositories/task_repository_test.go b/backend/app/repositories/task_repository_test.gonew file mode 100644index 00000000..f9cf3816--- /dev/null+++ b/backend/app/repositories/task_repository_test.go@@ -0,0 +1,380 @@+package repositories++import (+ "context"+ "testing"+ "time"++ "github.com/google/uuid"+ "github.com/tracewayapp/traceway/backend/app/models"+)++func TestTaskRepository_InsertAndCount(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "email.send", 100*time.Millisecond, now),+ makeTask(projectId, "email.send", 200*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "report.generate", 500*time.Millisecond, now.Add(2*time.Minute)),+ }++ err := TaskRepository.InsertAsync(ctx, tasks)+ if err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := TaskRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 3 {+ t.Errorf("expected count 3, got %d", count)+ }+}++func TestTaskRepository_CountBetween_TimeFilter(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "task-old", 100*time.Millisecond, now.Add(-2*time.Hour)),+ makeTask(projectId, "task-recent", 100*time.Millisecond, now),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ count, err := TaskRepository.CountBetween(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour))+ if err != nil {+ t.Fatalf("CountBetween failed: %v", err)+ }++ if count != 1 {+ t.Errorf("expected count 1 (only recent task), got %d", count)+ }+}++func TestTaskRepository_FindAll(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "task-a", 100*time.Millisecond, now),+ makeTask(projectId, "task-b", 200*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "task-c", 300*time.Millisecond, now.Add(2*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, total, err := TaskRepository.FindAll(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at")+ if err != nil {+ t.Fatalf("FindAll failed: %v", err)+ }++ if total != 3 {+ t.Errorf("expected total 3, got %d", total)+ }+ if len(found) != 3 {+ t.Errorf("expected 3 results, got %d", len(found))+ }+}++func TestTaskRepository_FindAll_Pagination(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := make([]models.Task, 5)+ for i := range tasks {+ tasks[i] = makeTask(projectId, "task", time.Duration(i+1)*100*time.Millisecond, now.Add(time.Duration(i)*time.Minute))+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ page1, total, err := TaskRepository.FindAll(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 2, "recorded_at")+ if err != nil {+ t.Fatalf("FindAll page 1 failed: %v", err)+ }+ if total != 5 {+ t.Errorf("expected total 5, got %d", total)+ }+ if len(page1) != 2 {+ t.Errorf("expected 2 results on page 1, got %d", len(page1))+ }++ page3, _, err := TaskRepository.FindAll(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 3, 2, "recorded_at")+ if err != nil {+ t.Fatalf("FindAll page 3 failed: %v", err)+ }+ if len(page3) != 1 {+ t.Errorf("expected 1 result on page 3, got %d", len(page3))+ }+}++func TestTaskRepository_FindGroupedByTaskName(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "email.send", 100*time.Millisecond, now),+ makeTask(projectId, "email.send", 300*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "report.generate", 500*time.Millisecond, now.Add(2*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ stats, total, err := TaskRepository.FindGroupedByTaskName(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "count", "desc")+ if err != nil {+ t.Fatalf("FindGroupedByTaskName failed: %v", err)+ }++ if total != 2 {+ t.Errorf("expected 2 distinct task names, got %d", total)+ }+ if len(stats) != 2 {+ t.Fatalf("expected 2 grouped stats, got %d", len(stats))+ }++ // First should be email.send (count=2) when ordered by count desc+ if stats[0].TaskName != "email.send" {+ t.Errorf("expected first group to be 'email.send', got %q", stats[0].TaskName)+ }+ if stats[0].Count != 2 {+ t.Errorf("expected count 2 for email.send, got %d", stats[0].Count)+ }+}++func TestTaskRepository_FindByTaskName(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "email.send", 100*time.Millisecond, now),+ makeTask(projectId, "email.send", 200*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "other.task", 300*time.Millisecond, now.Add(2*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, total, err := TaskRepository.FindByTaskName(ctx, projectId, "email.send", now.Add(-time.Hour), now.Add(time.Hour), 1, 10, "recorded_at", "desc")+ if err != nil {+ t.Fatalf("FindByTaskName failed: %v", err)+ }++ if total != 2 {+ t.Errorf("expected total 2, got %d", total)+ }+ if len(found) != 2 {+ t.Errorf("expected 2 results, got %d", len(found))+ }+ for _, f := range found {+ if f.TaskName != "email.send" {+ t.Errorf("expected task name 'email.send', got %q", f.TaskName)+ }+ }+}++func TestTaskRepository_FindById(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ task := makeTask(projectId, "specific.task", 150*time.Millisecond, now)++ if err := TaskRepository.InsertAsync(ctx, []models.Task{task}); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ found, err := TaskRepository.FindById(ctx, projectId, task.Id)+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found == nil {+ t.Fatal("expected to find task, got nil")+ }+ if found.TaskName != "specific.task" {+ t.Errorf("expected task name 'specific.task', got %q", found.TaskName)+ }+ if found.Duration != 150*time.Millisecond {+ t.Errorf("expected duration 150ms, got %v", found.Duration)+ }+}++func TestTaskRepository_FindById_NotFound(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ found, err := TaskRepository.FindById(ctx, uuid.New(), uuid.New())+ if err != nil {+ t.Fatalf("FindById failed: %v", err)+ }+ if found != nil {+ t.Errorf("expected nil for unknown task, got %+v", found)+ }+}++func TestTaskRepository_CountByHour(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC()).Truncate(time.Hour)++ tasks := []models.Task{+ makeTask(projectId, "task-a", 100*time.Millisecond, now),+ makeTask(projectId, "task-b", 100*time.Millisecond, now.Add(30*time.Minute)),+ makeTask(projectId, "task-c", 100*time.Millisecond, now.Add(time.Hour+10*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ points, err := TaskRepository.CountByHour(ctx, projectId, now.Add(-time.Minute), now.Add(2*time.Hour))+ if err != nil {+ t.Fatalf("CountByHour failed: %v", err)+ }++ if len(points) != 2 {+ t.Fatalf("expected 2 hourly buckets, got %d", len(points))+ }++ if points[0].Value != 2 {+ t.Errorf("expected 2 tasks in first hour, got %v", points[0].Value)+ }+ if points[1].Value != 1 {+ t.Errorf("expected 1 task in second hour, got %v", points[1].Value)+ }+}++func TestTaskRepository_CountByInterval(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ base := time.Date(2025, 1, 15, 10, 0, 0, 0, time.UTC)++ tasks := []models.Task{+ makeTask(projectId, "task-1", 100*time.Millisecond, base),+ makeTask(projectId, "task-2", 100*time.Millisecond, base.Add(10*time.Minute)),+ makeTask(projectId, "task-3", 100*time.Millisecond, base.Add(35*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ points, err := TaskRepository.CountByInterval(ctx, projectId, base.Add(-time.Minute), base.Add(time.Hour), 30)+ if err != nil {+ t.Fatalf("CountByInterval failed: %v", err)+ }++ if len(points) != 2 {+ t.Fatalf("expected 2 interval buckets, got %d", len(points))+ }+}++func TestTaskRepository_FindWorstTasks(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "fast.task", 10*time.Millisecond, now),+ makeTask(projectId, "fast.task", 20*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "slow.task", 1*time.Second, now),+ makeTask(projectId, "slow.task", 5*time.Second, now.Add(time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ worst, err := TaskRepository.FindWorstTasks(ctx, projectId, now.Add(-time.Hour), now.Add(time.Hour), 5)+ if err != nil {+ t.Fatalf("FindWorstTasks failed: %v", err)+ }++ if len(worst) != 2 {+ t.Fatalf("expected 2 task groups, got %d", len(worst))+ }++ // slow.task should have higher impact (larger P95-P50 spread * count)+ if worst[0].TaskName != "slow.task" {+ t.Errorf("expected worst task to be 'slow.task', got %q", worst[0].TaskName)+ }+}++func TestTaskRepository_GetTaskStats(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()+ projectId := uuid.New()+ now := truncateMs(time.Now().UTC())++ tasks := []models.Task{+ makeTask(projectId, "measured.task", 100*time.Millisecond, now),+ makeTask(projectId, "measured.task", 200*time.Millisecond, now.Add(time.Minute)),+ makeTask(projectId, "measured.task", 300*time.Millisecond, now.Add(2*time.Minute)),+ }++ if err := TaskRepository.InsertAsync(ctx, tasks); err != nil {+ t.Fatalf("InsertAsync failed: %v", err)+ }++ start := now.Add(-time.Hour)+ end := now.Add(time.Hour)+ stats, err := TaskRepository.GetTaskStats(ctx, projectId, "measured.task", start, end)+ if err != nil {+ t.Fatalf("GetTaskStats failed: %v", err)+ }++ if stats.Count != 3 {+ t.Errorf("expected count 3, got %d", stats.Count)+ }++ // avg = 200ms+ assertApproxEqual(t, "AvgDuration", stats.AvgDuration, 200.0, 1.0)++ // median of [100, 200, 300] = 200ms+ assertApproxEqual(t, "MedianDuration", stats.MedianDuration, 200.0, 1.0)++ if stats.P95Duration < 200 || stats.P95Duration > 300 {+ t.Errorf("P95Duration %v out of expected range [200, 300]ms", stats.P95Duration)+ }++ if stats.Throughput <= 0 {+ t.Errorf("expected positive throughput, got %v", stats.Throughput)+ }+}++func TestTaskRepository_InsertEmpty(t *testing.T) {+ setupTestDB(t)+ ctx := context.Background()++ err := TaskRepository.InsertAsync(ctx, []models.Task{})+ if err != nil {+ t.Fatalf("InsertAsync with empty slice should not error: %v", err)+ }+}diff --git a/backend/app/repositories/testhelper_clickhouse_test.go b/backend/app/repositories/testhelper_clickhouse_test.gonew file mode 100644index 00000000..1b3584eb--- /dev/null+++ b/backend/app/repositories/testhelper_clickhouse_test.go@@ -0,0 +1,112 @@+//go:build pgch++package repositories++import (+ "context"+ "database/sql"+ "fmt"+ "os"+ "testing"++ "github.com/ClickHouse/clickhouse-go/v2"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/chdb"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ _ "github.com/lib/pq"+)++func setupTestDB(t *testing.T) {+ t.Helper()++ chServer := os.Getenv("TEST_CLICKHOUSE_SERVER")+ if chServer == "" {+ t.Skip("TEST_CLICKHOUSE_SERVER not set, skipping ClickHouse tests")+ }++ chDatabase := os.Getenv("TEST_CLICKHOUSE_DATABASE")+ if chDatabase == "" {+ chDatabase = "traceway_test"+ }+ chUsername := os.Getenv("TEST_CLICKHOUSE_USERNAME")+ if chUsername == "" {+ chUsername = "default"+ }+ chPassword := os.Getenv("TEST_CLICKHOUSE_PASSWORD")++ conn, err := clickhouse.Open(&clickhouse.Options{+ Addr: []string{chServer},+ Auth: clickhouse.Auth{+ Database: chDatabase,+ Username: chUsername,+ Password: chPassword,+ },+ Settings: clickhouse.Settings{+ "max_execution_time": 60,+ },+ MaxOpenConns: 5,+ MaxIdleConns: 5,+ })+ if err != nil {+ t.Fatalf("failed to connect to ClickHouse: %v", err)+ }++ if err := conn.Ping(context.Background()); err != nil {+ t.Fatalf("failed to ping ClickHouse: %v", err)+ }++ chdb.Conn = conn++ pgHost := os.Getenv("TEST_POSTGRES_HOST")+ if pgHost == "" {+ pgHost = "localhost"+ }+ pgPort := os.Getenv("TEST_POSTGRES_PORT")+ if pgPort == "" {+ pgPort = "5432"+ }+ pgDatabase := os.Getenv("TEST_POSTGRES_DATABASE")+ if pgDatabase == "" {+ pgDatabase = "traceway_test"+ }+ pgUsername := os.Getenv("TEST_POSTGRES_USERNAME")+ if pgUsername == "" {+ pgUsername = "traceway"+ }+ pgPassword := os.Getenv("TEST_POSTGRES_PASSWORD")+ pgSSLMode := os.Getenv("TEST_POSTGRES_SSLMODE")+ if pgSSLMode == "" {+ pgSSLMode = "disable"+ }++ connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s",+ pgHost, pgPort, pgUsername, pgPassword, pgDatabase, pgSSLMode)++ pgDB, err := sql.Open("postgres", connStr)+ if err != nil {+ t.Fatalf("failed to connect to PostgreSQL: %v", err)+ }++ if err := pgDB.Ping(); err != nil {+ t.Fatalf("failed to ping PostgreSQL: %v", err)+ }++ db.DB = pgDB+ db.Driver = lit.PostgreSQL++ models.Init(db.Driver)++ t.Cleanup(func() {+ ctx := context.Background()+ tables := []string{+ "endpoints", "tasks", "exception_stack_traces",+ "spans", "metric_points", "session_recordings",+ "archived_exceptions", "slow_endpoints", "fired_notifications",+ }+ for _, table := range tables {+ _ = conn.Exec(ctx, fmt.Sprintf("TRUNCATE TABLE IF EXISTS %s", table))+ }+ pgDB.Close()+ })+}diff --git a/backend/app/repositories/testhelper_sqlite_test.go b/backend/app/repositories/testhelper_sqlite_test.gonew file mode 100644index 00000000..ce7c865d--- /dev/null+++ b/backend/app/repositories/testhelper_sqlite_test.go@@ -0,0 +1,207 @@+//go:build !pgch++package repositories++import (+ "database/sql"+ "testing"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/models"+ _ "modernc.org/sqlite"+)++func setupTestDB(t *testing.T) {+ t.Helper()++ sqliteDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("failed to open in-memory sqlite: %v", err)+ }++ if _, err := sqliteDB.Exec("PRAGMA foreign_keys = ON"); err != nil {+ t.Fatalf("failed to enable foreign keys: %v", err)+ }+ if _, err := sqliteDB.Exec("PRAGMA journal_mode = WAL"); err != nil {+ t.Fatalf("failed to set WAL mode: %v", err)+ }++ sqliteDB.SetMaxOpenConns(1)++ db.DB = sqliteDB+ db.Driver = lit.SQLite++ models.Init(db.Driver)++ if err := runTestMigrations(sqliteDB); err != nil {+ t.Fatalf("failed to run migrations: %v", err)+ }++ t.Cleanup(func() {+ sqliteDB.Close()+ })+}++func runTestMigrations(sqliteDB *sql.DB) error {+ telemetryDDL := `+CREATE TABLE IF NOT EXISTS endpoints (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ endpoint TEXT NOT NULL DEFAULT '',+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL,+ status_code INTEGER NOT NULL DEFAULT 0,+ body_size INTEGER NOT NULL DEFAULT 0,+ client_ip TEXT NOT NULL DEFAULT '',+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT ''+);+CREATE INDEX IF NOT EXISTS idx_endpoints_project_recorded ON endpoints(project_id, recorded_at);+CREATE INDEX IF NOT EXISTS idx_endpoints_project_endpoint ON endpoints(project_id, endpoint);++CREATE TABLE IF NOT EXISTS tasks (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ task_name TEXT NOT NULL DEFAULT '',+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL,+ client_ip TEXT NOT NULL DEFAULT '',+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT ''+);+CREATE INDEX IF NOT EXISTS idx_tasks_project_recorded ON tasks(project_id, recorded_at);++CREATE TABLE IF NOT EXISTS exception_stack_traces (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ trace_id TEXT,+ trace_type TEXT NOT NULL DEFAULT 'endpoint',+ exception_hash TEXT NOT NULL DEFAULT '',+ stack_trace TEXT NOT NULL DEFAULT '',+ recorded_at DATETIME NOT NULL,+ attributes TEXT NOT NULL DEFAULT '{}',+ app_version TEXT NOT NULL DEFAULT '',+ server_name TEXT NOT NULL DEFAULT '',+ is_message INTEGER NOT NULL DEFAULT 0+);+CREATE INDEX IF NOT EXISTS idx_exceptions_project_recorded ON exception_stack_traces(project_id, recorded_at);+CREATE INDEX IF NOT EXISTS idx_exceptions_project_hash ON exception_stack_traces(project_id, exception_hash);++CREATE TABLE IF NOT EXISTS spans (+ id TEXT NOT NULL,+ trace_id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ start_time DATETIME NOT NULL,+ duration INTEGER NOT NULL DEFAULT 0,+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_spans_project_trace ON spans(project_id, trace_id);++CREATE TABLE IF NOT EXISTS metric_points (+ project_id TEXT NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ value REAL NOT NULL DEFAULT 0,+ tags TEXT NOT NULL DEFAULT '{}',+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_metric_points_project_name ON metric_points(project_id, name, recorded_at);++CREATE TABLE IF NOT EXISTS session_recordings (+ id TEXT NOT NULL,+ project_id TEXT NOT NULL,+ exception_id TEXT NOT NULL,+ file_path TEXT NOT NULL DEFAULT '',+ recorded_at DATETIME NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_session_recordings_project_exception ON session_recordings(project_id, exception_id);++CREATE TABLE IF NOT EXISTS archived_exceptions (+ project_id TEXT NOT NULL,+ exception_hash TEXT NOT NULL,+ archived_at DATETIME NOT NULL DEFAULT (datetime('now')),+ UNIQUE(project_id, exception_hash)+);++CREATE TABLE IF NOT EXISTS slow_endpoints (+ project_id TEXT NOT NULL,+ endpoint TEXT NOT NULL,+ offset_ms INTEGER NOT NULL DEFAULT 0,+ reason TEXT NOT NULL DEFAULT '',+ UNIQUE(project_id, endpoint)+);++CREATE TABLE IF NOT EXISTS fired_notifications (+ project_id TEXT NOT NULL,+ rule_id INTEGER NOT NULL DEFAULT 0,+ rule_type TEXT NOT NULL DEFAULT '',+ rule_name TEXT NOT NULL DEFAULT '',+ channel_type TEXT NOT NULL DEFAULT '',+ channel_name TEXT NOT NULL DEFAULT '',+ severity TEXT NOT NULL DEFAULT '',+ subject TEXT NOT NULL DEFAULT '',+ body TEXT NOT NULL DEFAULT '',+ status TEXT NOT NULL DEFAULT '',+ error_message TEXT NOT NULL DEFAULT '',+ endpoint TEXT NOT NULL DEFAULT '',+ fired_at DATETIME NOT NULL+);+`++ statements := splitStatements(telemetryDDL)+ for _, stmt := range statements {+ if _, err := sqliteDB.Exec(stmt); err != nil {+ return err+ }+ }+ return nil+}++func splitStatements(sql string) []string {+ var stmts []string+ current := ""+ for _, line := range splitLines(sql) {+ trimmed := trimSpace(line)+ if trimmed == "" {+ continue+ }+ current += line + "\n"+ if len(trimmed) > 0 && trimmed[len(trimmed)-1] == ';' {+ stmts = append(stmts, current)+ current = ""+ }+ }+ if trimSpace(current) != "" {+ stmts = append(stmts, current)+ }+ return stmts+}++func splitLines(s string) []string {+ var lines []string+ start := 0+ for i := 0; i < len(s); i++ {+ if s[i] == '\n' {+ lines = append(lines, s[start:i])+ start = i + 1+ }+ }+ if start < len(s) {+ lines = append(lines, s[start:])+ }+ return lines+}++func trimSpace(s string) string {+ start, end := 0, len(s)+ for start < end && (s[start] == ' ' || s[start] == '\t' || s[start] == '\r' || s[start] == '\n') {+ start+++ }+ for end > start && (s[end-1] == ' ' || s[end-1] == '\t' || s[end-1] == '\r' || s[end-1] == '\n') {+ end--+ }+ return s[start:end]+}diff --git a/backend/cmd/options.go b/backend/cmd/options.goindex f0ef3b18..5d71f627 100644--- a/backend/cmd/options.go+++ b/backend/cmd/options.go@@ -2,7 +2,6 @@ package cmdtype options struct {sqlitePath string- clickhousePath stringport intserverURL stringdisableLogging bool@@ -29,12 +28,6 @@ func WithSQLitePath(path string) Option {}}-func WithClickhousePath(path string) Option {- return func(o *options) {- o.clickhousePath = path- }-}-func WithPort(port int) Option {return func(o *options) {o.port = portdiff --git a/backend/cmd/run.go b/backend/cmd/run.goindex 2848154f..864dbde8 100644--- a/backend/cmd/run.go+++ b/backend/cmd/run.go@@ -45,15 +45,13 @@ func Run(opts ...Option) {port = 8082}cfg = &config.Cfg{- JWTSecret: "traceway-dev-secret-key-min-32-chars!",- DBType: "sqlite",- SQLitePath: o.sqlitePath,- ClickhouseType: "embedded",- ClickhousePath: o.clickhousePath,- StorageType: "local",- StoragePath: "./storage",- APIOnly: "false",- Ports: fmt.Sprintf("%d", port),+ JWTSecret: "traceway-dev-secret-key-min-32-chars!",+ DBType: "sqlite",+ SQLitePath: o.sqlitePath,+ StorageType: "local",+ StoragePath: "./storage",+ APIOnly: "false",+ Ports: fmt.Sprintf("%d", port),}if o.serverURL == "" {o.serverURL = fmt.Sprintf("http://localhost:%d", port)diff --git a/backend/go.mod b/backend/go.modindex 0ea75c89..b0f40506 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -7,32 +7,19 @@ require (github.com/aws/aws-sdk-go-v2/config v1.32.7github.com/aws/aws-sdk-go-v2/credentials v1.19.7github.com/aws/aws-sdk-go-v2/service/s3 v1.96.0- github.com/chdb-io/chdb-go v1.11.0github.com/coreos/go-systemd/v22 v22.6.0github.com/golang-jwt/jwt/v5 v5.3.0github.com/lib/pq v1.10.9+ github.com/tracewayapp/lit/v2 v2.0.2go.tracewayapp.com v1.0.1go.tracewayapp.com/tracewaygin v0.4.3modernc.org/sqlite v1.18.1)require (- github.com/c-bata/go-prompt v0.2.6 // indirect- github.com/ebitengine/purego v0.8.4 // indirectgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 // indirect- github.com/huandu/go-sqlbuilder v1.27.3 // indirect- github.com/huandu/xstrings v1.4.0 // indirectgithub.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect- github.com/mattn/go-colorable v0.1.13 // indirect- github.com/mattn/go-runewidth v0.0.15 // indirect- github.com/mattn/go-tty v0.0.5 // indirect- github.com/olekukonko/tablewriter v0.0.5 // indirect- github.com/parquet-go/parquet-go v0.23.0 // indirect- github.com/pkg/term v1.2.0-beta.2 // indirectgithub.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect- github.com/rivo/uniseg v0.4.7 // indirect- github.com/segmentio/encoding v0.4.0 // indirect- github.com/tracewayapp/lit/v2 v2.0.2 // indirectgoogle.golang.org/genproto/googleapis/api v0.0.0-20250825161204-c5933d9347a5 // indirectgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20250825161204-c5933d9347a5 // indirectgoogle.golang.org/grpc v1.75.1 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 742d5506..cdbe20f0 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -54,12 +54,8 @@ github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQgithub.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=-github.com/c-bata/go-prompt v0.2.6 h1:POP+nrHE+DfLYx370bedwNhsqmpCUynWPxuHi0C5vZI=-github.com/c-bata/go-prompt v0.2.6/go.mod h1:/LMAke8wD2FsNu9EXNdHxNLbd9MedkPnCdfpU9wwHfY=github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=-github.com/chdb-io/chdb-go v1.11.0 h1:G6+Oy1onzNL3bSxncGfIdiB6beTpxwKztjfai7qLckE=-github.com/chdb-io/chdb-go v1.11.0/go.mod h1:RkT+xLXhdBKtUtJJPwhQQR4p6qiXHisJNS712QldDg8=github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58 h1:F1EaeKL/ta07PY/k9Os/UFtwERei2/XzGemhpGnBKNg=github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=@@ -87,8 +83,6 @@ github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDgithub.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=-github.com/ebitengine/purego v0.8.4 h1:CF7LEKg5FFOsASUj0+QwaXf8Ht6TlFxg09+S9wz0omw=-github.com/ebitengine/purego v0.8.4/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=@@ -139,11 +133,6 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2 h1:8Tjv8EJ+pM1xP8mK6egEbD1OgnVTyacbefKhmbLhIhU=github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.2/go.mod h1:pkJQ2tZHJ0aFOVEEot6oZmaVEZcRme73eIFmhiVuRWs=-github.com/huandu/go-assert v1.1.6/go.mod h1:JuIfbmYG9ykwvuxoJ3V8TB5QP+3+ajIA54Y44TmkMxs=-github.com/huandu/go-sqlbuilder v1.27.3 h1:cNVF9vQP4i7rTk6XXJIEeMbGkZbxfjcITeJzobJK44k=-github.com/huandu/go-sqlbuilder v1.27.3/go.mod h1:mS0GAtrtW+XL6nM2/gXHRJax2RwSW1TraavWDFAc1JA=-github.com/huandu/xstrings v1.4.0 h1:D17IlohoQq4UcpqD7fDk80P7l+lwAmlFaBHgOipl2FU=-github.com/huandu/xstrings v1.4.0/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=@@ -168,26 +157,12 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=-github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=-github.com/mattn/go-colorable v0.1.7/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=-github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA=-github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=-github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=-github.com/mattn/go-isatty v0.0.10/go.mod h1:qgIWMr58cqv1PHHyhnkY9lrL7etaEgOFcMEpPG5Rm84=github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=-github.com/mattn/go-runewidth v0.0.6/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=-github.com/mattn/go-runewidth v0.0.7/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=-github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=-github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=-github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=-github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvrWyR0=-github.com/mattn/go-tty v0.0.5 h1:s09uXI7yDbXzzTTfw3zonKFzwGkyYlgU3OMjqA0ddz4=-github.com/mattn/go-tty v0.0.5/go.mod h1:u5GGXBtZU6RQoKV8gY5W6UhMudbR5vXnUe7j3pxse28=github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=@@ -199,14 +174,10 @@ github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYgithub.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc=github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=-github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=-github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=-github.com/parquet-go/parquet-go v0.23.0 h1:dyEU5oiHCtbASyItMCD2tXtT2nPmoPbKpqf0+nnGrmk=-github.com/parquet-go/parquet-go v0.23.0/go.mod h1:MnwbUcFHU6uBYMymKAlPPAw9yh3kE1wWl6Gl1uLdkNk=github.com/paulmach/orb v0.12.0 h1:z+zOwjmG3MyEEqzv92UN49Lg1JFYx0L9GpGKNVDKk1s=github.com/paulmach/orb v0.12.0/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU=github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY=@@ -216,8 +187,6 @@ github.com/pierrec/lz4/v4 v4.1.22 h1:cKFw6uJDK+/gfw5BcDL0JL5aBsAFdsIT18eRtLj7VIUgithub.com/pierrec/lz4/v4 v4.1.22/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=-github.com/pkg/term v1.2.0-beta.2 h1:L3y/h2jkuBVFdWiJvNfYfKmzcCnILw7mJWm2JQuMppw=-github.com/pkg/term v1.2.0-beta.2/go.mod h1:E25nymQcrSllhX42Ok8MRm1+hyBdHY0dCeiKZ9jpNGw=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=@@ -227,15 +196,10 @@ github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBgithub.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk=github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=-github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=-github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=-github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=-github.com/segmentio/encoding v0.4.0 h1:MEBYvRqiUB2nfR2criEXWqwdY6HJOUrCn5hboVOVmy8=-github.com/segmentio/encoding v0.4.0/go.mod h1:/d03Cd8PoaDeceuhUUUQWjU0KhWjrmYrWPgtJHYZSnI=github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=@@ -314,14 +278,8 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJgolang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=-golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/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-20191008105621-543471e840be/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200909081042-eff7692f9009/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=-golang.org/x/sys v0.0.0-20200918174421-af09f7315aff/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=diff --git a/backend/traceway.go b/backend/traceway.goindex cc2e4881..e0ac3fd0 100644--- a/backend/traceway.go+++ b/backend/traceway.go@@ -1,11 +1,7 @@// Package tracewaybackend provides an embeddable Traceway backend that can be-// run inside your own Go application.+// run inside your own Go application. Uses SQLite for all storage — no external+// databases required.//-// !! WARNING: Linux and macOS only.-// !! The embedded backend uses chdb (embedded ClickHouse), which does NOT-// !! support Windows. libchdb must be installed on the system before use:-// !!-// !! curl -sL https://lib.chdb.io | bashpackage tracewaybackendimport "github.com/tracewayapp/traceway/backend/cmd"@@ -17,7 +13,6 @@ var (WithPort = cmd.WithPortWithServerURL = cmd.WithServerURLWithSQLitePath = cmd.WithSQLitePath- WithClickhousePath = cmd.WithClickhousePathWithDefaultUser = cmd.WithDefaultUserWithDefaultProject = cmd.WithDefaultProjectDisableLogging = cmd.DisableLoggingdiff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.jsonindex 96a86f5c..92c4d183 100644--- a/docs/pages/learn/_meta.json+++ b/docs/pages/learn/_meta.json@@ -7,5 +7,7 @@"spans": "Spans","metrics": "Metrics","alerts": "Alerts",- "embedded-mode": "Embedded Mode"+ "embedded-mode": "Embedded Mode",+ "build-tags": "Build Tags",+ "contributing": "Contributing"}diff --git a/docs/pages/learn/build-tags.mdx b/docs/pages/learn/build-tags.mdxnew file mode 100644index 00000000..11006bd5--- /dev/null+++ b/docs/pages/learn/build-tags.mdx@@ -0,0 +1,57 @@+# Build Tags++The Traceway backend uses Go build tags to switch between storage backends and to embed the frontend.++## Tags++| Tag | Purpose |+|-----|---------|+| *(none)* | **SQLite** storage — embedded mode, zero external dependencies. This is the default. |+| `pgch` | **ClickHouse + PostgreSQL** storage — standalone server mode. |+| `localdist` | Embeds the pre-built frontend static files into the Go binary. Used in Docker builds. |++## Building++### Embedded mode (SQLite)++No tags needed — a plain `go build` gives you the embedded SQLite backend:++```bash+cd backend && go build ./...+```++This is what library consumers get when they `go get github.com/tracewayapp/traceway/backend` and call `tracewaybackend.Run()`.++### Standalone server (ClickHouse + PostgreSQL)++```bash+cd backend && go build -tags pgch ./...+```++Requires `CLICKHOUSE_SERVER`, `POSTGRES_HOST`, and the other environment variables to be configured.++### Docker image++The Dockerfiles combine both `localdist` (embedded frontend) and `pgch` (CH+PG storage):++```bash+go build -tags "localdist,pgch" ./...+```++You don't need `localdist` for local development — run the frontend dev server separately with `cd frontend && npm run dev`.++## Running Tests++### SQLite tests (default)++```bash+cd backend && go test -v -count=1 ./app/repositories/+```++### ClickHouse tests++```bash+cd backend && TEST_CLICKHOUSE_SERVER=localhost:9000 go test -tags pgch -v ./app/repositories/+```++Without `TEST_CLICKHOUSE_SERVER` set, the `pgch` tests skip cleanly.diff --git a/docs/pages/learn/contributing.mdx b/docs/pages/learn/contributing.mdxnew file mode 100644index 00000000..5811c8ab--- /dev/null+++ b/docs/pages/learn/contributing.mdx@@ -0,0 +1,249 @@+# Contributing++import { Callout } from "nextra/components";++This guide covers how to set up the Traceway development environment, run tests, and submit changes.++## Project Structure++| Directory | Description |+|-----------|-------------|+| `backend/` | Go/Gin API server — handles telemetry ingestion, REST API, and database access |+| `frontend/` | SvelteKit 2 dashboard — the web UI users interact with |+| `docs/` | Nextra documentation site (what you're reading now) |+| `examples/` | Working example apps demonstrating embedded mode |+| `scripts/` | Helper scripts for testing and CI |++## Tech Stack++| Component | Technology |+|-----------|------------|+| Backend | Go 1.25, Gin, ClickHouse, PostgreSQL |+| Frontend | SvelteKit 2, Svelte 5, Tailwind CSS v4, shadcn-svelte |+| Embedded mode | SQLite (default build, no external dependencies) |+| Docs | Nextra (Next.js) |++## Prerequisites++- **Go** 1.25 or later+- **Node.js** 18+ and npm+- **Docker** (for running the full pgch test suite)+- **ClickHouse** and **PostgreSQL** (only if running the standalone server locally — not needed for embedded/SQLite mode)++## Build Tags++Traceway uses Go build tags to switch between storage backends:++| Tag | Purpose |+|-----|---------|+| *(none)* | **SQLite** — embedded mode, zero dependencies. This is the default. |+| `pgch` | **ClickHouse + PostgreSQL** — standalone server mode. |+| `localdist` | Embeds the pre-built frontend into the Go binary. Used in Docker builds. |++See the [Build Tags](/learn/build-tags) page for more details.++## Setting Up for Development++### Backend (embedded/SQLite mode)++The fastest way to get going — no databases to install:++```bash+cd backend+go build ./...+go test ./...+```++This builds and tests the SQLite backend, which is the default.++### Backend (standalone server mode)++If you're working on ClickHouse or PostgreSQL-specific code, see the [Local Setup](/server/local-setup) guide for database installation and environment variables. Then:++```bash+cd backend+go build -tags pgch ./...+go run -tags pgch ./cmd/traceway+```++### Frontend++```bash+cd frontend+npm install+npm run dev+```++The dev server runs on port **5173** and proxies API requests to the backend on port **8082**.++### Docs++```bash+cd docs+npm install+npm run dev+```++## Running Tests++### SQLite tests (default)++These run without any external dependencies:++```bash+cd backend+go test -v -count=1 ./app/repositories/+```++### ClickHouse + PostgreSQL tests (via Docker)++The full pgch test suite runs ClickHouse and PostgreSQL inside a Docker container. This is the most reliable way to verify ClickHouse-specific code:++```bash+./scripts/test-backend-pgch.sh+```++This builds a Docker image with both databases, applies all migrations, and runs the test suite with `-tags pgch`. All tests should pass.++<Callout type="info">+ Without Docker, you can run pgch tests against local databases by setting environment variables:++ ```bash+ cd backend+ TEST_CLICKHOUSE_SERVER=localhost:9000 \+ TEST_CLICKHOUSE_DATABASE=traceway_test \+ TEST_POSTGRES_HOST=localhost \+ TEST_POSTGRES_DATABASE=traceway_test \+ TEST_POSTGRES_USERNAME=traceway \+ TEST_POSTGRES_PASSWORD=traceway \+ go test -tags pgch -v -count=1 ./app/repositories/+ ```++ Without `TEST_CLICKHOUSE_SERVER` set, the pgch tests skip cleanly.+</Callout>++### Frontend checks++```bash+cd frontend+npm run check # TypeScript checking+npm run build # Production build+```++## Architecture Overview++### Data Flow++```+Application → [SDK] → POST /api/report → Backend → ClickHouse/SQLite+ ↓+Dashboard ← [SvelteKit Frontend] ← JSON API ← Gin Controllers+```++The SDK sends telemetry (traces, exceptions, metrics) as gzipped JSON to the backend. The backend stores it in ClickHouse (standalone) or SQLite (embedded), and the frontend reads it via REST API.++### Authentication++Two separate auth systems:++- **Client auth**: Project bearer tokens — used by the SDK to send telemetry (`Authorization: Bearer <project_token>`)+- **App auth**: JWT tokens — used by the dashboard for user sessions (`Authorization: Bearer <jwt_token>`)++### Database Split++- **PostgreSQL** (or SQLite in embedded mode): Relational data that gets updated — users, organizations, projects, invitations, notification rules, widget config+- **ClickHouse** (or SQLite in embedded mode): High-volume append-only telemetry — traces, exceptions, metrics, spans, tasks, session recordings++### Backend Patterns++**Repositories** are singletons (`var FooRepository = fooRepository{}`). Each repository has two implementations in separate files — one for ClickHouse/PostgreSQL (`//go:build pgch`) and one for SQLite (`//go:build !pgch`).++**Controllers** use the Gin framework. PostgreSQL operations go through `middleware.Transactional` for automatic commit/rollback.++**Migrations** live in `backend/app/migrations/ch/` (ClickHouse) and `backend/app/migrations/pg/` (PostgreSQL). Each ClickHouse migration file must contain exactly one SQL statement. Migrations run automatically on startup.++### Frontend Patterns++**State** is managed with Svelte 5 runes (`$state`, `$derived`, `$effect`) in singleton classes exported from `src/lib/state/`.++**API calls** go through `src/lib/api.ts` which auto-attaches auth tokens and the current project ID.++**Components** use shadcn-svelte (in `src/lib/components/ui/`) with custom Traceway wrappers (in `src/lib/components/traceway/`).++## Forking and Opening PRs++### Fork and clone++1. Fork the repository on GitHub+2. Clone your fork:++```bash+git clone https://github.com/YOUR_USERNAME/traceway.git+cd traceway+```++3. Add the upstream remote:++```bash+git remote add upstream https://github.com/tracewayapp/traceway.git+```++### Create a branch++Always branch from `main`:++```bash+git fetch upstream+git checkout -b your-feature upstream/main+```++### Before submitting++1. **Build both backends** to make sure nothing is broken:++```bash+cd backend+go build ./... # SQLite (default)+go build -tags pgch ./... # ClickHouse + PostgreSQL+```++2. **Run the SQLite tests**:++```bash+go test -v -count=1 ./app/repositories/+```++3. **Run the pgch Docker tests** if you changed any repository code:++```bash+./scripts/test-backend-pgch.sh+```++4. **Check the frontend** if you changed any frontend code:++```bash+cd frontend+npm run check+npm run build+```++### Open a pull request++Push your branch and open a PR against `main`:++```bash+git push origin your-feature+```++Then create a pull request on GitHub. Include:++- A short description of what the change does and why+- Steps to test, if applicable+- Screenshots for UI changes++### Keeping your fork up to date++```bash+git fetch upstream+git rebase upstream/main+```diff --git a/docs/pages/learn/embedded-mode.mdx b/docs/pages/learn/embedded-mode.mdxindex 0f7ea38e..417f663e 100644--- a/docs/pages/learn/embedded-mode.mdx+++ b/docs/pages/learn/embedded-mode.mdx@@ -1,15 +1,8 @@# Embedded Mode-import { Callout } from "nextra/components";+import { Callout, Steps } from "nextra/components";-<Callout type="warning">- **Linux and macOS only.** Embedded mode uses- [chdb](https://github.com/chdb-io/chdb) (embedded ClickHouse), which does- **not** support Windows. If you're on Windows, use the [Docker- Compose](/server/docker-compose) deployment instead.-</Callout>--Embedded mode runs a full Traceway server inside your Go process — using **SQLite** instead of PostgreSQL and **embedded ClickHouse** (via [chdb](https://github.com/chdb-io/chdb)) instead of an external server. No Docker, no infrastructure — just one `tracewaybackend.Run()` call and your app has local observability.+Embedded mode runs a full Traceway server inside your Go process — using **SQLite** for all storage (relational data and telemetry). No Docker, no infrastructure — just one `tracewaybackend.Run()` call and your app has local observability.This is intended for **local development only**. For production, use the [Docker Compose](/server/docker-compose) or [minimal](/server/minimal) deployment.@@ -20,212 +13,108 @@ This is intended for **local development only**. For production, use the [Dockeryou can run in one command.</Callout>-## Prerequisites--Install `libchdb` (the embedded ClickHouse C library). Supports macOS and Linux:--```bash-curl -sL https://lib.chdb.io | bash-```--Embedded ClickHouse is included by default in all builds. To exclude it (e.g., for production Docker images using an external ClickHouse), build with the `nochdb` tag:--```bash-go build -tags nochdb ./...-```-## Quick Start-Add the Traceway server module to your project:+<Steps>++### Install the Traceway backend module```bashgo get github.com/tracewayapp/traceway/backend```-Then call `tracewaybackend.Run()` somewhere in your application startup. A common pattern is guarding it behind an environment check so it only runs in development:+### Start Traceway inside your app++Call `tracewaybackend.Run()` in a goroutine during startup. It boots an in-memory SQLite server and seeds a default user and project:```gopackage mainimport (- "os"-"github.com/gin-gonic/gin"tracewaybackend "github.com/tracewayapp/traceway/backend"- tracewaygin "go.tracewayapp.com/tracewaygin")func main() {- if os.Getenv("ENV") != "production" {- go tracewaybackend.Run(- tracewaybackend.WithPort(8085),- tracewaybackend.WithDefaultUser("[email protected]", "admin"),- tracewaybackend.WithDefaultProject("Backend", "go", "backend-dev-token"),- tracewaybackend.WithDefaultProject("Frontend", "sveltekit", "frontend-dev-token"),- )- }+ go tracewaybackend.Run(+ tracewaybackend.WithPort(8082),+ tracewaybackend.WithDefaultUser("[email protected]", "admin"),+ tracewaybackend.WithDefaultProject("My App", "go", "dev-token"),+ )router := gin.Default()- router.Use(tracewaygin.New(- "backend-dev-token@http://localhost:8085/api/report",- tracewaygin.WithOnErrorRecording(- tracewaygin.RecordingUrl | tracewaygin.RecordingQuery,- ),- ))-- router.GET("/ping", func(c *gin.Context) {- c.String(200, "pong")- })- router.Run(":3000")+ // ... your routes+ router.Run(":8080")}```-`WithDefaultProject` can be called multiple times to create separate projects — one for your Go backend, another for a frontend or any other service. Each project gets its own token, keeping telemetry organized in the dashboard.+### Point OpenTelemetry to your local Traceway-Run the application:+Install the OTel dependencies:```bash-go run .-```--The Traceway dashboard is available at `http://localhost:8085`. Log in with the credentials from `WithDefaultUser`.--## Configuration Options--All options are passed to `tracewaybackend.Run()`. When any options are provided, embedded mode is activated automatically (SQLite + embedded ClickHouse).--| Option | Description | Default |-| -------------------------------------------- | -------------------------------------------------------------------------- | ------------------------- |-| `WithPort(port)` | HTTP port for the Traceway server | `8082` |-| `WithServerURL(url)` | Base URL override (used in connection string output) | `http://localhost:{port}` |-| `WithSQLitePath(path)` | SQLite database file path | `:memory:` (in-memory) |-| `WithClickhousePath(path)` | ClickHouse data directory | `""` (in-memory) |-| `WithDefaultUser(email, password)` | Create a default admin user on startup | None |-| `WithDefaultProject(name, framework, token)` | Create a default project with a fixed token (can be called multiple times) | None |--## Data Persistence--By default, both databases are **in-memory** — all data is lost when your application restarts. This is fine for quick debugging sessions, but if you want data to survive restarts, set file paths:--```go-tracewaybackend.Run(- tracewaybackend.WithSQLitePath("./traceway.db"),- tracewaybackend.WithClickhousePath("./chdb-data"),- tracewaybackend.WithDefaultUser("[email protected]", "admin"),- tracewaybackend.WithDefaultProject("Backend", "go", "backend-dev-token"),- tracewaybackend.WithDefaultProject("Frontend", "sveltekit", "frontend-dev-token"),-)+go get go.opentelemetry.io/otel \+ go.opentelemetry.io/otel/sdk \+ go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp \+ go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin```-- `WithSQLitePath` stores users, projects, and organizations in a local SQLite file.-- `WithClickhousePath` stores traces, issues, and metrics in a local directory.--Seeding is idempotent — if the user from `WithDefaultUser` already exists, it's skipped.--## Connecting Your App--## Open Telemetry Full Example--The example below shows a complete Go application with Traceway running inside the same process. The embedded server starts in a goroutine, OpenTelemetry sends traces to it over localhost, and you get a full dashboard — all from a single `go run .`.--> [View the full example on GitHub →](https://github.com/tracewayapp/traceway/tree/main/examples/embedded-backend-otel)+Configure the OTLP exporter to send traces to the embedded server, and add the OTel middleware to your router:```gopackage mainimport ("context"- "errors""fmt"- "math/rand/v2"- "net/http""time""github.com/gin-gonic/gin"tracewaybackend "github.com/tracewayapp/traceway/backend""go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin""go.opentelemetry.io/otel"- "go.opentelemetry.io/otel/codes""go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp""go.opentelemetry.io/otel/sdk/resource"sdktrace "go.opentelemetry.io/otel/sdk/trace"semconv "go.opentelemetry.io/otel/semconv/v1.26.0"- "go.opentelemetry.io/otel/trace")-const (- appPort = 8080- tracewayToken = "backend-dev-token"- serviceName = "embedded-example"-)+const tracewayToken = "dev-token"func main() {- // Start the embedded Traceway server in the background.- // It runs on port 8082 and seeds a default admin user and project.go tracewaybackend.Run(tracewaybackend.WithPort(8082),tracewaybackend.WithDefaultUser("[email protected]", "admin"),- tracewaybackend.WithDefaultProject("Example App", "go", tracewayToken),- tracewaybackend.DisableLogging(),+ tracewaybackend.WithDefaultProject("My App", "go", tracewayToken),)- // Set up OpenTelemetry to export traces to the embedded server.shutdown := initTracer()defer shutdown()router := gin.Default()- router.Use(otelgin.Middleware(serviceName))-- router.GET("/hello/:name", func(c *gin.Context) {- name := c.Param("name")- tracer := otel.Tracer(serviceName)-- // Create a child span to simulate a database lookup.- _, span := tracer.Start(c.Request.Context(), "db.lookup")- time.Sleep(time.Duration(20+rand.IntN(80)) * time.Millisecond)- span.End()-- // Passing "error" as the name triggers an error for testing.- if name == "error" {- err := errors.New("something went wrong")- rootSpan := trace.SpanFromContext(c.Request.Context())- rootSpan.RecordError(err, trace.WithStackTrace(true))- rootSpan.SetStatus(codes.Error, err.Error())- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})- return- }-- c.JSON(http.StatusOK, gin.H{"message": "Hello, " + name + "!"})- })+ router.Use(otelgin.Middleware("my-app"))- router.Run(fmt.Sprintf(":%d", appPort))+ router.GET("/ping", func(c *gin.Context) {+ c.String(200, "pong")+ })+ router.Run(":8080")}func initTracer() func() {- exporter, err := otlptracehttp.New(+ exporter, _ := otlptracehttp.New(context.Background(),otlptracehttp.WithEndpointURL("http://localhost:8082/api/otel/v1/traces"),otlptracehttp.WithHeaders(map[string]string{"Authorization": "Bearer " + tracewayToken,}),)- if err != nil {- panic(fmt.Sprintf("failed to create OTLP exporter: %v", err))- }-- res, err := resource.New(- context.Background(),- resource.WithAttributes(- semconv.ServiceName(serviceName),- ),- )- if err != nil {- panic(fmt.Sprintf("failed to create resource: %v", err))- }tp := sdktrace.NewTracerProvider(sdktrace.WithBatcher(exporter),- sdktrace.WithResource(res),+ sdktrace.WithResource(resource.NewWithAttributes(+ semconv.SchemaURL,+ semconv.ServiceName("my-app"),+ )),)otel.SetTracerProvider(tp)@@ -237,11 +126,75 @@ func initTracer() func() {}```-Run it:+The key parts:+- **Exporter URL** points to `http://localhost:8082/api/otel/v1/traces` — the embedded server's OTLP endpoint+- **Authorization header** uses the same token from `WithDefaultProject`-```bash-curl -sL https://lib.chdb.io | bash # one-time: install embedded ClickHouse-go run .+### Open the dashboard++Run your app, then open **[http://localhost:8082](http://localhost:8082)** in your browser.++Log in with the credentials from `WithDefaultUser` (`[email protected]` / `admin`).++Hit your app at `http://localhost:8080/ping` a few times — traces will appear in the Traceway dashboard within a few seconds.++</Steps>++## Configuration Options++All options are passed to `tracewaybackend.Run()`. When any options are provided, embedded mode is activated automatically (pure SQLite).++| Option | Description | Default |+| -------------------------------------------- | -------------------------------------------------------------------------- | ------------------------- |+| `WithPort(port)` | HTTP port for the Traceway server | `8082` |+| `WithServerURL(url)` | Base URL override (used in connection string output) | `http://localhost:{port}` |+| `WithSQLitePath(path)` | SQLite database file path | `:memory:` (in-memory) |+| `WithDefaultUser(email, password)` | Create a default admin user on startup | None |+| `WithDefaultProject(name, framework, token)` | Create a default project with a fixed token (can be called multiple times) | None |++## Multiple Projects++`WithDefaultProject` can be called multiple times to create separate projects — one for your Go backend, another for a frontend or any other service. Each project gets its own token, keeping telemetry organized in the dashboard:++```go+go tracewaybackend.Run(+ tracewaybackend.WithPort(8082),+ tracewaybackend.WithDefaultUser("[email protected]", "admin"),+ tracewaybackend.WithDefaultProject("Backend", "go", "backend-token"),+ tracewaybackend.WithDefaultProject("Frontend", "sveltekit", "frontend-token"),+)+```++## Data Persistence++By default, the database is **in-memory** — all data is lost when your application restarts. This is fine for quick debugging sessions, but if you want data to survive restarts, set a file path:++```go+tracewaybackend.Run(+ tracewaybackend.WithSQLitePath("./traceway.db"),+ tracewaybackend.WithDefaultUser("[email protected]", "admin"),+ tracewaybackend.WithDefaultProject("My App", "go", "dev-token"),+)+```++`WithSQLitePath` stores everything — users, projects, traces, issues, and metrics — in a single SQLite file.++Seeding is idempotent — if the user from `WithDefaultUser` already exists, it's skipped.++## Development-Only Guard++A common pattern is guarding embedded mode behind an environment check so it only runs in development:++```go+if os.Getenv("ENV") != "production" {+ go tracewaybackend.Run(+ tracewaybackend.WithPort(8082),+ tracewaybackend.WithDefaultUser("[email protected]", "admin"),+ tracewaybackend.WithDefaultProject("My App", "go", "dev-token"),+ )+}```-Then open `http://localhost:8082`, log in with **[email protected] / admin**, and hit `http://localhost:8080/hello/world` a few times to see traces appear in the dashboard.+## Full Example++For a complete working example with error recording and child spans, see the [embedded-backend-otel example on GitHub](https://github.com/tracewayapp/traceway/tree/main/examples/embedded-backend-otel).diff --git a/examples/embedded-backend-go-client/main.go b/examples/embedded-backend-go-client/main.goindex c6af6a12..e9fe9c02 100644--- a/examples/embedded-backend-go-client/main.go+++ b/examples/embedded-backend-go-client/main.go@@ -18,11 +18,6 @@ const (tracewayToken = "backend-dev-token")-// !! WARNING: The embedded backend ONLY works on Linux and macOS.-// !! Windows is NOT supported due to embedded ClickHouse (chdb) limitations.-// !!-// !! ClickHouse MUST be installed on the system:-// !! curl -sL https://lib.chdb.io | bashfunc main() {// 1: initialize traceway backendgo tracewaybackend.Run(diff --git a/examples/embedded-backend-go-client/readme.md b/examples/embedded-backend-go-client/readme.mdindex fde00539..2e07bc21 100644--- a/examples/embedded-backend-go-client/readme.md+++ b/examples/embedded-backend-go-client/readme.md@@ -1,9 +1,6 @@# Embedded Backend Example (Go Client)-> **WARNING: Linux and macOS only.**-> The embedded backend uses [chdb](https://github.com/chdb-io/chdb) (embedded ClickHouse), which does **not** support Windows.--A single-file Go example that runs the Traceway backend and a Gin app instrumented with the Traceway Go client SDK in one process. No external databases required — everything is embedded (SQLite + embedded ClickHouse).+A single-file Go example that runs the Traceway backend and a Gin app instrumented with the Traceway Go client SDK in one process. No external databases required — everything runs on SQLite.## What it does@@ -11,18 +8,11 @@ A single-file Go example that runs the Traceway backend and a Gin app instrument2. Configures the Traceway Gin middleware to send traces and exceptions to the backend3. Runs a Gin server on `:8080` with a single `/hello/:name` endpoint that optionally records an error-## Prerequisites--Install `libchdb` (the embedded ClickHouse C library). Supports macOS and Linux:--```bash-curl -sL https://lib.chdb.io | bash-```-## Running```bash-go run .+go build .+./embedded-backend-go-client```Then try:diff --git a/examples/embedded-backend-otel/main.go b/examples/embedded-backend-otel/main.goindex 0e51c197..6fa78a0a 100644--- a/examples/embedded-backend-otel/main.go+++ b/examples/embedded-backend-otel/main.go@@ -26,11 +26,6 @@ const (serviceName = "embedded-example")-// !! WARNING: The embedded backend ONLY works on Linux and macOS.-// !! Windows is NOT supported due to embedded ClickHouse (chdb) limitations.-// !!-// !! ClickHouse MUST be installed on the system:-// !! curl -sL https://lib.chdb.io | bashfunc main() {// 1: initialize traceway backendgo tracewaybackend.Run(diff --git a/examples/embedded-backend-otel/readme.md b/examples/embedded-backend-otel/readme.mdindex 32d7b558..794b8b1a 100644--- a/examples/embedded-backend-otel/readme.md+++ b/examples/embedded-backend-otel/readme.md@@ -1,9 +1,6 @@# Embedded Backend Example-> **WARNING: Linux and macOS only.**-> The embedded backend uses [chdb](https://github.com/chdb-io/chdb) (embedded ClickHouse), which does **not** support Windows.--A single-file Go example that runs the Traceway backend and an OTel-instrumented Gin app in one process. No external databases required — everything is embedded (SQLite + embedded ClickHouse).+A single-file Go example that runs the Traceway backend and an OTel-instrumented Gin app in one process. No external databases required — everything runs on SQLite.## What it does@@ -11,18 +8,11 @@ A single-file Go example that runs the Traceway backend and an OTel-instrumented2. Configures an OTLP HTTP trace exporter that sends spans to the backend3. Runs a Gin server on `:8080` with a single `/hello/:name` endpoint that creates a child span and optionally records an error-## Prerequisites--Install `libchdb` (the embedded ClickHouse C library). Supports macOS and Linux:--```bash-curl -sL https://lib.chdb.io | bash-```-## Running```bash-go run .+go build .+./embedded-backend-otel```Then try:diff --git a/scripts/test-backend-pgch.sh b/scripts/test-backend-pgch.shnew file mode 100755index 00000000..b6123884--- /dev/null+++ b/scripts/test-backend-pgch.sh@@ -0,0 +1,23 @@+#!/usr/bin/env bash+set -euo pipefail++SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"+REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"+IMAGE_NAME="traceway-test-pgch"++echo "Building test image..."+docker build -f "$REPO_ROOT/Dockerfile.test-pgch" -t "$IMAGE_NAME" "$REPO_ROOT"++echo ""+echo "Running pgch tests..."+docker run --rm --privileged "$IMAGE_NAME"+EXIT_CODE=$?++if [ $EXIT_CODE -eq 0 ]; then+ echo ""+ echo "All pgch tests passed."+else+ echo ""+ echo "pgch tests FAILED (exit code $EXIT_CODE)."+ exit $EXIT_CODE+fidiff --git a/scripts/test-pgch-entrypoint.sh b/scripts/test-pgch-entrypoint.shnew file mode 100755index 00000000..fc7220a4--- /dev/null+++ b/scripts/test-pgch-entrypoint.sh@@ -0,0 +1,64 @@+#!/usr/bin/env bash+set -euo pipefail++# --------------------------------------------------------------------------+# Start PostgreSQL+# --------------------------------------------------------------------------+pg_ctlcluster 15 main start || pg_ctlcluster 16 main start || pg_ctlcluster 17 main start++# Wait for PostgreSQL to be ready+for i in $(seq 1 30); do+ if su - postgres -c "pg_isready" >/dev/null 2>&1; then break; fi+ sleep 0.5+done++# Create test database and user+su - postgres -c "psql -c \"CREATE USER traceway WITH PASSWORD 'traceway';\"" 2>/dev/null || true+su - postgres -c "psql -c \"CREATE DATABASE traceway_test OWNER traceway;\"" 2>/dev/null || true++# --------------------------------------------------------------------------+# Start ClickHouse+# --------------------------------------------------------------------------+sudo -u clickhouse clickhouse-server --config-file=/etc/clickhouse-server/config.xml --daemon++# Wait for ClickHouse to be ready+for i in $(seq 1 30); do+ if clickhouse-client --query "SELECT 1" >/dev/null 2>&1; then break; fi+ sleep 0.5+done++# Create test database+clickhouse-client --query "CREATE DATABASE IF NOT EXISTS traceway_test"++# --------------------------------------------------------------------------+# Apply ClickHouse migrations+# --------------------------------------------------------------------------+echo "Applying ClickHouse migrations..."+for f in $(ls /app/backend/app/migrations/ch/*.up.sql | sort); do+ echo " $(basename "$f")"+ clickhouse-client --database traceway_test --multiquery < "$f" || true+done++# --------------------------------------------------------------------------+# Apply PostgreSQL migrations+# --------------------------------------------------------------------------+echo "Applying PostgreSQL migrations..."+for f in $(ls /app/backend/app/migrations/pg/*.up.sql | sort); do+ echo " $(basename "$f")"+ PGPASSWORD=traceway psql -h localhost -U traceway -d traceway_test -f "$f" 2>/dev/null || true+done++# --------------------------------------------------------------------------+# Run tests+# --------------------------------------------------------------------------+echo ""+echo "Running pgch tests..."+cd /app/backend++TEST_CLICKHOUSE_SERVER=localhost:9000 \+TEST_CLICKHOUSE_DATABASE=traceway_test \+TEST_POSTGRES_HOST=localhost \+TEST_POSTGRES_DATABASE=traceway_test \+TEST_POSTGRES_USERNAME=traceway \+TEST_POSTGRES_PASSWORD=traceway \+go test -tags pgch -v -count=1 ./app/repositories/