Skip to content

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

Added retention for disk hosted sessions and sqlite hosting

ddux5c71c4c70b61
diff --git a/backend/app/config/config.go b/backend/app/config/config.go
index 1cf0836a..049d3e45 100644
--- a/backend/app/config/config.go
+++ b/backend/app/config/config.go
@@ -28,6 +28,9 @@ type Cfg struct {
S3SecretKey string
S3Endpoint string
+ SQLiteRetentionDays string
+ SessionRecordingRetentionDays string
+
SMTPEnabled string
SMTPHost string
SMTPPort string
@@ -80,6 +83,9 @@ func LoadFromEnv() *Cfg {
S3SecretKey: os.Getenv("S3_SECRET_KEY"),
S3Endpoint: os.Getenv("S3_ENDPOINT"),
+ SQLiteRetentionDays: os.Getenv("SQLITE_RETENTION_DAYS"),
+ SessionRecordingRetentionDays: os.Getenv("SESSION_RECORDING_RETENTION_DAYS"),
+
SMTPEnabled: os.Getenv("SMTP_ENABLED"),
SMTPHost: os.Getenv("SMTP_HOST"),
SMTPPort: os.Getenv("SMTP_PORT"),
diff --git a/backend/app/retention/recordings.go b/backend/app/retention/recordings.go
new file mode 100644
index 00000000..62ff92a9
--- /dev/null
+++ b/backend/app/retention/recordings.go
@@ -0,0 +1,131 @@
+package retention
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+ traceway "go.tracewayapp.com"
+)
+
+const recordingsSubdir = "recordings"
+
+func startRecordingDiskCleanup(ctx context.Context, days int) {
+ if days == 0 {
+ config.Logln("Session recording disk cleanup disabled (SESSION_RECORDING_RETENTION_DAYS=0)")
+ return
+ }
+
+ cfg := config.Config
+ storageType := cfg.StorageType
+ if storageType == "" {
+ storageType = "local"
+ }
+ if storageType != "local" {
+ return
+ }
+
+ basePath := cfg.StoragePath
+ if basePath == "" {
+ basePath = "./storage"
+ }
+ abs, err := filepath.Abs(basePath)
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: cannot resolve storage path %q: %w", basePath, err))
+ return
+ }
+ recordingsDir := filepath.Clean(filepath.Join(abs, recordingsSubdir))
+
+ if !isSafeRecordingsDir(recordingsDir) {
+ traceway.CaptureException(fmt.Errorf("retention: refusing to clean shallow recordings dir %q — set STORAGE_PATH to a dedicated directory", recordingsDir))
+ return
+ }
+
+ config.Logf("Starting session recording disk cleanup worker (TTL: %d days, dir: %s)", days, recordingsDir)
+
+ go func() {
+ runRecordingDiskCleanup(recordingsDir, days)
+
+ ticker := time.NewTicker(tickInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ runRecordingDiskCleanup(recordingsDir, days)
+ }
+ }
+ }()
+}
+
+func isSafeRecordingsDir(path string) bool {
+ cleaned := filepath.Clean(path)
+ if cleaned == "/" || cleaned == "." {
+ return false
+ }
+ rel := strings.TrimPrefix(cleaned, string(filepath.Separator))
+ parts := strings.Split(rel, string(filepath.Separator))
+ return len(parts) >= 2
+}
+
+func runRecordingDiskCleanup(dir string, days int) {
+ info, err := os.Stat(dir)
+ if errors.Is(err, fs.ErrNotExist) {
+ return
+ }
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: stat %s failed: %w", dir, err))
+ return
+ }
+ if !info.IsDir() {
+ traceway.CaptureException(fmt.Errorf("retention: recordings path %s is not a directory", dir))
+ return
+ }
+
+ cutoff := time.Now().Add(-time.Duration(days) * 24 * time.Hour)
+
+ var subDirs []string
+ var removed int
+ walkErr := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: walk error at %s: %w", path, err))
+ return nil
+ }
+ if d.IsDir() {
+ if path != dir {
+ subDirs = append(subDirs, path)
+ }
+ return nil
+ }
+ fi, err := d.Info()
+ if err != nil {
+ return nil
+ }
+ if fi.ModTime().Before(cutoff) {
+ if rmErr := os.Remove(path); rmErr != nil {
+ traceway.CaptureException(fmt.Errorf("retention: failed to remove %s: %w", path, rmErr))
+ return nil
+ }
+ removed++
+ }
+ return nil
+ })
+ if walkErr != nil {
+ traceway.CaptureException(fmt.Errorf("retention: walk %s failed: %w", dir, walkErr))
+ }
+
+ for i := len(subDirs) - 1; i >= 0; i-- {
+ _ = os.Remove(subDirs[i])
+ }
+
+ if removed > 0 {
+ config.Logf("Recording disk cleanup removed %d file(s) older than %d day(s) under %s", removed, days, dir)
+ }
+}
diff --git a/backend/app/retention/recordings_test.go b/backend/app/retention/recordings_test.go
new file mode 100644
index 00000000..559c2bc5
--- /dev/null
+++ b/backend/app/retention/recordings_test.go
@@ -0,0 +1,149 @@
+package retention
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+)
+
+func TestIsSafeRecordingsDir(t *testing.T) {
+ cases := []struct {
+ path string
+ safe bool
+ }{
+ {"/", false},
+ {".", false},
+ {"/recordings", false},
+ {"recordings", false},
+ {"/storage/recordings", true},
+ {"/var/lib/traceway/recordings", true},
+ }
+ for _, c := range cases {
+ if got := isSafeRecordingsDir(c.path); got != c.safe {
+ t.Errorf("isSafeRecordingsDir(%q) = %v, want %v", c.path, got, c.safe)
+ }
+ }
+}
+
+func TestRunRecordingDiskCleanup_DeletesOldKeepsFresh(t *testing.T) {
+ dir := t.TempDir()
+
+ oldFile := filepath.Join(dir, "project-1", "old.json")
+ freshFile := filepath.Join(dir, "project-1", "fresh.json")
+ nestedOld := filepath.Join(dir, "project-2", "sessions", "abc", "0.json")
+ nestedFresh := filepath.Join(dir, "project-2", "sessions", "xyz", "0.json")
+
+ mustWriteFile(t, oldFile, "old")
+ mustWriteFile(t, freshFile, "fresh")
+ mustWriteFile(t, nestedOld, "nested-old")
+ mustWriteFile(t, nestedFresh, "nested-fresh")
+
+ aged := time.Now().Add(-40 * 24 * time.Hour)
+ mustChtime(t, oldFile, aged)
+ mustChtime(t, nestedOld, aged)
+
+ runRecordingDiskCleanup(dir, 30)
+
+ assertNotExists(t, oldFile)
+ assertExists(t, freshFile)
+ assertNotExists(t, nestedOld)
+ assertExists(t, nestedFresh)
+}
+
+func TestRunRecordingDiskCleanup_PrunesEmptyDirsKeepsRoot(t *testing.T) {
+ dir := t.TempDir()
+
+ emptyAfter := filepath.Join(dir, "project-empty", "old.json")
+ mixedOld := filepath.Join(dir, "project-mixed", "old.json")
+ mixedFresh := filepath.Join(dir, "project-mixed", "fresh.json")
+
+ mustWriteFile(t, emptyAfter, "")
+ mustWriteFile(t, mixedOld, "")
+ mustWriteFile(t, mixedFresh, "")
+
+ aged := time.Now().Add(-40 * 24 * time.Hour)
+ mustChtime(t, emptyAfter, aged)
+ mustChtime(t, mixedOld, aged)
+
+ runRecordingDiskCleanup(dir, 30)
+
+ assertExists(t, dir)
+ assertNotExists(t, filepath.Join(dir, "project-empty"))
+ assertExists(t, filepath.Join(dir, "project-mixed"))
+ assertExists(t, mixedFresh)
+}
+
+func TestRunRecordingDiskCleanup_NoOpOnMissingDir(t *testing.T) {
+ parent := t.TempDir()
+ missing := filepath.Join(parent, "does-not-exist")
+
+ runRecordingDiskCleanup(missing, 30)
+
+ if _, err := os.Stat(missing); !os.IsNotExist(err) {
+ t.Fatalf("expected missing dir to remain absent, got err=%v", err)
+ }
+}
+
+func TestRunRecordingDiskCleanup_RefusesPathThatIsAFile(t *testing.T) {
+ parent := t.TempDir()
+ filePath := filepath.Join(parent, "not-a-dir")
+ mustWriteFile(t, filePath, "important")
+
+ aged := time.Now().Add(-40 * 24 * time.Hour)
+ mustChtime(t, filePath, aged)
+
+ runRecordingDiskCleanup(filePath, 30)
+
+ assertExists(t, filePath)
+}
+
+func TestRunRecordingDiskCleanup_KeepsAllWhenNoneAreOld(t *testing.T) {
+ dir := t.TempDir()
+
+ files := []string{
+ filepath.Join(dir, "p1", "a.json"),
+ filepath.Join(dir, "p1", "b.json"),
+ filepath.Join(dir, "p2", "c.json"),
+ }
+ for _, f := range files {
+ mustWriteFile(t, f, "fresh")
+ }
+
+ runRecordingDiskCleanup(dir, 30)
+
+ for _, f := range files {
+ assertExists(t, f)
+ }
+}
+
+func mustWriteFile(t *testing.T, path, content string) {
+ t.Helper()
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write %s: %v", path, err)
+ }
+}
+
+func mustChtime(t *testing.T, path string, when time.Time) {
+ t.Helper()
+ if err := os.Chtimes(path, when, when); err != nil {
+ t.Fatalf("chtimes %s: %v", path, err)
+ }
+}
+
+func assertExists(t *testing.T, path string) {
+ t.Helper()
+ if _, err := os.Stat(path); err != nil {
+ t.Errorf("expected %s to exist, got err=%v", path, err)
+ }
+}
+
+func assertNotExists(t *testing.T, path string) {
+ t.Helper()
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Errorf("expected %s to be gone, got err=%v", path, err)
+ }
+}
diff --git a/backend/app/retention/retention.go b/backend/app/retention/retention.go
new file mode 100644
index 00000000..351e4784
--- /dev/null
+++ b/backend/app/retention/retention.go
@@ -0,0 +1,39 @@
+package retention
+
+import (
+ "context"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+)
+
+const (
+ defaultRetentionDays = 30
+ tickInterval = time.Hour
+)
+
+func Start(ctx context.Context) {
+ cfg := config.Config
+ daysRetentionRecordings := defaultRetentionDays
+ sessionRecordingRetentionDays := strings.TrimSpace(cfg.SessionRecordingRetentionDays)
+ if sessionRecordingRetentionDays != "" {
+ sessionRecordingRetentionDaysInt, err := strconv.Atoi(sessionRecordingRetentionDays)
+ if err == nil && sessionRecordingRetentionDaysInt >= 0 {
+ daysRetentionRecordings = sessionRecordingRetentionDaysInt
+ }
+ }
+
+ daysRetentionSqlite := defaultRetentionDays
+ sqliteRetentionDays := strings.TrimSpace(cfg.SQLiteRetentionDays)
+ if sqliteRetentionDays != "" {
+ sqliteRetentionDaysInt, err := strconv.Atoi(sqliteRetentionDays)
+ if err == nil && sqliteRetentionDaysInt >= 0 {
+ daysRetentionSqlite = sqliteRetentionDaysInt
+ }
+ }
+
+ startSQLiteRetention(ctx, daysRetentionSqlite)
+ startRecordingDiskCleanup(ctx, daysRetentionRecordings)
+}
diff --git a/backend/app/retention/sqlite.go b/backend/app/retention/sqlite.go
new file mode 100644
index 00000000..0e9f43bf
--- /dev/null
+++ b/backend/app/retention/sqlite.go
@@ -0,0 +1,91 @@
+package retention
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ traceway "go.tracewayapp.com"
+)
+
+var telemetryRetentionTargets = []struct {
+ table string
+ column string
+}{
+ {"endpoints", "recorded_at"},
+ {"tasks", "recorded_at"},
+ {"exception_stack_traces", "recorded_at"},
+ {"spans", "recorded_at"},
+ {"metric_points", "recorded_at"},
+ {"session_recordings", "recorded_at"},
+ {"fired_notifications", "fired_at"},
+ {"ai_traces", "recorded_at"},
+ {"log_records", "timestamp"},
+ {"sessions", "started_at"},
+}
+
+var mainRetentionTargets = []struct {
+ table string
+ column string
+}{
+ {"notification_history", "created_at"},
+}
+
+func startSQLiteRetention(ctx context.Context, days int) {
+ if !db.IsSQLite() {
+ return
+ }
+ if days == 0 {
+ config.Logln("SQLite retention disabled (SQLITE_RETENTION_DAYS=0)")
+ return
+ }
+
+ config.Logf("Starting SQLite retention worker (TTL: %d days, interval: %s)", days, tickInterval)
+
+ go func() {
+ runSQLiteRetention(ctx, days)
+
+ ticker := time.NewTicker(tickInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ runSQLiteRetention(ctx, days)
+ }
+ }
+ }()
+}
+
+func runSQLiteRetention(ctx context.Context, days int) {
+ cutoff := time.Now().UTC().AddDate(0, 0, -days).Format(time.RFC3339Nano)
+ params := lit.P{"cutoff": cutoff}
+
+ if db.TelemetryDB != nil {
+ for _, tgt := range telemetryRetentionTargets {
+ if ctx.Err() != nil {
+ return
+ }
+ query := fmt.Sprintf("DELETE FROM %s WHERE %s < :cutoff", tgt.table, tgt.column)
+ if err := lit.DeleteNamed(db.Driver, db.TelemetryDB, query, params); err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: delete from telemetry.%s failed: %w", tgt.table, err))
+ }
+ }
+ }
+
+ if db.DB != nil {
+ for _, tgt := range mainRetentionTargets {
+ if ctx.Err() != nil {
+ return
+ }
+ query := fmt.Sprintf("DELETE FROM %s WHERE %s < :cutoff", tgt.table, tgt.column)
+ if err := lit.DeleteNamed(db.Driver, db.DB, query, params); err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: delete from main.%s failed: %w", tgt.table, err))
+ }
+ }
+ }
+}
diff --git a/backend/app/retention/sqlite_test.go b/backend/app/retention/sqlite_test.go
new file mode 100644
index 00000000..741eb128
--- /dev/null
+++ b/backend/app/retention/sqlite_test.go
@@ -0,0 +1,152 @@
+//go:build !pgch
+
+package retention
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ _ "modernc.org/sqlite"
+)
+
+func setupRetentionTestDB(t *testing.T) {
+ t.Helper()
+
+ mainDB, err := sql.Open("sqlite", ":memory:")
+ if err != nil {
+ t.Fatalf("open main: %v", err)
+ }
+ mainDB.SetMaxOpenConns(1)
+
+ telDB, err := sql.Open("sqlite", ":memory:")
+ if err != nil {
+ t.Fatalf("open telemetry: %v", err)
+ }
+ telDB.SetMaxOpenConns(1)
+
+ for _, tgt := range telemetryRetentionTargets {
+ ddl := fmt.Sprintf(
+ "CREATE TABLE %s (id TEXT, project_id TEXT, %s DATETIME NOT NULL)",
+ tgt.table, tgt.column,
+ )
+ if _, err := telDB.Exec(ddl); err != nil {
+ t.Fatalf("telemetry ddl %s: %v", tgt.table, err)
+ }
+ }
+
+ for _, tgt := range mainRetentionTargets {
+ ddl := fmt.Sprintf(
+ "CREATE TABLE %s (id INTEGER PRIMARY KEY AUTOINCREMENT, project_id TEXT, %s DATETIME NOT NULL)",
+ tgt.table, tgt.column,
+ )
+ if _, err := mainDB.Exec(ddl); err != nil {
+ t.Fatalf("main ddl %s: %v", tgt.table, err)
+ }
+ }
+
+ prevDB, prevTelDB, prevDriver := db.DB, db.TelemetryDB, db.Driver
+ db.DB = mainDB
+ db.TelemetryDB = telDB
+ db.Driver = lit.SQLite
+
+ t.Cleanup(func() {
+ mainDB.Close()
+ telDB.Close()
+ db.DB = prevDB
+ db.TelemetryDB = prevTelDB
+ db.Driver = prevDriver
+ })
+}
+
+func insertWithTime(t *testing.T, ex *sql.DB, table, column string, when time.Time) {
+ t.Helper()
+ ts := when.UTC().Format(time.RFC3339Nano)
+ stmt := fmt.Sprintf("INSERT INTO %s (project_id, %s) VALUES (?, ?)", table, column)
+ if _, err := ex.Exec(stmt, uuid.NewString(), ts); err != nil {
+ t.Fatalf("insert into %s: %v", table, err)
+ }
+}
+
+func countRows(t *testing.T, ex *sql.DB, table string) int {
+ t.Helper()
+ var n int
+ if err := ex.QueryRow("SELECT count(*) FROM " + table).Scan(&n); err != nil {
+ t.Fatalf("count %s: %v", table, err)
+ }
+ return n
+}
+
+func TestRunSQLiteRetention_DeletesOldKeepsFresh(t *testing.T) {
+ setupRetentionTestDB(t)
+
+ now := time.Now().UTC()
+ old := now.AddDate(0, 0, -45)
+ fresh := now.AddDate(0, 0, -5)
+
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", old)
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", old)
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", fresh)
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", fresh)
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", fresh)
+
+ insertWithTime(t, db.TelemetryDB, "log_records", "timestamp", old)
+ insertWithTime(t, db.TelemetryDB, "log_records", "timestamp", fresh)
+ insertWithTime(t, db.TelemetryDB, "log_records", "timestamp", fresh)
+
+ insertWithTime(t, db.TelemetryDB, "sessions", "started_at", old)
+ insertWithTime(t, db.TelemetryDB, "sessions", "started_at", fresh)
+
+ insertWithTime(t, db.TelemetryDB, "fired_notifications", "fired_at", old)
+ insertWithTime(t, db.TelemetryDB, "fired_notifications", "fired_at", fresh)
+
+ insertWithTime(t, db.DB, "notification_history", "created_at", old)
+ insertWithTime(t, db.DB, "notification_history", "created_at", fresh)
+
+ runSQLiteRetention(context.Background(), 30)
+
+ assertCount(t, db.TelemetryDB, "endpoints", 3)
+ assertCount(t, db.TelemetryDB, "log_records", 2)
+ assertCount(t, db.TelemetryDB, "sessions", 1)
+ assertCount(t, db.TelemetryDB, "fired_notifications", 1)
+ assertCount(t, db.DB, "notification_history", 1)
+}
+
+func TestRunSQLiteRetention_BoundaryRowAtCutoffStays(t *testing.T) {
+ setupRetentionTestDB(t)
+
+ cutoff := time.Now().UTC().AddDate(0, 0, -30)
+
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", cutoff.Add(-time.Second))
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", cutoff.Add(time.Second))
+
+ runSQLiteRetention(context.Background(), 30)
+
+ assertCount(t, db.TelemetryDB, "endpoints", 1)
+}
+
+func TestRunSQLiteRetention_AlreadyCancelledContextIsNoOp(t *testing.T) {
+ setupRetentionTestDB(t)
+
+ old := time.Now().UTC().AddDate(0, 0, -45)
+ insertWithTime(t, db.TelemetryDB, "endpoints", "recorded_at", old)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ runSQLiteRetention(ctx, 30)
+
+ assertCount(t, db.TelemetryDB, "endpoints", 1)
+}
+
+func assertCount(t *testing.T, ex *sql.DB, table string, want int) {
+ t.Helper()
+ if got := countRows(t, ex, table); got != want {
+ t.Errorf("%s: got %d rows after cleanup, want %d", table, got, want)
+ }
+}
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index 5d94b0aa..02572630 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -11,6 +11,7 @@ import (
"github.com/tracewayapp/traceway/backend/app/models"
"github.com/tracewayapp/traceway/backend/app/monitoring"
"github.com/tracewayapp/traceway/backend/app/notifications"
+ "github.com/tracewayapp/traceway/backend/app/retention"
"github.com/tracewayapp/traceway/backend/app/services"
"github.com/tracewayapp/traceway/backend/app/storage"
"github.com/tracewayapp/traceway/backend/static"
@@ -119,6 +120,7 @@ func Run(opts ...Option) {
}
notifications.StartEvaluator(ctx)
+ retention.Start(ctx)
var router *gin.Engine
if o != nil && o.disableLogging {