Skip to content

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

progress

ddux92140b44e89e
diff --git a/backend/app/cache/project_cache.go b/backend/app/cache/project_cache.go
new file mode 100644
index 00000000..7fe48d38
--- /dev/null
+++ b/backend/app/cache/project_cache.go
@@ -0,0 +1,98 @@
+package cache
+
+import (
+ "backend/app/models"
+ "backend/app/repositories"
+ "context"
+ "sort"
+ "sync"
+ "time"
+)
+
+type projectCache struct {
+ projects map[string]*models.Project // key: token
+ projectsById map[string]*models.Project // key: id
+ mu sync.RWMutex
+ lastRefresh time.Time
+}
+
+// ProjectCache is the global project cache instance
+var ProjectCache = &projectCache{
+ projects: make(map[string]*models.Project),
+ projectsById: make(map[string]*models.Project),
+}
+
+// Init initializes the cache by loading all projects from the database
+func (c *projectCache) Init(ctx context.Context) error {
+ return c.Refresh(ctx)
+}
+
+// Refresh reloads all projects from the database into the cache
+func (c *projectCache) Refresh(ctx context.Context) error {
+ projects, err := repositories.ProjectRepository.FindAll(ctx)
+ if err != nil {
+ return err
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+
+ c.projects = make(map[string]*models.Project)
+ c.projectsById = make(map[string]*models.Project)
+
+ for i := range projects {
+ proj := &projects[i]
+ c.projects[proj.Token] = proj
+ c.projectsById[proj.Id] = proj
+ }
+ c.lastRefresh = time.Now()
+
+ return nil
+}
+
+// GetByToken returns a project by its token, or nil if not found
+func (c *projectCache) GetByToken(token string) *models.Project {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.projects[token]
+}
+
+// GetById returns a project by its ID, or nil if not found
+func (c *projectCache) GetById(id string) *models.Project {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.projectsById[id]
+}
+
+// GetAll returns all cached projects sorted by created_at (oldest first)
+func (c *projectCache) GetAll() []*models.Project {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+
+ result := make([]*models.Project, 0, len(c.projectsById))
+ for _, proj := range c.projectsById {
+ result = append(result, proj)
+ }
+
+ // Sort by CreatedAt ascending (oldest first, newest last)
+ sort.Slice(result, func(i, j int) bool {
+ return result[i].CreatedAt.Before(result[j].CreatedAt)
+ })
+
+ return result
+}
+
+// AddProject adds a project to the cache
+func (c *projectCache) AddProject(proj *models.Project) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.projects[proj.Token] = proj
+ c.projectsById[proj.Id] = proj
+}
+
+// LastRefresh returns the time of the last cache refresh
+func (c *projectCache) LastRefresh() time.Time {
+ c.mu.RLock()
+ defer c.mu.RUnlock()
+ return c.lastRefresh
+}
diff --git a/backend/app/controllers/clientcontrollers/client.controller.go b/backend/app/controllers/clientcontrollers/client.controller.go
index dec24033..f9930ab3 100644
--- a/backend/app/controllers/clientcontrollers/client.controller.go
+++ b/backend/app/controllers/clientcontrollers/client.controller.go
@@ -1,6 +1,7 @@
package clientcontrollers
import (
+ "backend/app/middleware"
"backend/app/models"
"backend/app/models/clientmodels"
"backend/app/repositories"
@@ -21,6 +22,9 @@ type ReportRequest struct {
}
func (e clientController) Report(c *gin.Context) {
+ // Get project ID from context (set by middleware)
+ projectId := middleware.GetProjectId(c)
+
// we need to parse the request
var request ReportRequest
if err := c.ShouldBindBodyWithJSON(&request); err != nil {
@@ -33,15 +37,21 @@ func (e clientController) Report(c *gin.Context) {
metricRecordsToInsert := []models.MetricRecord{}
for _, cf := range request.CollectionFrames {
for _, ct := range cf.Transactions {
- transactionsToInsert = append(transactionsToInsert, ct.ToTransaction())
+ t := ct.ToTransaction()
+ t.ProjectId = projectId
+ transactionsToInsert = append(transactionsToInsert, t)
}
for _, cst := range cf.StackTraces {
- exceptionStackTraceToInsert = append(exceptionStackTraceToInsert, cst.ToExceptionStackTrace(computeExceptionHash(cst.StackTrace)))
+ est := cst.ToExceptionStackTrace(computeExceptionHash(cst.StackTrace))
+ est.ProjectId = projectId
+ exceptionStackTraceToInsert = append(exceptionStackTraceToInsert, est)
}
for _, cm := range cf.Metrics {
- metricRecordsToInsert = append(metricRecordsToInsert, cm.ToMetricRecord())
+ mr := cm.ToMetricRecord()
+ mr.ProjectId = projectId
+ metricRecordsToInsert = append(metricRecordsToInsert, mr)
}
}
diff --git a/backend/app/controllers/dashboard.controller.go b/backend/app/controllers/dashboard.controller.go
index 23ed3118..8dbaf3fd 100644
--- a/backend/app/controllers/dashboard.controller.go
+++ b/backend/app/controllers/dashboard.controller.go
@@ -12,6 +12,8 @@ import (
type dashboardController struct{}
func (d dashboardController) GetDashboard(c *gin.Context) {
+ projectId := c.Query("projectId")
+
now := time.Now()
start := now.Add(-24 * time.Hour)
prevStart := now.Add(-48 * time.Hour)
@@ -20,65 +22,65 @@ func (d dashboardController) GetDashboard(c *gin.Context) {
metrics := make([]models.DashboardMetric, 0, 6)
// 1. Requests count
- requestsTrend, err := repositories.TransactionRepository.CountByHour(c, start, now)
+ requestsTrend, err := repositories.TransactionRepository.CountByHour(c, projectId, start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, start, now)
- requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, prevStart, prevEnd)
+ requestsCurrent, _ := repositories.TransactionRepository.CountBetween(c, projectId, start, now)
+ requestsPrev, _ := repositories.TransactionRepository.CountBetween(c, projectId, prevStart, prevEnd)
metrics = append(metrics, buildMetric("requests", "Requests", float64(requestsCurrent), "count", requestsTrend, float64(requestsPrev), "requests"))
// 2. Exceptions count
- exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByHour(c, start, now)
+ exceptionsTrend, err := repositories.ExceptionStackTraceRepository.CountByHour(c, projectId, start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, start, now)
- exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, prevStart, prevEnd)
+ exceptionsCurrent, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, start, now)
+ exceptionsPrev, _ := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, prevStart, prevEnd)
metrics = append(metrics, buildMetric("exceptions", "Exceptions", float64(exceptionsCurrent), "count", exceptionsTrend, float64(exceptionsPrev), "exceptions"))
// 3. Average Response Time
- avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByHour(c, start, now)
+ avgDurationTrend, err := repositories.TransactionRepository.AvgDurationByHour(c, projectId, start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
avgDurationCurrent := getLastValue(avgDurationTrend)
- avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByHour(c, prevStart, prevEnd)
+ avgDurationPrevTrend, _ := repositories.TransactionRepository.AvgDurationByHour(c, projectId, prevStart, prevEnd)
avgDurationPrev := getAverageValue(avgDurationPrevTrend)
metrics = append(metrics, buildMetric("avg_response_time", "Avg Response Time", avgDurationCurrent, "ms", avgDurationTrend, avgDurationPrev, "response_time"))
// 4. Error Rate
- errorRateTrend, err := repositories.TransactionRepository.ErrorRateByHour(c, start, now)
+ errorRateTrend, err := repositories.TransactionRepository.ErrorRateByHour(c, projectId, start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
errorRateCurrent := getLastValue(errorRateTrend)
- errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByHour(c, prevStart, prevEnd)
+ errorRatePrevTrend, _ := repositories.TransactionRepository.ErrorRateByHour(c, projectId, prevStart, prevEnd)
errorRatePrev := getAverageValue(errorRatePrevTrend)
metrics = append(metrics, buildMetric("error_rate", "Error Rate", errorRateCurrent, "%", errorRateTrend, errorRatePrev, "error_rate"))
// 5. CPU Usage
- cpuTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, "cpu", start, now)
+ cpuTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, "cpu", start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
cpuCurrent := getLastValue(cpuTrend)
- cpuPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, "cpu", prevStart, prevEnd)
+ cpuPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, "cpu", prevStart, prevEnd)
metrics = append(metrics, buildMetric("cpu_usage", "CPU Usage", cpuCurrent, "%", cpuTrend, cpuPrev, "cpu"))
// 6. Memory Usage
- memTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, "ram", start, now)
+ memTrend, err := repositories.MetricRecordRepository.GetAverageByHour(c, projectId, "ram", start, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
memCurrent := getLastValue(memTrend)
- memPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, "ram", prevStart, prevEnd)
+ memPrev, _ := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, "ram", prevStart, prevEnd)
metrics = append(metrics, buildMetric("memory_usage", "Memory Usage", memCurrent, "MB", memTrend, memPrev, "memory"))
c.JSON(http.StatusOK, models.DashboardResponse{
diff --git a/backend/app/controllers/exception_stack_trace.controller.go b/backend/app/controllers/exception_stack_trace.controller.go
index 3371411d..745d8fdf 100644
--- a/backend/app/controllers/exception_stack_trace.controller.go
+++ b/backend/app/controllers/exception_stack_trace.controller.go
@@ -13,6 +13,7 @@ import (
type exceptionStackTraceController struct{}
type ExceptionSearchRequest struct {
+ ProjectId string `json:"projectId"`
FromDate time.Time `json:"fromDate"`
ToDate time.Time `json:"toDate"`
OrderBy string `json:"orderBy"`
@@ -21,6 +22,7 @@ type ExceptionSearchRequest struct {
}
type ExceptionDetailRequest struct {
+ ProjectId string `json:"projectId"`
Pagination PaginationParams `json:"pagination"`
}
@@ -37,7 +39,7 @@ func (e exceptionStackTraceController) FindGrouppedExceptionStackTraces(c *gin.C
return
}
- exceptions, total, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.Search)
+ exceptions, total, err := repositories.ExceptionStackTraceRepository.FindGrouped(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy, request.Search)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -67,7 +69,7 @@ func (e exceptionStackTraceController) FindByHash(c *gin.Context) {
request.Pagination = PaginationParams{Page: 1, PageSize: 20}
}
- group, occurrences, total, err := repositories.ExceptionStackTraceRepository.FindByHash(c, exceptionHash, request.Pagination.Page, request.Pagination.PageSize)
+ group, occurrences, total, err := repositories.ExceptionStackTraceRepository.FindByHash(c, request.ProjectId, exceptionHash, request.Pagination.Page, request.Pagination.PageSize)
if err != nil {
if errors.Is(err, repositories.ErrExceptionNotFound) {
c.JSON(http.StatusNotFound, gin.H{"error": "Exception not found"})
diff --git a/backend/app/controllers/metric_record.controller.go b/backend/app/controllers/metric_record.controller.go
index 30df6b1a..b9032327 100644
--- a/backend/app/controllers/metric_record.controller.go
+++ b/backend/app/controllers/metric_record.controller.go
@@ -11,55 +11,67 @@ import (
type metricRecordController struct{}
+type HomepageStatsRequest struct {
+ ProjectId string `json:"projectId"`
+}
+
func (e metricRecordController) FindHomepageStats(c *gin.Context) {
+ var request HomepageStatsRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ projectId := request.ProjectId
+
// requests in last 24h vs previous 24h
now := time.Now()
oneDayAgo := now.Add(-24 * time.Hour)
twoDaysAgo := now.Add(-48 * time.Hour)
// requests
- requestsNow, err := repositories.TransactionRepository.CountBetween(c, oneDayAgo, now)
+ requestsNow, err := repositories.TransactionRepository.CountBetween(c, projectId, oneDayAgo, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- requestsPrev, err := repositories.TransactionRepository.CountBetween(c, twoDaysAgo, oneDayAgo)
+ requestsPrev, err := repositories.TransactionRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// exceptions
- exceptionsNow, err := repositories.ExceptionStackTraceRepository.CountBetween(c, oneDayAgo, now)
+ exceptionsNow, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, oneDayAgo, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- exceptionsPrev, err := repositories.ExceptionStackTraceRepository.CountBetween(c, twoDaysAgo, oneDayAgo)
+ exceptionsPrev, err := repositories.ExceptionStackTraceRepository.CountBetween(c, projectId, twoDaysAgo, oneDayAgo)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// ram usage last 24h vs previous 24h
- ramNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, models.MetricNameMemoryUsage, oneDayAgo, now)
+ ramNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, oneDayAgo, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- ramPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, models.MetricNameMemoryUsage, twoDaysAgo, oneDayAgo)
+ ramPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameMemoryUsage, twoDaysAgo, oneDayAgo)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
// memory usage last 24h vs previous 24h
- cpuNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, models.MetricNameCpuUsage, oneDayAgo, now)
+ cpuNow, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, oneDayAgo, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
- cpuPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, models.MetricNameCpuUsage, twoDaysAgo, oneDayAgo)
+ cpuPrev, err := repositories.MetricRecordRepository.GetAverageBetween(c, projectId, models.MetricNameCpuUsage, twoDaysAgo, oneDayAgo)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.go
new file mode 100644
index 00000000..00133fa0
--- /dev/null
+++ b/backend/app/controllers/project.controller.go
@@ -0,0 +1,99 @@
+package controllers
+
+import (
+ "backend/app/cache"
+ "backend/app/models"
+ "backend/app/repositories"
+ "net/http"
+ "regexp"
+ "unicode/utf8"
+
+ "github.com/gin-gonic/gin"
+)
+
+// Valid framework values
+var validFrameworks = map[string]bool{
+ "stdlib": true,
+ "fasthttp": true,
+ "gin": true,
+ "fiber": true,
+ "chi": true,
+ "custom": true,
+}
+
+// Project name validation regex: allows alphanumeric, spaces, hyphens, and underscores
+var projectNameRegex = regexp.MustCompile(`^[a-zA-Z0-9\s\-_]+$`)
+
+type projectController struct{}
+
+type CreateProjectRequest struct {
+ Name string `json:"name" binding:"required"`
+ Framework string `json:"framework" binding:"required"`
+}
+
+// ListProjects returns all projects without tokens
+func (p projectController) ListProjects(c *gin.Context) {
+ projects := cache.ProjectCache.GetAll()
+
+ // Convert to response format (without tokens)
+ response := make([]models.ProjectResponse, len(projects))
+ for i, proj := range projects {
+ response[i] = proj.ToResponse()
+ }
+
+ c.JSON(http.StatusOK, response)
+}
+
+// CreateProject creates a new project and returns it with its token
+func (p projectController) CreateProject(c *gin.Context) {
+ var request CreateProjectRequest
+ if err := c.ShouldBindJSON(&request); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ return
+ }
+
+ // Validate project name
+ nameLen := utf8.RuneCountInString(request.Name)
+ if nameLen < 1 || nameLen > 100 {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Project name must be between 1 and 100 characters"})
+ return
+ }
+ if !projectNameRegex.MatchString(request.Name) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Project name can only contain letters, numbers, spaces, hyphens, and underscores"})
+ return
+ }
+
+ // Validate framework
+ if !validFrameworks[request.Framework] {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: stdlib, fasthttp, gin, fiber, chi, custom"})
+ return
+ }
+
+ project, err := repositories.ProjectRepository.Create(c, request.Name, request.Framework)
+ if err != nil {
+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create project"})
+ return
+ }
+
+ // Add to cache
+ cache.ProjectCache.AddProject(project)
+
+ // Return with token since this is creation
+ c.JSON(http.StatusCreated, project.ToWithToken())
+}
+
+// GetProject returns a project by ID with its token (for connection page)
+func (p projectController) GetProject(c *gin.Context) {
+ projectId := c.Param("id")
+
+ project := cache.ProjectCache.GetById(projectId)
+ if project == nil {
+ c.JSON(http.StatusNotFound, gin.H{"error": "Project not found"})
+ return
+ }
+
+ // Return with token for connection page
+ c.JSON(http.StatusOK, project.ToWithToken())
+}
+
+var ProjectController = projectController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index ef465c73..76833520 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -27,6 +27,11 @@ type Pagination struct {
func RegisterControllers(router *gin.RouterGroup) {
router.POST("/report", middleware.UseClientAuth, middleware.UseGzip, clientcontrollers.ClientController.Report)
+ // Project management
+ router.GET("/projects", middleware.UseAppAuth, ProjectController.ListProjects)
+ router.POST("/projects", middleware.UseAppAuth, ProjectController.CreateProject)
+ router.GET("/projects/:id", middleware.UseAppAuth, ProjectController.GetProject)
+
router.POST("/stats", middleware.UseAppAuth, MetricRecordController.FindHomepageStats)
router.GET("/dashboard", middleware.UseAppAuth, DashboardController.GetDashboard)
diff --git a/backend/app/controllers/transaction.controller.go b/backend/app/controllers/transaction.controller.go
index fe984d70..73612060 100644
--- a/backend/app/controllers/transaction.controller.go
+++ b/backend/app/controllers/transaction.controller.go
@@ -13,6 +13,7 @@ import (
type transactionController struct{}
type TransactionSearchRequest struct {
+ ProjectId string `json:"projectId"`
FromDate time.Time `json:"fromDate"`
ToDate time.Time `json:"toDate"`
OrderBy string `json:"orderBy"`
@@ -20,6 +21,7 @@ type TransactionSearchRequest struct {
}
type EndpointTransactionsRequest struct {
+ ProjectId string `json:"projectId"`
FromDate time.Time `json:"fromDate"`
ToDate time.Time `json:"toDate"`
OrderBy string `json:"orderBy"`
@@ -33,7 +35,7 @@ func (e transactionController) FindAllTransactions(c *gin.Context) {
return
}
- transactions, total, err := repositories.TransactionRepository.FindAll(c, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
+ transactions, total, err := repositories.TransactionRepository.FindAll(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -57,7 +59,7 @@ func (e transactionController) FindGroupedByEndpoint(c *gin.Context) {
return
}
- stats, total, err := repositories.TransactionRepository.FindGroupedByEndpoint(c, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
+ stats, total, err := repositories.TransactionRepository.FindGroupedByEndpoint(c, request.ProjectId, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
@@ -93,7 +95,7 @@ func (e transactionController) FindByEndpoint(c *gin.Context) {
return
}
- transactions, total, err := repositories.TransactionRepository.FindByEndpoint(c, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
+ transactions, total, err := repositories.TransactionRepository.FindByEndpoint(c, request.ProjectId, endpoint, request.FromDate, request.ToDate, request.Pagination.Page, request.Pagination.PageSize, request.OrderBy)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
diff --git a/backend/app/middleware/use_client_auth.middleware.go b/backend/app/middleware/use_client_auth.middleware.go
index 0cd78245..33065a66 100644
--- a/backend/app/middleware/use_client_auth.middleware.go
+++ b/backend/app/middleware/use_client_auth.middleware.go
@@ -1,23 +1,49 @@
package middleware
import (
+ "backend/app/cache"
"net/http"
- "os"
+ "strings"
"github.com/gin-gonic/gin"
)
+const ProjectContextKey = "project"
+const ProjectIdContextKey = "project_id"
+
var UseClientAuth func(c *gin.Context)
func InitUseClientAuth() {
- authHeader := "Bearer " + os.Getenv("TOKEN")
-
UseClientAuth = func(c *gin.Context) {
- if authHeader != c.GetHeader("Authorization") {
+ authHeader := c.GetHeader("Authorization")
+
+ // Extract token from "Bearer <token>"
+ if !strings.HasPrefix(authHeader, "Bearer ") {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+
+ token := strings.TrimPrefix(authHeader, "Bearer ")
+
+ // Look up project by token in cache
+ project := cache.ProjectCache.GetByToken(token)
+ if project == nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
+ // Set project in context for downstream handlers
+ c.Set(ProjectContextKey, project)
+ c.Set(ProjectIdContextKey, project.Id)
+
c.Next()
}
}
+
+// GetProjectId retrieves the project ID from the Gin context
+func GetProjectId(c *gin.Context) string {
+ if id, exists := c.Get(ProjectIdContextKey); exists {
+ return id.(string)
+ }
+ return ""
+}
diff --git a/backend/app/migrations/ch/0004_created_projects.up.sql b/backend/app/migrations/ch/0004_created_projects.up.sql
new file mode 100644
index 00000000..22c29a91
--- /dev/null
+++ b/backend/app/migrations/ch/0004_created_projects.up.sql
@@ -0,0 +1,7 @@
+CREATE TABLE IF NOT EXISTS projects (
+ id String,
+ name String,
+ token String,
+ created_at DateTime DEFAULT now()
+) ENGINE = MergeTree()
+ORDER BY (created_at, id)
diff --git a/backend/app/migrations/ch/0005_insert_default_project.up.sql b/backend/app/migrations/ch/0005_insert_default_project.up.sql
new file mode 100644
index 00000000..0ac5ca34
--- /dev/null
+++ b/backend/app/migrations/ch/0005_insert_default_project.up.sql
@@ -0,0 +1,6 @@
+INSERT INTO projects (id, name, token, created_at) VALUES (
+ '00000000-0000-0000-0000-000000000001',
+ 'Default Project',
+ 'default_token_change_me',
+ now()
+)
diff --git a/backend/app/migrations/ch/0006_add_project_id_to_transactions.up.sql b/backend/app/migrations/ch/0006_add_project_id_to_transactions.up.sql
new file mode 100644
index 00000000..275ab33a
--- /dev/null
+++ b/backend/app/migrations/ch/0006_add_project_id_to_transactions.up.sql
@@ -0,0 +1 @@
+ALTER TABLE transactions ADD COLUMN IF NOT EXISTS project_id String DEFAULT '00000000-0000-0000-0000-000000000001'
diff --git a/backend/app/migrations/ch/0007_add_project_id_to_metric_records.up.sql b/backend/app/migrations/ch/0007_add_project_id_to_metric_records.up.sql
new file mode 100644
index 00000000..bd67ff27
--- /dev/null
+++ b/backend/app/migrations/ch/0007_add_project_id_to_metric_records.up.sql
@@ -0,0 +1 @@
+ALTER TABLE metric_records ADD COLUMN IF NOT EXISTS project_id String DEFAULT '00000000-0000-0000-0000-000000000001'
diff --git a/backend/app/migrations/ch/0008_add_project_id_to_exception_stack_traces.up.sql b/backend/app/migrations/ch/0008_add_project_id_to_exception_stack_traces.up.sql
new file mode 100644
index 00000000..d8a9ff14
--- /dev/null
+++ b/backend/app/migrations/ch/0008_add_project_id_to_exception_stack_traces.up.sql
@@ -0,0 +1 @@
+ALTER TABLE exception_stack_traces ADD COLUMN IF NOT EXISTS project_id String DEFAULT '00000000-0000-0000-0000-000000000001'
diff --git a/backend/app/migrations/ch/0009_add_framework_to_projects.up.sql b/backend/app/migrations/ch/0009_add_framework_to_projects.up.sql
new file mode 100644
index 00000000..b9704214
--- /dev/null
+++ b/backend/app/migrations/ch/0009_add_framework_to_projects.up.sql
@@ -0,0 +1 @@
+ALTER TABLE projects ADD COLUMN IF NOT EXISTS framework String DEFAULT 'custom';
diff --git a/backend/app/models/exception_stack_trace.model.go b/backend/app/models/exception_stack_trace.model.go
index 1a80f4aa..4982d2be 100644
--- a/backend/app/models/exception_stack_trace.model.go
+++ b/backend/app/models/exception_stack_trace.model.go
@@ -3,6 +3,7 @@ package models
import "time"
type ExceptionStackTrace struct {
+ ProjectId string `json:"projectId" ch:"project_id"`
TransactionId *string `json:"transactionId" ch:"transaction_id"`
ExceptionHash string `json:"exceptionHash" ch:"exception_hash"`
StackTrace string `json:"stackTrace" ch:"stack_trace"`
diff --git a/backend/app/models/metric_record.model.go b/backend/app/models/metric_record.model.go
index a68dd484..3b5814f2 100644
--- a/backend/app/models/metric_record.model.go
+++ b/backend/app/models/metric_record.model.go
@@ -3,6 +3,7 @@ package models
import "time"
type MetricRecord struct {
+ ProjectId string `json:"projectId" ch:"project_id"`
Name string `json:"name" ch:"name"`
Value float64 `json:"value" ch:"value"`
RecordedAt time.Time `json:"recordedAt" ch:"recorded_at"`
diff --git a/backend/app/models/project.model.go b/backend/app/models/project.model.go
new file mode 100644
index 00000000..87c8e30a
--- /dev/null
+++ b/backend/app/models/project.model.go
@@ -0,0 +1,49 @@
+package models
+
+import "time"
+
+type Project struct {
+ Id string `json:"id" ch:"id"`
+ Name string `json:"name" ch:"name"`
+ Token string `json:"token" ch:"token"`
+ Framework string `json:"framework" ch:"framework"`
+ CreatedAt time.Time `json:"createdAt" ch:"created_at"`
+}
+
+// ProjectResponse omits the token for security in listing endpoints
+type ProjectResponse struct {
+ Id string `json:"id"`
+ Name string `json:"name"`
+ Framework string `json:"framework"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// ProjectWithToken includes token - used when creating or viewing connection details
+type ProjectWithToken struct {
+ Id string `json:"id"`
+ Name string `json:"name"`
+ Token string `json:"token"`
+ Framework string `json:"framework"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+// ToResponse converts a Project to ProjectResponse (without token)
+func (p *Project) ToResponse() ProjectResponse {
+ return ProjectResponse{
+ Id: p.Id,
+ Name: p.Name,
+ Framework: p.Framework,
+ CreatedAt: p.CreatedAt,
+ }
+}
+
+// ToWithToken converts a Project to ProjectWithToken
+func (p *Project) ToWithToken() ProjectWithToken {
+ return ProjectWithToken{
+ Id: p.Id,
+ Name: p.Name,
+ Token: p.Token,
+ Framework: p.Framework,
+ CreatedAt: p.CreatedAt,
+ }
+}
diff --git a/backend/app/models/transaction.model.go b/backend/app/models/transaction.model.go
index 43c5adca..9801c4bd 100644
--- a/backend/app/models/transaction.model.go
+++ b/backend/app/models/transaction.model.go
@@ -3,7 +3,8 @@ package models
import "time"
type Transaction struct {
- Id string `json:"id" ch:"id"`
+ Id string `json:"id" ch:"id"`
+ ProjectId string `json:"projectId" ch:"project_id"`
// endpoint is the route from the router/does not contain actual params so it's safe to group on it
Endpoint string `json:"endpoint" ch:"endpoint"`
Duration time.Duration `json:"duration" ch:"duration"`
diff --git a/backend/app/repositories/exception_stack_trace.repository.go b/backend/app/repositories/exception_stack_trace.repository.go
index 3f511693..b81755aa 100644
--- a/backend/app/repositories/exception_stack_trace.repository.go
+++ b/backend/app/repositories/exception_stack_trace.repository.go
@@ -13,25 +13,25 @@ var ErrExceptionNotFound = errors.New("exception not found")
type exceptionStackTraceRepository struct{}
func (e *exceptionStackTraceRepository) InsertAsync(ctx context.Context, lines []models.ExceptionStackTrace) error {
- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO exception_stack_traces (transaction_id, exception_hash, stack_trace, recorded_at)")
+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO exception_stack_traces (project_id, transaction_id, exception_hash, stack_trace, recorded_at)")
if err != nil {
return err
}
- for _, e := range lines {
- if err := batch.Append(e.TransactionId, e.ExceptionHash, e.StackTrace, e.RecordedAt); err != nil {
+ for _, est := range lines {
+ if err := batch.Append(est.ProjectId, est.TransactionId, est.ExceptionHash, est.StackTrace, est.RecordedAt); err != nil {
return err
}
}
return batch.Send()
}
-func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, start, end time.Time) (int64, error) {
+func (e *exceptionStackTraceRepository) CountBetween(ctx context.Context, projectId string, start, end time.Time) (int64, error) {
var count uint64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM exception_stack_traces WHERE recorded_at >= ? AND recorded_at <= ?", start, end).Scan(&count)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM exception_stack_traces WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, start, end).Scan(&count)
return int64(count), err
}
-func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, fromDate, toDate time.Time, page, pageSize int, orderBy string, search string) ([]models.ExceptionGroup, int64, error) {
+func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string, search string) ([]models.ExceptionGroup, int64, error) {
offset := (page - 1) * pageSize
allowedOrderBy := map[string]bool{
@@ -45,8 +45,8 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, fromDat
}
// Build WHERE clause dynamically based on search
- whereClause := "recorded_at >= ? AND recorded_at <= ?"
- args := []interface{}{fromDate, toDate}
+ whereClause := "project_id = ? AND recorded_at >= ? AND recorded_at <= ?"
+ args := []interface{}{projectId, fromDate, toDate}
if search != "" {
whereClause += " AND positionCaseInsensitive(stack_trace, ?) > 0"
@@ -83,14 +83,14 @@ func (e *exceptionStackTraceRepository) FindGrouped(ctx context.Context, fromDat
return groups, int64(count), nil
}
-func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, exceptionHash string, page, pageSize int) (*models.ExceptionGroup, []models.ExceptionStackTrace, int64, error) {
+func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, projectId string, exceptionHash string, page, pageSize int) (*models.ExceptionGroup, []models.ExceptionStackTrace, int64, error) {
offset := (page - 1) * pageSize
// Get grouped info
var group models.ExceptionGroup
err := (*chdb.Conn).QueryRow(ctx,
- "SELECT exception_hash, any(stack_trace), max(recorded_at) as last_seen, min(recorded_at) as first_seen, count() as count FROM exception_stack_traces WHERE exception_hash = ? GROUP BY exception_hash",
- exceptionHash).Scan(&group.ExceptionHash, &group.StackTrace, &group.LastSeen, &group.FirstSeen, &group.Count)
+ "SELECT exception_hash, any(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, exceptionHash).Scan(&group.ExceptionHash, &group.StackTrace, &group.LastSeen, &group.FirstSeen, &group.Count)
if err != nil {
// ClickHouse returns error when no rows found in QueryRow
return nil, nil, 0, ErrExceptionNotFound
@@ -98,8 +98,8 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, exceptio
// Get individual occurrences with pagination
rows, err := (*chdb.Conn).Query(ctx,
- "SELECT transaction_id, exception_hash, stack_trace, recorded_at FROM exception_stack_traces WHERE exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",
- exceptionHash, pageSize, offset)
+ "SELECT project_id, transaction_id, exception_hash, stack_trace, recorded_at FROM exception_stack_traces WHERE project_id = ? AND exception_hash = ? ORDER BY recorded_at DESC LIMIT ? OFFSET ?",
+ projectId, exceptionHash, pageSize, offset)
if err != nil {
return nil, nil, 0, err
}
@@ -108,7 +108,7 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, exceptio
var occurrences []models.ExceptionStackTrace
for rows.Next() {
var o models.ExceptionStackTrace
- if err := rows.Scan(&o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt); err != nil {
+ if err := rows.Scan(&o.ProjectId, &o.TransactionId, &o.ExceptionHash, &o.StackTrace, &o.RecordedAt); err != nil {
return nil, nil, 0, err
}
occurrences = append(occurrences, o)
@@ -118,16 +118,16 @@ func (e *exceptionStackTraceRepository) FindByHash(ctx context.Context, exceptio
}
// CountByHour returns exception counts grouped by hour
-func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {
+func (e *exceptionStackTraceRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
query := `SELECT
toStartOfHour(recorded_at) as hour,
count() as count
FROM exception_stack_traces
- WHERE recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY hour
ORDER BY hour ASC`
- rows, err := (*chdb.Conn).Query(ctx, query, start, end)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)
if err != nil {
return nil, err
}
diff --git a/backend/app/repositories/metric_record.repository.go b/backend/app/repositories/metric_record.repository.go
index aa69ba6f..9a631b34 100644
--- a/backend/app/repositories/metric_record.repository.go
+++ b/backend/app/repositories/metric_record.repository.go
@@ -10,35 +10,35 @@ import (
type metricRecordRepository struct{}
func (e *metricRecordRepository) InsertAsync(ctx context.Context, lines []models.MetricRecord) error {
- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO metric_records (name, value, recorded_at)")
+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO metric_records (project_id, name, value, recorded_at)")
if err != nil {
return err
}
- for _, e := range lines {
- if err := batch.Append(e.Name, e.Value, e.RecordedAt); err != nil {
+ for _, m := range lines {
+ if err := batch.Append(m.ProjectId, m.Name, m.Value, m.RecordedAt); err != nil {
return err
}
}
return batch.Send()
}
-func (e *metricRecordRepository) GetAverageBetween(ctx context.Context, name string, start, end time.Time) (float64, error) {
+func (e *metricRecordRepository) GetAverageBetween(ctx context.Context, projectId string, name string, start, end time.Time) (float64, error) {
var avg float64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT coalesce(avg(value), 0) FROM metric_records WHERE name = ? AND recorded_at >= ? AND recorded_at <= ?", name, start, end).Scan(&avg)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT coalesce(avg(value), 0) FROM metric_records WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, name, start, end).Scan(&avg)
return avg, err
}
// GetAverageByHour returns metric averages grouped by hour
-func (e *metricRecordRepository) GetAverageByHour(ctx context.Context, name string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
+func (e *metricRecordRepository) GetAverageByHour(ctx context.Context, projectId string, name string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
query := `SELECT
toStartOfHour(recorded_at) as hour,
avg(value) as avg_value
FROM metric_records
- WHERE name = ? AND recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND name = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY hour
ORDER BY hour ASC`
- rows, err := (*chdb.Conn).Query(ctx, query, name, start, end)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, name, start, end)
if err != nil {
return nil, err
}
diff --git a/backend/app/repositories/project.repository.go b/backend/app/repositories/project.repository.go
new file mode 100644
index 00000000..96530ab4
--- /dev/null
+++ b/backend/app/repositories/project.repository.go
@@ -0,0 +1,74 @@
+package repositories
+
+import (
+ "backend/app/chdb"
+ "backend/app/models"
+ "context"
+ "crypto/rand"
+ "encoding/hex"
+ "errors"
+
+ "github.com/google/uuid"
+)
+
+var ErrProjectNotFound = errors.New("project not found")
+
+type projectRepository struct{}
+
+func (p *projectRepository) FindAll(ctx context.Context) ([]models.Project, error) {
+ rows, err := (*chdb.Conn).Query(ctx, "SELECT id, name, token, framework, created_at FROM projects ORDER BY created_at ASC")
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var projects []models.Project
+ for rows.Next() {
+ var proj models.Project
+ if err := rows.Scan(&proj.Id, &proj.Name, &proj.Token, &proj.Framework, &proj.CreatedAt); err != nil {
+ return nil, err
+ }
+ projects = append(projects, proj)
+ }
+ return projects, nil
+}
+
+func (p *projectRepository) FindByToken(ctx context.Context, token string) (*models.Project, error) {
+ var proj models.Project
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT id, name, token, framework, created_at FROM projects WHERE token = ?", token).
+ Scan(&proj.Id, &proj.Name, &proj.Token, &proj.Framework, &proj.CreatedAt)
+ if err != nil {
+ return nil, ErrProjectNotFound
+ }
+ return &proj, nil
+}
+
+func (p *projectRepository) FindById(ctx context.Context, id string) (*models.Project, error) {
+ var proj models.Project
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT id, name, token, framework, created_at FROM projects WHERE id = ?", id).
+ Scan(&proj.Id, &proj.Name, &proj.Token, &proj.Framework, &proj.CreatedAt)
+ if err != nil {
+ return nil, ErrProjectNotFound
+ }
+ return &proj, nil
+}
+
+func (p *projectRepository) Create(ctx context.Context, name string, framework string) (*models.Project, error) {
+ id := uuid.New().String()
+ token := generateSecureToken()
+
+ err := (*chdb.Conn).Exec(ctx, "INSERT INTO projects (id, name, token, framework) VALUES (?, ?, ?, ?)", id, name, token, framework)
+ if err != nil {
+ return nil, err
+ }
+
+ return p.FindById(ctx, id)
+}
+
+func generateSecureToken() string {
+ bytes := make([]byte, 32)
+ rand.Read(bytes)
+ return hex.EncodeToString(bytes)
+}
+
+var ProjectRepository = projectRepository{}
diff --git a/backend/app/repositories/transaction.repository.go b/backend/app/repositories/transaction.repository.go
index f32de144..c3203d29 100644
--- a/backend/app/repositories/transaction.repository.go
+++ b/backend/app/repositories/transaction.repository.go
@@ -10,27 +10,27 @@ import (
type transactionRepository struct{}
func (e *transactionRepository) InsertAsync(ctx context.Context, lines []models.Transaction) error {
- batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO transactions (id, endpoint, duration, recorded_at, status_code, body_size, client_ip)")
+ batch, err := (*chdb.Conn).PrepareBatch(ctx, "INSERT INTO transactions (id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip)")
if err != nil {
return err
}
- for _, e := range lines {
- if err := batch.Append(e.Id, e.Endpoint, e.Duration, e.RecordedAt, e.StatusCode, e.BodySize, e.ClientIP); err != nil {
+ for _, t := range lines {
+ if err := batch.Append(t.Id, t.ProjectId, t.Endpoint, t.Duration, t.RecordedAt, t.StatusCode, t.BodySize, t.ClientIP); err != nil {
return err
}
}
return batch.Send()
}
-func (e *transactionRepository) CountBetween(ctx context.Context, start, end time.Time) (int64, error) {
+func (e *transactionRepository) CountBetween(ctx context.Context, projectId string, start, end time.Time) (int64, error) {
var count uint64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE recorded_at >= ? AND recorded_at <= ?", start, end).Scan(&count)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, start, end).Scan(&count)
return int64(count), err
}
-func (e *transactionRepository) FindAll(ctx context.Context, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {
+func (e *transactionRepository) FindAll(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {
var count uint64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE recorded_at >= ? AND recorded_at <= ?", fromDate, toDate).Scan(&count)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)
if err != nil {
return nil, 0, err
}
@@ -48,8 +48,8 @@ func (e *transactionRepository) FindAll(ctx context.Context, fromDate, toDate ti
orderBy = "recorded_at"
}
- query := "SELECT id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"
- rows, err := (*chdb.Conn).Query(ctx, query, fromDate, toDate, pageSize, offset)
+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, fromDate, toDate, pageSize, offset)
if err != nil {
return nil, 0, err
}
@@ -58,7 +58,7 @@ func (e *transactionRepository) FindAll(ctx context.Context, fromDate, toDate ti
var transactions []models.Transaction
for rows.Next() {
var t models.Transaction
- if err := rows.Scan(&t.Id, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {
+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {
return nil, 0, err
}
transactions = append(transactions, t)
@@ -67,10 +67,10 @@ func (e *transactionRepository) FindAll(ctx context.Context, fromDate, toDate ti
return transactions, int64(count), nil
}
-func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.EndpointStats, int64, error) {
+func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, projectId string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.EndpointStats, int64, error) {
// Count unique endpoints
var count uint64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(endpoint) FROM transactions WHERE recorded_at >= ? AND recorded_at <= ?", fromDate, toDate).Scan(&count)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT uniq(endpoint) FROM transactions WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, fromDate, toDate).Scan(&count)
if err != nil {
return nil, 0, err
}
@@ -97,12 +97,12 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, fromD
avg(duration) as avg_duration,
max(recorded_at) as last_seen
FROM transactions
- WHERE recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY endpoint
ORDER BY ` + orderBy + ` DESC
LIMIT ? OFFSET ?`
- rows, err := (*chdb.Conn).Query(ctx, query, fromDate, toDate, pageSize, offset)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, fromDate, toDate, pageSize, offset)
if err != nil {
return nil, 0, err
}
@@ -124,9 +124,9 @@ func (e *transactionRepository) FindGroupedByEndpoint(ctx context.Context, fromD
return stats, int64(count), nil
}
-func (e *transactionRepository) FindByEndpoint(ctx context.Context, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {
+func (e *transactionRepository) FindByEndpoint(ctx context.Context, projectId string, endpoint string, fromDate, toDate time.Time, page, pageSize int, orderBy string) ([]models.Transaction, int64, error) {
var count uint64
- err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", endpoint, fromDate, toDate).Scan(&count)
+ err := (*chdb.Conn).QueryRow(ctx, "SELECT count() FROM transactions WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ?", projectId, endpoint, fromDate, toDate).Scan(&count)
if err != nil {
return nil, 0, err
}
@@ -144,8 +144,8 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, endpoint str
orderBy = "recorded_at"
}
- query := "SELECT id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"
- rows, err := (*chdb.Conn).Query(ctx, query, endpoint, fromDate, toDate, pageSize, offset)
+ query := "SELECT id, project_id, endpoint, duration, recorded_at, status_code, body_size, client_ip FROM transactions WHERE project_id = ? AND endpoint = ? AND recorded_at >= ? AND recorded_at <= ? ORDER BY " + orderBy + " DESC LIMIT ? OFFSET ?"
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, endpoint, fromDate, toDate, pageSize, offset)
if err != nil {
return nil, 0, err
}
@@ -154,7 +154,7 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, endpoint str
var transactions []models.Transaction
for rows.Next() {
var t models.Transaction
- if err := rows.Scan(&t.Id, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {
+ if err := rows.Scan(&t.Id, &t.ProjectId, &t.Endpoint, &t.Duration, &t.RecordedAt, &t.StatusCode, &t.BodySize, &t.ClientIP); err != nil {
return nil, 0, err
}
transactions = append(transactions, t)
@@ -164,16 +164,16 @@ func (e *transactionRepository) FindByEndpoint(ctx context.Context, endpoint str
}
// CountByHour returns transaction counts grouped by hour
-func (e *transactionRepository) CountByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {
+func (e *transactionRepository) CountByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
query := `SELECT
toStartOfHour(recorded_at) as hour,
count() as count
FROM transactions
- WHERE recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY hour
ORDER BY hour ASC`
- rows, err := (*chdb.Conn).Query(ctx, query, start, end)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)
if err != nil {
return nil, err
}
@@ -192,16 +192,16 @@ func (e *transactionRepository) CountByHour(ctx context.Context, start, end time
}
// AvgDurationByHour returns average response time in ms grouped by hour
-func (e *transactionRepository) AvgDurationByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {
+func (e *transactionRepository) AvgDurationByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
query := `SELECT
toStartOfHour(recorded_at) as hour,
avg(duration) / 1000000 as avg_duration_ms
FROM transactions
- WHERE recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY hour
ORDER BY hour ASC`
- rows, err := (*chdb.Conn).Query(ctx, query, start, end)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)
if err != nil {
return nil, err
}
@@ -220,16 +220,16 @@ func (e *transactionRepository) AvgDurationByHour(ctx context.Context, start, en
}
// ErrorRateByHour returns error rate (percentage) grouped by hour
-func (e *transactionRepository) ErrorRateByHour(ctx context.Context, start, end time.Time) ([]models.TimeSeriesPoint, error) {
+func (e *transactionRepository) ErrorRateByHour(ctx context.Context, projectId string, start, end time.Time) ([]models.TimeSeriesPoint, error) {
query := `SELECT
toStartOfHour(recorded_at) as hour,
countIf(status_code >= 400) * 100.0 / count() as error_rate
FROM transactions
- WHERE recorded_at >= ? AND recorded_at <= ?
+ WHERE project_id = ? AND recorded_at >= ? AND recorded_at <= ?
GROUP BY hour
ORDER BY hour ASC`
- rows, err := (*chdb.Conn).Query(ctx, query, start, end)
+ rows, err := (*chdb.Conn).Query(ctx, query, projectId, start, end)
if err != nil {
return nil, err
}
diff --git a/backend/main.go b/backend/main.go
index a2996e4a..a19f61e2 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -1,10 +1,12 @@
package main
import (
+ "backend/app/cache"
"backend/app/chdb"
"backend/app/controllers"
"backend/app/middleware"
"backend/app/migrations"
+ "context"
"log"
"github.com/gin-gonic/gin"
@@ -27,6 +29,12 @@ func main() {
panic(err)
}
+ // Initialize project cache
+ ctx := context.Background()
+ if err := cache.ProjectCache.Init(ctx); err != nil {
+ panic(err)
+ }
+
middleware.InitUseClientAuth()
router := gin.Default()
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 0b9b3681..7d355f92 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -2,7 +2,12 @@ import { authState } from './state/auth.svelte';
const BASE_URL = '/api';
-async function request(method: string, endpoint: string, data?: any) {
+interface RequestOptions {
+ projectId?: string;
+ skipProjectId?: boolean;
+}
+
+async function request(method: string, endpoint: string, data?: unknown, options?: RequestOptions) {
const currentToken = authState.token;
const headers: Record<string, string> = {
'Content-Type': 'application/json'
@@ -17,11 +22,23 @@ async function request(method: string, endpoint: string, data?: any) {
headers,
};
+ // For POST/PUT requests, add projectId to the body if provided
+ if (data && options?.projectId && !options?.skipProjectId) {
+ data = { ...data as object, projectId: options.projectId };
+ }
+
if (data) {
config.body = JSON.stringify(data);
}
- const response = await fetch(`${BASE_URL}${endpoint}`, config);
+ // For GET requests, add projectId as query parameter if provided
+ let url = `${BASE_URL}${endpoint}`;
+ if (method === 'GET' && options?.projectId && !options?.skipProjectId) {
+ const separator = endpoint.includes('?') ? '&' : '?';
+ url = `${url}${separator}projectId=${options.projectId}`;
+ }
+
+ const response = await fetch(url, config);
if (response.status === 401) {
authState.logout();
@@ -39,8 +56,8 @@ async function request(method: string, endpoint: string, data?: any) {
}
export const api = {
- get: (endpoint: string) => request('GET', endpoint),
- post: (endpoint: string, data: any) => request('POST', endpoint, data),
- put: (endpoint: string, data: any) => request('PUT', endpoint, data),
- delete: (endpoint: string) => request('DELETE', endpoint)
+ get: (endpoint: string, options?: RequestOptions) => request('GET', endpoint, undefined, options),
+ post: (endpoint: string, data: unknown, options?: RequestOptions) => request('POST', endpoint, data, options),
+ put: (endpoint: string, data: unknown, options?: RequestOptions) => request('PUT', endpoint, data, options),
+ delete: (endpoint: string, options?: RequestOptions) => request('DELETE', endpoint, undefined, options)
};
diff --git a/frontend/src/lib/components/add-project-modal.svelte b/frontend/src/lib/components/add-project-modal.svelte
new file mode 100644
index 00000000..f7246856
--- /dev/null
+++ b/frontend/src/lib/components/add-project-modal.svelte
@@ -0,0 +1,221 @@
+<script lang="ts">
+ import * as Sheet from "$lib/components/ui/sheet";
+ import * as Select from "$lib/components/ui/select";
+ import { Button } from "$lib/components/ui/button";
+ import { Input } from "$lib/components/ui/input";
+ import { Label } from "$lib/components/ui/label";
+ import { projectsState, type ProjectWithToken, type Framework } from '$lib/state/projects.svelte';
+ import { Copy, Check, ExternalLink } from 'lucide-svelte';
+ import FrameworkIcon from './framework-icon.svelte';
+
+ interface Props {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onProjectCreated: () => void;
+ }
+
+ let { open, onOpenChange, onProjectCreated }: Props = $props();
+
+ let projectName = $state('');
+ let selectedFramework = $state<Framework>('gin');
+ let loading = $state(false);
+ let error = $state('');
+ let createdProject = $state<ProjectWithToken | null>(null);
+ let copied = $state(false);
+
+ // Framework options with labels
+ const frameworks = [
+ { value: 'gin', label: 'Gin', description: 'Fast HTTP web framework' },
+ { value: 'fiber', label: 'Fiber', description: 'Express-inspired framework' },
+ { value: 'chi', label: 'Chi', description: 'Lightweight router' },
+ { value: 'fasthttp', label: 'FastHTTP', description: 'High-performance HTTP' },
+ { value: 'stdlib', label: 'Standard Library', description: 'net/http package' },
+ { value: 'custom', label: 'Custom', description: 'Other / manual setup' },
+ ] as const;
+
+ const selectedFrameworkLabel = $derived(
+ frameworks.find(f => f.value === selectedFramework)?.label ?? 'Select framework'
+ );
+
+ async function handleSubmit(e: Event) {
+ e.preventDefault();
+ if (!projectName.trim()) {
+ error = 'Project name is required';
+ return;
+ }
+
+ loading = true;
+ error = '';
+
+ try {
+ const project = await projectsState.createProject(projectName.trim(), selectedFramework);
+ createdProject = project;
+ } catch (err) {
+ error = err instanceof Error ? err.message : 'Failed to create project';
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function copyToken() {
+ if (createdProject?.token) {
+ await navigator.clipboard.writeText(createdProject.token);
+ copied = true;
+ setTimeout(() => copied = false, 2000);
+ }
+ }
+
+ function handleClose() {
+ projectName = '';
+ selectedFramework = 'gin';
+ error = '';
+ createdProject = null;
+ onOpenChange(false);
+ }
+
+ function handleGoToConnection() {
+ if (createdProject) {
+ projectsState.selectProject(createdProject.id);
+ }
+ handleClose();
+ onProjectCreated();
+ }
+</script>
+
+<Sheet.Root {open} onOpenChange={handleClose}>
+ <Sheet.Content side="right" class="w-[400px] sm:w-[540px]">
+ <Sheet.Header>
+ <Sheet.Title>
+ {#if createdProject}
+ Project Created!
+ {:else}
+ Create New Project
+ {/if}
+ </Sheet.Title>
+ <Sheet.Description>
+ {#if createdProject}
+ Your project has been created. Save the token below - you'll need it to connect your application.
+ {:else}
+ Add a new project to start tracking errors and metrics.
+ {/if}
+ </Sheet.Description>
+ </Sheet.Header>
+
+ {#if createdProject}
+ <div class="px-6 py-6 space-y-6">
+ <div class="space-y-2">
+ <Label>Project Name</Label>
+ <div class="text-lg font-medium">{createdProject.name}</div>
+ </div>
+
+ <div class="space-y-2">
+ <Label>Framework</Label>
+ <div class="flex items-center gap-2 text-sm text-muted-foreground">
+ <FrameworkIcon framework={selectedFramework} />
+ <span>{selectedFrameworkLabel}</span>
+ </div>
+ </div>
+
+ <div class="space-y-2">
+ <Label>Project Token</Label>
+ <div class="flex gap-2">
+ <Input
+ type="text"
+ value={createdProject.token}
+ readonly
+ class="font-mono text-sm"
+ />
+ <Button variant="outline" size="icon" onclick={copyToken}>
+ {#if copied}
+ <Check class="h-4 w-4 text-green-500" />
+ {:else}
+ <Copy class="h-4 w-4" />
+ {/if}
+ </Button>
+ </div>
+ <p class="text-sm text-muted-foreground">
+ This token will only be shown once. Make sure to save it securely.
+ </p>
+ </div>
+ </div>
+
+ <div class="flex justify-end gap-2 px-6 pb-6">
+ <Button variant="outline" onclick={handleClose}>
+ Close
+ </Button>
+ <Button onclick={handleGoToConnection}>
+ <ExternalLink class="mr-2 h-4 w-4" />
+ Go to Connection
+ </Button>
+ </div>
+ {:else}
+ <form onsubmit={handleSubmit} class="px-6 py-6 space-y-5">
+ <div class="space-y-2">
+ <Label for="project-name">Project Name</Label>
+ <Input
+ id="project-name"
+ type="text"
+ placeholder="My Application"
+ bind:value={projectName}
+ disabled={loading}
+ />
+ <p class="text-xs text-muted-foreground">
+ A unique name for your project (letters, numbers, spaces, hyphens)
+ </p>
+ </div>
+
+ <div class="space-y-2">
+ <Label for="framework">Framework</Label>
+ <Select.Root type="single" bind:value={selectedFramework}>
+ <Select.Trigger class="w-full">
+ <div class="flex items-center gap-2">
+ <FrameworkIcon framework={selectedFramework} />
+ <span>{selectedFrameworkLabel}</span>
+ </div>
+ </Select.Trigger>
+ <Select.Content>
+ {#each frameworks as framework}
+ <Select.Item value={framework.value}>
+ {#snippet children({ selected })}
+ <div class="flex items-center gap-2">
+ <FrameworkIcon framework={framework.value} />
+ <div class="flex flex-col">
+ <span class="font-medium">{framework.label}</span>
+ <span class="text-xs text-muted-foreground">{framework.description}</span>
+ </div>
+ </div>
+ {#if selected}
+ <Check class="absolute end-2 size-4" />
+ {/if}
+ {/snippet}
+ </Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ <p class="text-xs text-muted-foreground">
+ Select your Go web framework for tailored integration code
+ </p>
+ </div>
+
+ {#if error}
+ <div class="rounded-md bg-destructive/10 border border-destructive/20 p-3">
+ <p class="text-sm text-destructive">{error}</p>
+ </div>
+ {/if}
+
+ <div class="flex justify-end gap-2 pt-2">
+ <Button type="button" variant="outline" onclick={handleClose} disabled={loading}>
+ Cancel
+ </Button>
+ <Button type="submit" disabled={loading || !projectName.trim()}>
+ {#if loading}
+ Creating...
+ {:else}
+ Create Project
+ {/if}
+ </Button>
+ </div>
+ </form>
+ {/if}
+ </Sheet.Content>
+</Sheet.Root>
diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelte
index e62a4fa2..c3085a19 100644
--- a/frontend/src/lib/components/app-sidebar.svelte
+++ b/frontend/src/lib/components/app-sidebar.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import * as Sidebar from "$lib/components/ui/sidebar";
- import { List, Bug, Gauge } from "@lucide/svelte";
+ import { List, Bug, Link2 } from "@lucide/svelte";
import { themeState } from '$lib/state/theme.svelte';
import { LayoutDashboard } from "@lucide/svelte";
import { page } from '$app/state';
@@ -10,6 +10,7 @@
{Icon: LayoutDashboard, href: "/", title: "Dashboard"},
{Icon: Bug, href: "/issues", title: "Issues"},
{Icon: List, href: "/transactions", title: "Transactions"},
+ {Icon: Link2, href: "/connection", title: "Connection"},
]
</script>
diff --git a/frontend/src/lib/components/framework-icon.svelte b/frontend/src/lib/components/framework-icon.svelte
new file mode 100644
index 00000000..7d351e0d
--- /dev/null
+++ b/frontend/src/lib/components/framework-icon.svelte
@@ -0,0 +1,28 @@
+<script lang="ts">
+ import type { Framework } from '$lib/state/projects.svelte';
+
+ interface Props {
+ framework: Framework | string;
+ class?: string;
+ }
+
+ let { framework, class: className = 'size-4 shrink-0' }: Props = $props();
+</script>
+
+{#if framework === 'gin'}
+ <img src="/gin.png" alt="Gin" class={className} />
+{:else if framework === 'fiber'}
+ <svg class={className} viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <rect x="1" y="3" width="10" height="2.5" rx="0.5" fill="#00ACD7"/>
+ <rect x="1" y="6.75" width="14" height="2.5" rx="0.5" fill="#00ACD7"/>
+ <rect x="1" y="10.5" width="6" height="2.5" rx="0.5" fill="#00ACD7"/>
+ </svg>
+{:else if framework === 'chi'}
+ <img src="/chi.png" alt="Chi" class={className} />
+{:else if framework === 'fasthttp'}
+ <img src="/fasthttp.png" alt="FastHTTP" class={className} />
+{:else if framework === 'stdlib'}
+ <img src="/stdlib.png" alt="Standard Library" class={className} />
+{:else}
+ <img src="/custom.png" alt="Custom" class={className} />
+{/if}
diff --git a/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte b/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte
new file mode 100644
index 00000000..27d7ebbb
--- /dev/null
+++ b/frontend/src/lib/components/ui/datetime-picker/datetime-picker.svelte
@@ -0,0 +1,270 @@
+<script lang="ts">
+ import { Calendar } from "$lib/components/ui/calendar";
+ import * as Select from "$lib/components/ui/select";
+ import { cn } from "$lib/utils";
+ import { CalendarDate, CalendarDateTime, getLocalTimeZone, today, type DateValue } from "@internationalized/date";
+
+ type Period = 'AM' | 'PM';
+
+ interface Props {
+ value?: CalendarDateTime | CalendarDate;
+ onValueChange?: (value: CalendarDateTime) => void;
+ class?: string;
+ }
+
+ let {
+ value = $bindable(),
+ onValueChange,
+ class: className
+ }: Props = $props();
+
+ // Time state (12-hour format for display)
+ let hours = $state(12);
+ let minutes = $state(0);
+ let seconds = $state(0);
+ let period = $state<Period>('AM');
+
+ // Initialize from value
+ $effect(() => {
+ if (value && 'hour' in value) {
+ const hour24 = value.hour;
+ period = hour24 >= 12 ? 'PM' : 'AM';
+ hours = hour24 % 12 || 12;
+ minutes = value.minute;
+ seconds = value.second;
+ }
+ });
+
+ // Derived 24-hour value
+ const hour24 = $derived(() => {
+ if (period === 'AM') {
+ return hours === 12 ? 0 : hours;
+ } else {
+ return hours === 12 ? 12 : hours + 12;
+ }
+ });
+
+ // Handle calendar date change
+ function handleDateChange(newDate: DateValue | undefined) {
+ if (!newDate) return;
+
+ const dateTime = new CalendarDateTime(
+ newDate.year,
+ newDate.month,
+ newDate.day,
+ hour24(),
+ minutes,
+ seconds
+ );
+
+ value = dateTime;
+ onValueChange?.(dateTime);
+ }
+
+ // Handle time changes
+ function updateDateTime() {
+ if (!value) {
+ const now = today(getLocalTimeZone());
+ value = new CalendarDateTime(now.year, now.month, now.day, hour24(), minutes, seconds);
+ } else {
+ const dateTime = new CalendarDateTime(
+ value.year,
+ value.month,
+ value.day,
+ hour24(),
+ minutes,
+ seconds
+ );
+ value = dateTime;
+ onValueChange?.(dateTime);
+ }
+ }
+
+ // Input handlers with validation
+ function handleHoursInput(e: Event) {
+ const input = e.target as HTMLInputElement;
+ let val = parseInt(input.value) || 0;
+ if (val < 1) val = 1;
+ if (val > 12) val = 12;
+ hours = val;
+ input.value = String(val).padStart(2, '0');
+ updateDateTime();
+ }
+
+ function handleMinutesInput(e: Event) {
+ const input = e.target as HTMLInputElement;
+ let val = parseInt(input.value) || 0;
+ if (val < 0) val = 0;
+ if (val > 59) val = 59;
+ minutes = val;
+ input.value = String(val).padStart(2, '0');
+ updateDateTime();
+ }
+
+ function handleSecondsInput(e: Event) {
+ const input = e.target as HTMLInputElement;
+ let val = parseInt(input.value) || 0;
+ if (val < 0) val = 0;
+ if (val > 59) val = 59;
+ seconds = val;
+ input.value = String(val).padStart(2, '0');
+ updateDateTime();
+ }
+
+ function handlePeriodChange(newPeriod: string | undefined) {
+ if (newPeriod === 'AM' || newPeriod === 'PM') {
+ period = newPeriod;
+ updateDateTime();
+ }
+ }
+
+ // Increment/decrement helpers
+ function incrementHours() {
+ hours = hours >= 12 ? 1 : hours + 1;
+ updateDateTime();
+ }
+
+ function decrementHours() {
+ hours = hours <= 1 ? 12 : hours - 1;
+ updateDateTime();
+ }
+
+ function incrementMinutes() {
+ if (minutes >= 59) {
+ minutes = 0;
+ incrementHours();
+ } else {
+ minutes++;
+ }
+ updateDateTime();
+ }
+
+ function decrementMinutes() {
+ if (minutes <= 0) {
+ minutes = 59;
+ decrementHours();
+ } else {
+ minutes--;
+ }
+ updateDateTime();
+ }
+
+ function incrementSeconds() {
+ if (seconds >= 59) {
+ seconds = 0;
+ incrementMinutes();
+ } else {
+ seconds++;
+ }
+ updateDateTime();
+ }
+
+ function decrementSeconds() {
+ if (seconds <= 0) {
+ seconds = 59;
+ decrementMinutes();
+ } else {
+ seconds--;
+ }
+ updateDateTime();
+ }
+
+ // Handle keyboard navigation
+ function handleKeyDown(e: KeyboardEvent, field: 'hours' | 'minutes' | 'seconds') {
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (field === 'hours') incrementHours();
+ else if (field === 'minutes') incrementMinutes();
+ else incrementSeconds();
+ } else if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ if (field === 'hours') decrementHours();
+ else if (field === 'minutes') decrementMinutes();
+ else decrementSeconds();
+ }
+ }
+
+ // Get calendar-compatible date value
+ const calendarValue = $derived(() => {
+ if (!value) return undefined;
+ return new CalendarDate(value.year, value.month, value.day);
+ });
+</script>
+
+<div class={cn("flex flex-col", className)}>
+ <!-- Calendar -->
+ <Calendar
+ type="single"
+ value={calendarValue()}
+ onValueChange={handleDateChange}
+ />
+
+ <!-- Time Picker -->
+ <div class="border-t px-3 py-3">
+ <div class="flex items-end gap-2">
+ <!-- Hours -->
+ <div class="flex flex-col items-center gap-1">
+ <span class="text-xs text-muted-foreground">Hours</span>
+ <input
+ type="text"
+ inputmode="numeric"
+ class="w-10 h-9 text-center text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring tabular-nums"
+ value={String(hours).padStart(2, '0')}
+ onchange={handleHoursInput}
+ onkeydown={(e) => handleKeyDown(e, 'hours')}
+ maxlength={2}
+ />
+ </div>
+
+ <span class="text-sm font-medium text-muted-foreground pb-1">:</span>
+
+ <!-- Minutes -->
+ <div class="flex flex-col items-center gap-1">
+ <span class="text-xs text-muted-foreground">Minutes</span>
+ <input
+ type="text"
+ inputmode="numeric"
+ class="w-10 h-9 text-center text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring tabular-nums"
+ value={String(minutes).padStart(2, '0')}
+ onchange={handleMinutesInput}
+ onkeydown={(e) => handleKeyDown(e, 'minutes')}
+ maxlength={2}
+ />
+ </div>
+
+ <span class="text-sm font-medium text-muted-foreground pb-1">:</span>
+
+ <!-- Seconds -->
+ <div class="flex flex-col items-center gap-1">
+ <span class="text-xs text-muted-foreground">Seconds</span>
+ <input
+ type="text"
+ inputmode="numeric"
+ class="w-10 h-9 text-center text-sm border rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring tabular-nums"
+ value={String(seconds).padStart(2, '0')}
+ onchange={handleSecondsInput}
+ onkeydown={(e) => handleKeyDown(e, 'seconds')}
+ maxlength={2}
+ />
+ </div>
+
+ <!-- Period (AM/PM) -->
+ <div class="flex flex-col items-center gap-1">
+ <span class="text-xs text-muted-foreground">Period</span>
+ <Select.Root
+ type="single"
+ value={period}
+ onValueChange={handlePeriodChange}
+ >
+ <Select.Trigger class="w-[60px] h-9 text-sm">
+ {period}
+ </Select.Trigger>
+ <Select.Content>
+ <Select.Item value="AM" label="AM">AM</Select.Item>
+ <Select.Item value="PM" label="PM">PM</Select.Item>
+ </Select.Content>
+ </Select.Root>
+ </div>
+ </div>
+ </div>
+</div>
diff --git a/frontend/src/lib/components/ui/datetime-picker/index.ts b/frontend/src/lib/components/ui/datetime-picker/index.ts
new file mode 100644
index 00000000..07bc6beb
--- /dev/null
+++ b/frontend/src/lib/components/ui/datetime-picker/index.ts
@@ -0,0 +1,3 @@
+import DateTimePicker from "./datetime-picker.svelte";
+
+export { DateTimePicker };
diff --git a/frontend/src/lib/components/ui/time-range-picker/index.ts b/frontend/src/lib/components/ui/time-range-picker/index.ts
new file mode 100644
index 00000000..2fb89ba2
--- /dev/null
+++ b/frontend/src/lib/components/ui/time-range-picker/index.ts
@@ -0,0 +1,3 @@
+import TimeRangePicker from "./time-range-picker.svelte";
+
+export { TimeRangePicker };
diff --git a/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte
new file mode 100644
index 00000000..8a181dc2
--- /dev/null
+++ b/frontend/src/lib/components/ui/time-range-picker/time-range-picker.svelte
@@ -0,0 +1,291 @@
+<script lang="ts">
+ import { Button } from "$lib/components/ui/button";
+ import { DateTimePicker } from "$lib/components/ui/datetime-picker";
+ import * as Popover from "$lib/components/ui/popover";
+ import { Clock, ChevronDown, ChevronRight, Check } from "@lucide/svelte";
+ import { CalendarDate, CalendarDateTime, getLocalTimeZone, today } from "@internationalized/date";
+
+ type TimeRangePreset = {
+ value: string;
+ label: string;
+ minutes: number;
+ };
+
+ type PresetGroup = {
+ presets: TimeRangePreset[];
+ };
+
+ interface Props {
+ fromDate?: CalendarDate;
+ toDate?: CalendarDate;
+ fromTime?: string;
+ toTime?: string;
+ onApply?: (from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) => void;
+ }
+
+ let {
+ fromDate = $bindable(today(getLocalTimeZone()).subtract({ days: 7 })),
+ toDate = $bindable(today(getLocalTimeZone())),
+ fromTime = $bindable('00:00'),
+ toTime = $bindable('23:59'),
+ onApply
+ }: Props = $props();
+
+ // Preset groups
+ const presetGroups: PresetGroup[] = [
+ {
+ presets: [
+ { value: '30m', label: '30 minutes', minutes: 30 },
+ { value: '60m', label: '60 minutes', minutes: 60 },
+ ]
+ },
+ {
+ presets: [
+ { value: '3h', label: '3 hours', minutes: 180 },
+ { value: '6h', label: '6 hours', minutes: 360 },
+ { value: '12h', label: '12 hours', minutes: 720 },
+ { value: '24h', label: '24 hours', minutes: 1440 },
+ ]
+ },
+ {
+ presets: [
+ { value: '3d', label: '3 days', minutes: 4320 },
+ { value: '7d', label: '7 days', minutes: 10080 },
+ ]
+ },
+ {
+ presets: [
+ { value: '1M', label: '1 month', minutes: 43200 },
+ { value: '3M', label: '3 months', minutes: 129600 },
+ ]
+ }
+ ];
+
+ let isOpen = $state(false);
+ let showCustom = $state(false);
+ let selectedPreset = $state<string | null>('7d');
+
+ // DateTime picker popover states
+ let fromPickerOpen = $state(false);
+ let toPickerOpen = $state(false);
+
+ // Temporary CalendarDateTime values for custom selection
+ let tempFromDateTime = $state<CalendarDateTime>(
+ new CalendarDateTime(fromDate.year, fromDate.month, fromDate.day, 0, 0, 0)
+ );
+ let tempToDateTime = $state<CalendarDateTime>(
+ new CalendarDateTime(toDate.year, toDate.month, toDate.day, 23, 59, 59)
+ );
+
+ // Get display label for trigger button
+ const displayLabel = $derived(() => {
+ if (selectedPreset && !showCustom) {
+ const preset = presetGroups.flatMap(g => g.presets).find(p => p.value === selectedPreset);
+ return preset ? `Last ${preset.label}` : 'Select time range';
+ }
+ // For custom selection, show date and time range (no prefix)
+ if (tempFromDateTime && tempToDateTime) {
+ const fromDateStr = formatDateShort(tempFromDateTime);
+ const fromTimeStr = formatTime12h(tempFromDateTime);
+ const toDateStr = formatDateShort(tempToDateTime);
+ const toTimeStr = formatTime12h(tempToDateTime);
+ return `${fromDateStr} ${fromTimeStr} – ${toDateStr} ${toTimeStr}`;
+ }
+ return 'Select time range';
+ });
+
+ function formatDateShort(dt: CalendarDateTime): string {
+ return new CalendarDate(dt.year, dt.month, dt.day)
+ .toDate(getLocalTimeZone())
+ .toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
+ }
+
+ // YY/MM/DD format for compact display
+ function formatDateCompact(dt: CalendarDateTime): string {
+ const year = String(dt.year).slice(-2);
+ const month = String(dt.month).padStart(2, '0');
+ const day = String(dt.day).padStart(2, '0');
+ return `${year}/${month}/${day}`;
+ }
+
+ // Format time as 12h with AM/PM
+ function formatTime12h(dt: CalendarDateTime): string {
+ const hours = dt.hour;
+ const minutes = dt.minute;
+ const period = hours >= 12 ? 'PM' : 'AM';
+ const hours12 = hours % 12 || 12;
+ return `${hours12}:${String(minutes).padStart(2, '0')} ${period}`;
+ }
+
+ function selectPreset(preset: TimeRangePreset) {
+ selectedPreset = preset.value;
+ showCustom = false;
+
+ // Calculate the date range for this preset
+ const now = new Date();
+ const fromDateTime = new Date(now.getTime() - preset.minutes * 60 * 1000);
+
+ // Update temp values only - don't close or apply yet
+ tempFromDateTime = new CalendarDateTime(
+ fromDateTime.getFullYear(),
+ fromDateTime.getMonth() + 1,
+ fromDateTime.getDate(),
+ fromDateTime.getHours(),
+ fromDateTime.getMinutes(),
+ fromDateTime.getSeconds()
+ );
+ tempToDateTime = new CalendarDateTime(
+ now.getFullYear(),
+ now.getMonth() + 1,
+ now.getDate(),
+ now.getHours(),
+ now.getMinutes(),
+ now.getSeconds()
+ );
+ }
+
+ function toggleCustom() {
+ showCustom = !showCustom;
+ if (showCustom) {
+ selectedPreset = null;
+ }
+ }
+
+ function resetToNow() {
+ const now = new Date();
+ tempToDateTime = new CalendarDateTime(
+ now.getFullYear(), now.getMonth() + 1, now.getDate(),
+ now.getHours(), now.getMinutes(), now.getSeconds()
+ );
+ }
+
+ function handleOpenChange(open: boolean) {
+ // Auto-apply when closing (both presets and custom)
+ if (!open) {
+ fromDate = new CalendarDate(tempFromDateTime.year, tempFromDateTime.month, tempFromDateTime.day);
+ toDate = new CalendarDate(tempToDateTime.year, tempToDateTime.month, tempToDateTime.day);
+ fromTime = `${String(tempFromDateTime.hour).padStart(2, '0')}:${String(tempFromDateTime.minute).padStart(2, '0')}`;
+ toTime = `${String(tempToDateTime.hour).padStart(2, '0')}:${String(tempToDateTime.minute).padStart(2, '0')}`;
+ onApply?.({ date: fromDate, time: fromTime }, { date: toDate, time: toTime });
+
+ // Keep showCustom state (don't reset it) so it remembers custom mode
+ fromPickerOpen = false;
+ toPickerOpen = false;
+ }
+ isOpen = open;
+ }
+
+ function handleFromDateTimeChange(dt: CalendarDateTime) {
+ tempFromDateTime = dt;
+ }
+
+ function handleToDateTimeChange(dt: CalendarDateTime) {
+ tempToDateTime = dt;
+ }
+</script>
+
+<Popover.Root bind:open={isOpen} onOpenChange={handleOpenChange}>
+ <Popover.Trigger>
+ <Button variant="outline" class="h-9 min-w-[340px] justify-between gap-2 font-normal">
+ <span class="flex items-center gap-2">
+ <Clock class="h-4 w-4 text-muted-foreground" />
+ <span class="truncate">{displayLabel()}</span>
+ </span>
+ <ChevronDown class="h-4 w-4 text-muted-foreground" />
+ </Button>
+ </Popover.Trigger>
+ <Popover.Content class="w-auto p-0" align="start">
+ <div class="flex">
+ <!-- Presets Column -->
+ <div class="w-[140px] border-r py-2">
+ {#each presetGroups as group, groupIndex}
+ {#if groupIndex > 0}
+ <div class="my-1 border-t mx-2"></div>
+ {/if}
+ {#each group.presets as preset}
+ <button
+ class="w-full px-3 py-1.5 text-left text-sm hover:bg-muted/50 flex items-center justify-between transition-colors {selectedPreset === preset.value && !showCustom ? 'bg-muted' : ''}"
+ onclick={() => selectPreset(preset)}
+ >
+ <span>{preset.label}</span>
+ {#if selectedPreset === preset.value && !showCustom}
+ <Check class="h-4 w-4 text-primary" />
+ {/if}
+ </button>
+ {/each}
+ {/each}
+ <div class="my-1 border-t mx-2"></div>
+ <button
+ class="w-full px-3 py-1.5 text-left text-sm hover:bg-muted/50 flex items-center justify-between transition-colors {showCustom ? 'bg-muted' : ''}"
+ onclick={toggleCustom}
+ >
+ <span>Set custom</span>
+ <ChevronRight class="h-4 w-4 text-muted-foreground" />
+ </button>
+ </div>
+
+ <!-- Custom Section -->
+ {#if showCustom}
+ <div class="p-5 min-w-[380px]">
+ <div class="flex items-center justify-between mb-3">
+ <span class="text-xs font-medium text-muted-foreground uppercase tracking-wide">Custom</span>
+ <button
+ class="text-xs text-primary hover:underline"
+ onclick={resetToNow}
+ >
+ Reset to now
+ </button>
+ </div>
+
+ <!-- Compact Date/Time Inputs Row -->
+ <div class="flex items-center gap-2 mb-4">
+ <!-- From DateTime -->
+ <Popover.Root bind:open={fromPickerOpen}>
+ <Popover.Trigger>
+ <button
+ class="h-9 px-3 text-sm border rounded-md text-left hover:bg-muted/50 transition-colors flex items-center gap-2 {fromPickerOpen ? 'ring-2 ring-ring' : ''}"
+ >
+ <span class="tabular-nums">{formatDateCompact(tempFromDateTime)}</span>
+ <span class="text-muted-foreground tabular-nums">{formatTime12h(tempFromDateTime)}</span>
+ </button>
+ </Popover.Trigger>
+ <Popover.Content class="w-auto p-0" align="start">
+ <DateTimePicker
+ value={tempFromDateTime}
+ onValueChange={handleFromDateTimeChange}
+ />
+ </Popover.Content>
+ </Popover.Root>
+
+ <span class="text-muted-foreground text-xs">–</span>
+
+ <!-- To DateTime -->
+ <Popover.Root bind:open={toPickerOpen}>
+ <Popover.Trigger>
+ <button
+ class="h-9 px-3 text-sm border rounded-md text-left hover:bg-muted/50 transition-colors flex items-center gap-2 {toPickerOpen ? 'ring-2 ring-ring' : ''}"
+ >
+ <span class="tabular-nums">{formatDateCompact(tempToDateTime)}</span>
+ <span class="text-muted-foreground tabular-nums">{formatTime12h(tempToDateTime)}</span>
+ </button>
+ </Popover.Trigger>
+ <Popover.Content class="w-auto p-0" align="start">
+ <DateTimePicker
+ value={tempToDateTime}
+ onValueChange={handleToDateTimeChange}
+ />
+ </Popover.Content>
+ </Popover.Root>
+ </div>
+
+ <!-- Apply button -->
+ <div class="flex justify-end pt-2">
+ <Button size="sm" onclick={() => isOpen = false}>
+ Apply
+ </Button>
+ </div>
+ </div>
+ {/if}
+ </div>
+ </Popover.Content>
+</Popover.Root>
diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.ts
new file mode 100644
index 00000000..65c89d5b
--- /dev/null
+++ b/frontend/src/lib/state/projects.svelte.ts
@@ -0,0 +1,95 @@
+import { api } from '$lib/api';
+
+export type Framework = 'gin' | 'fiber' | 'chi' | 'fasthttp' | 'stdlib' | 'custom';
+
+export interface Project {
+ id: string;
+ name: string;
+ framework: Framework;
+ createdAt: string;
+}
+
+export interface ProjectWithToken extends Project {
+ token: string;
+}
+
+class ProjectsState {
+ projects = $state<Project[]>([]);
+ currentProjectId = $state<string | null>(localStorage.getItem('CURRENT_PROJECT_ID'));
+ loading = $state(false);
+ error = $state<string | null>(null);
+
+ currentProject = $derived(
+ this.projects.find(p => p.id === this.currentProjectId) || this.projects[0] || null
+ );
+
+ constructor() {
+ $effect.root(() => {
+ $effect(() => {
+ if (this.currentProjectId) {
+ localStorage.setItem('CURRENT_PROJECT_ID', this.currentProjectId);
+ } else {
+ localStorage.removeItem('CURRENT_PROJECT_ID');
+ }
+ });
+ });
+ }
+
+ async loadProjects() {
+ this.loading = true;
+ this.error = null;
+
+ try {
+ const response = await api.get('/projects');
+ this.projects = response;
+
+ // If no current project selected or current project not in list, select first one
+ if (!this.currentProjectId || !this.projects.find(p => p.id === this.currentProjectId)) {
+ if (this.projects.length > 0) {
+ this.currentProjectId = this.projects[0].id;
+ }
+ }
+
+ // Cache in localStorage
+ localStorage.setItem('PROJECTS_CACHE', JSON.stringify(this.projects));
+ } catch (e: unknown) {
+ const errorMessage = e instanceof Error ? e.message : 'Failed to load projects';
+ this.error = errorMessage;
+
+ // Try to load from cache
+ const cached = localStorage.getItem('PROJECTS_CACHE');
+ if (cached) {
+ this.projects = JSON.parse(cached);
+ }
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ async createProject(name: string, framework: Framework = 'gin'): Promise<ProjectWithToken> {
+ const response = await api.post('/projects', { name, framework });
+
+ // Reload projects to refresh cache
+ await this.loadProjects();
+
+ return response;
+ }
+
+ async getProjectWithToken(id: string): Promise<ProjectWithToken> {
+ return await api.get(`/projects/${id}`);
+ }
+
+ selectProject(projectId: string) {
+ this.currentProjectId = projectId;
+ }
+
+ // Initialize from localStorage cache on startup
+ initFromCache() {
+ const cached = localStorage.getItem('PROJECTS_CACHE');
+ if (cached) {
+ this.projects = JSON.parse(cached);
+ }
+ }
+}
+
+export const projectsState = new ProjectsState();
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index 9c597e4a..7a2b077c 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -2,25 +2,50 @@
import './layout.css';
import { goto } from '$app/navigation';
import { authState } from '$lib/state/auth.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
import { themeState, initTheme, toggleTheme } from '$lib/state/theme.svelte';
import AppSidebar from '$lib/components/app-sidebar.svelte';
+ import AddProjectModal from '$lib/components/add-project-modal.svelte';
+ import FrameworkIcon from '$lib/components/framework-icon.svelte';
import * as Sidebar from "$lib/components/ui/sidebar";
import { Button } from "$lib/components/ui/button";
- import { Sun, Moon, LogOut } from "@lucide/svelte";
+ import { Sun, Moon, LogOut, Plus, Check } from "@lucide/svelte";
import { onMount } from "svelte";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";
import { ChevronDown } from 'lucide-svelte';
let { children } = $props();
+ let showAddProjectModal = $state(false);
onMount(() => {
- return initTheme();
+ initTheme();
+
+ // Load projects after auth check
+ if (authState.isAuthenticated) {
+ projectsState.initFromCache();
+ projectsState.loadProjects();
+ }
});
function handleLogout() {
authState.logout();
goto('/login');
}
+
+ function handleProjectSelect(projectId: string) {
+ projectsState.selectProject(projectId);
+ goto('/');
+ }
+
+ function handleAddProjectClick() {
+ showAddProjectModal = true;
+ }
+
+ function handleProjectCreated() {
+ showAddProjectModal = false;
+ // Optionally navigate to connection page to show token
+ goto('/connection');
+ }
</script>
<svelte:head><link rel="icon" href="/favicon.ico" /></svelte:head>
@@ -34,19 +59,39 @@
<div class="h-4 w-px bg-border"></div>
<h1 class="text-lg font-semibold">
<DropdownMenu.Root>
- <DropdownMenu.Trigger class="flex flex-row items-center">
- <div>Project 1</div> <ChevronDown size=16 />
+ <DropdownMenu.Trigger class="flex flex-row items-center gap-2 hover:bg-accent hover:text-accent-foreground rounded-md px-2 py-1 transition-colors">
+ {#if projectsState.currentProject}
+ <FrameworkIcon framework={projectsState.currentProject.framework} />
+ {/if}
+ <span>{projectsState.currentProject?.name || 'Select Project'}</span>
+ <ChevronDown size={16} />
</DropdownMenu.Trigger>
- <DropdownMenu.Content>
+ <DropdownMenu.Content align="start" class="w-56">
<DropdownMenu.Group>
<DropdownMenu.Label>Projects</DropdownMenu.Label>
<DropdownMenu.Separator />
- <DropdownMenu.Item>CT gin-backend</DropdownMenu.Item>
- <DropdownMenu.Item>CT eldapp</DropdownMenu.Item>
- <DropdownMenu.Item>CT frontend</DropdownMenu.Item>
- <DropdownMenu.Item>Traceway BE</DropdownMenu.Item>
+ {#each projectsState.projects as project}
+ <DropdownMenu.Item
+ onclick={() => handleProjectSelect(project.id)}
+ class="flex items-center justify-between cursor-pointer"
+ >
+ <div class="flex items-center gap-2">
+ <FrameworkIcon framework={project.framework} />
+ <span>{project.name}</span>
+ </div>
+ {#if project.id === projectsState.currentProjectId}
+ <Check class="h-4 w-4" />
+ {/if}
+ </DropdownMenu.Item>
+ {/each}
+ {#if projectsState.projects.length === 0}
+ <DropdownMenu.Item disabled>No projects yet</DropdownMenu.Item>
+ {/if}
<DropdownMenu.Separator />
- <DropdownMenu.Item>+ Add Project</DropdownMenu.Item>
+ <DropdownMenu.Item onclick={handleAddProjectClick} class="cursor-pointer">
+ <Plus class="mr-2 h-4 w-4" />
+ Add Project
+ </DropdownMenu.Item>
</DropdownMenu.Group>
</DropdownMenu.Content>
</DropdownMenu.Root>
@@ -69,6 +114,12 @@
</main>
</Sidebar.SidebarInset>
</Sidebar.SidebarProvider>
+
+ <AddProjectModal
+ open={showAddProjectModal}
+ onOpenChange={(open) => showAddProjectModal = open}
+ onProjectCreated={handleProjectCreated}
+ />
{:else}
<main class="h-screen w-screen">
{@render children()}
diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelte
index 224c3f62..7ba90c1d 100644
--- a/frontend/src/routes/+page.svelte
+++ b/frontend/src/routes/+page.svelte
@@ -8,6 +8,7 @@
import { Card, CardContent } from '$lib/components/ui/card';
import { api } from '$lib/api';
import { ErrorDisplay } from '$lib/components/ui/error-display';
+ import { projectsState } from '$lib/state/projects.svelte';
let dashboardData = $state<DashboardData | null>(null);
let loading = $state(true);
@@ -20,7 +21,7 @@
errorStatus = 0;
try {
- const response = await api.get('/dashboard');
+ const response = await api.get('/dashboard', { projectId: projectsState.currentProjectId ?? undefined });
// Transform the API response to match the DashboardData type
// Convert timestamp strings to Date objects
diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelte
new file mode 100644
index 00000000..da9027e7
--- /dev/null
+++ b/frontend/src/routes/connection/+page.svelte
@@ -0,0 +1,430 @@
+<script lang="ts">
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import { Copy, Check, Eye, EyeOff } from 'lucide-svelte';
+ import { projectsState, type ProjectWithToken, type Framework } from '$lib/state/projects.svelte';
+ import { Skeleton } from '$lib/components/ui/skeleton';
+ import FrameworkIcon from '$lib/components/framework-icon.svelte';
+
+ let projectWithToken = $state<ProjectWithToken | null>(null);
+ let loading = $state(true);
+ let error = $state<string | null>(null);
+ let copiedToken = $state(false);
+ let copiedCode = $state(false);
+ let copiedInstall = $state(false);
+ let showToken = $state(false);
+
+ // React to project changes
+ $effect(() => {
+ const projectId = projectsState.currentProjectId;
+ if (projectId) {
+ loading = true;
+ error = null;
+ projectWithToken = null;
+
+ projectsState.getProjectWithToken(projectId)
+ .then((project) => {
+ projectWithToken = project;
+ })
+ .catch((e) => {
+ error = e instanceof Error ? e.message : 'Failed to load project';
+ })
+ .finally(() => {
+ loading = false;
+ });
+ } else {
+ loading = false;
+ projectWithToken = null;
+ }
+ });
+
+ async function copyToken() {
+ if (projectWithToken?.token) {
+ await navigator.clipboard.writeText(projectWithToken.token);
+ copiedToken = true;
+ setTimeout(() => copiedToken = false, 2000);
+ }
+ }
+
+ // Framework-specific code snippets
+ function getFrameworkCode(framework: Framework, token: string): string {
+ const tokenValue = token || 'YOUR_PROJECT_TOKEN';
+
+ switch (framework) {
+ case 'gin':
+ return `package main
+
+import (
+ "github.com/gin-gonic/gin"
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Create Gin router
+ router := gin.Default()
+
+ // Add Traceway middleware
+ router.Use(tw.GinMiddleware())
+
+ // Your routes
+ router.GET("/", func(c *gin.Context) {
+ c.JSON(200, gin.H{"message": "Hello World"})
+ })
+
+ router.Run(":8080")
+}`;
+
+ case 'fiber':
+ return `package main
+
+import (
+ "github.com/gofiber/fiber/v2"
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Create Fiber app
+ app := fiber.New()
+
+ // Add Traceway middleware
+ app.Use(tw.FiberMiddleware())
+
+ // Your routes
+ app.Get("/", func(c *fiber.Ctx) error {
+ return c.JSON(fiber.Map{"message": "Hello World"})
+ })
+
+ app.Listen(":8080")
+}`;
+
+ case 'chi':
+ return `package main
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Create Chi router
+ r := chi.NewRouter()
+
+ // Add Traceway middleware
+ r.Use(tw.ChiMiddleware())
+
+ // Your routes
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]string{"message": "Hello World"})
+ })
+
+ http.ListenAndServe(":8080", r)
+}`;
+
+ case 'fasthttp':
+ return `package main
+
+import (
+ "github.com/valyala/fasthttp"
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Request handler
+ handler := func(ctx *fasthttp.RequestCtx) {
+ ctx.SetContentType("application/json")
+ ctx.WriteString(\`{"message": "Hello World"}\`)
+ }
+
+ // Wrap with Traceway middleware
+ wrappedHandler := tw.FastHTTPMiddleware(handler)
+
+ fasthttp.ListenAndServe(":8080", wrappedHandler)
+}`;
+
+ case 'stdlib':
+ return `package main
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Create a new ServeMux
+ mux := http.NewServeMux()
+
+ // Your routes
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]string{"message": "Hello World"})
+ })
+
+ // Wrap with Traceway middleware
+ handler := tw.HTTPMiddleware(mux)
+
+ http.ListenAndServe(":8080", handler)
+}`;
+
+ case 'custom':
+ default:
+ return `package main
+
+import (
+ "github.com/tracewayapp/traceway-go"
+)
+
+func main() {
+ // Initialize Traceway client
+ tw := traceway.New(traceway.Config{
+ Token: "${tokenValue}",
+ ServerURL: "http://localhost:8082", // Your Traceway server
+ })
+ defer tw.Close()
+
+ // Manual instrumentation example
+ // Use tw.StartTransaction() and tw.EndTransaction() to track requests
+ // See documentation for your specific framework integration
+}`;
+ }
+ }
+
+ function getInstallCommand(framework: Framework): string {
+ const base = 'go get github.com/tracewayapp/traceway-go';
+ switch (framework) {
+ case 'gin':
+ return `${base}\ngo get github.com/gin-gonic/gin`;
+ case 'fiber':
+ return `${base}\ngo get github.com/gofiber/fiber/v2`;
+ case 'chi':
+ return `${base}\ngo get github.com/go-chi/chi/v5`;
+ case 'fasthttp':
+ return `${base}\ngo get github.com/valyala/fasthttp`;
+ case 'stdlib':
+ case 'custom':
+ default:
+ return base;
+ }
+ }
+
+ function getFrameworkLabel(framework: Framework): string {
+ const labels: Record<Framework, string> = {
+ gin: 'Gin',
+ fiber: 'Fiber',
+ chi: 'Chi',
+ fasthttp: 'FastHTTP',
+ stdlib: 'Standard Library (net/http)',
+ custom: 'Custom Integration'
+ };
+ return labels[framework] || framework;
+ }
+
+ const sdkCode = $derived(
+ projectWithToken
+ ? getFrameworkCode(projectWithToken.framework, projectWithToken.token)
+ : ''
+ );
+
+ const installCommand = $derived(
+ projectWithToken
+ ? getInstallCommand(projectWithToken.framework)
+ : 'go get github.com/tracewayapp/traceway-go'
+ );
+
+ async function copyCode() {
+ await navigator.clipboard.writeText(sdkCode);
+ copiedCode = true;
+ setTimeout(() => copiedCode = false, 2000);
+ }
+
+ async function copyInstall() {
+ await navigator.clipboard.writeText(installCommand);
+ copiedInstall = true;
+ setTimeout(() => copiedInstall = false, 2000);
+ }
+</script>
+
+<div class="space-y-6">
+ <div>
+ <h2 class="text-3xl font-bold tracking-tight">Connection</h2>
+ <p class="text-muted-foreground">
+ Connect your application to Traceway using the SDK
+ </p>
+ </div>
+
+ {#if loading}
+ <Card>
+ <CardHeader>
+ <Skeleton class="h-6 w-32" />
+ <Skeleton class="h-4 w-64" />
+ </CardHeader>
+ <CardContent class="space-y-4">
+ <Skeleton class="h-10 w-full" />
+ </CardContent>
+ </Card>
+ {:else if error}
+ <Card>
+ <CardContent class="p-6">
+ <p class="text-destructive">{error}</p>
+ </CardContent>
+ </Card>
+ {:else if projectWithToken}
+ <Card>
+ <CardHeader>
+ <CardTitle>Project Token</CardTitle>
+ <CardDescription>
+ Use this token to authenticate your application with Traceway.
+ Keep it secure and don't share it publicly.
+ </CardDescription>
+ </CardHeader>
+ <CardContent class="space-y-4">
+ <div class="space-y-2">
+ <Label>Token for {projectWithToken.name}</Label>
+ <div class="flex gap-2">
+ <div class="relative flex-1">
+ <Input
+ type={showToken ? 'text' : 'password'}
+ value={projectWithToken.token}
+ readonly
+ class="pr-20 font-mono text-sm"
+ />
+ </div>
+ <Button
+ variant="outline"
+ size="icon"
+ onclick={() => showToken = !showToken}
+ title={showToken ? 'Hide token' : 'Show token'}
+ >
+ {#if showToken}
+ <EyeOff class="h-4 w-4" />
+ {:else}
+ <Eye class="h-4 w-4" />
+ {/if}
+ </Button>
+ <Button
+ variant="outline"
+ size="icon"
+ onclick={copyToken}
+ title="Copy token"
+ >
+ {#if copiedToken}
+ <Check class="h-4 w-4 text-green-500" />
+ {:else}
+ <Copy class="h-4 w-4" />
+ {/if}
+ </Button>
+ </div>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle class="flex items-center gap-2">
+ <FrameworkIcon framework={projectWithToken.framework} />
+ {getFrameworkLabel(projectWithToken.framework)} Integration
+ </CardTitle>
+ <CardDescription>
+ Add Traceway to your Go application with just a few lines of code.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={copyCode}
+ >
+ {#if copiedCode}
+ <Check class="h-4 w-4 mr-2 text-green-500" />
+ Copied!
+ {:else}
+ <Copy class="h-4 w-4 mr-2" />
+ Copy
+ {/if}
+ </Button>
+ </div>
+ <pre class="bg-muted p-4 rounded-lg overflow-x-auto text-sm font-mono leading-relaxed"><code class="language-go">{sdkCode}</code></pre>
+ </div>
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Installation</CardTitle>
+ <CardDescription>
+ Install the required packages using go get.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <div class="relative">
+ <div class="absolute top-2 right-2 z-10">
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={copyInstall}
+ >
+ {#if copiedInstall}
+ <Check class="h-4 w-4 mr-2 text-green-500" />
+ Copied!
+ {:else}
+ <Copy class="h-4 w-4 mr-2" />
+ Copy
+ {/if}
+ </Button>
+ </div>
+ <pre class="bg-muted p-4 rounded-lg overflow-x-auto text-sm font-mono">{installCommand}</pre>
+ </div>
+ </CardContent>
+ </Card>
+ {:else}
+ <Card>
+ <CardContent class="p-6 text-center">
+ <p class="text-muted-foreground">
+ No project selected. Please select or create a project from the dropdown above.
+ </p>
+ </CardContent>
+ </Card>
+ {/if}
+</div>
diff --git a/frontend/src/routes/connection/+page.ts b/frontend/src/routes/connection/+page.ts
new file mode 100644
index 00000000..9f2ce0c4
--- /dev/null
+++ b/frontend/src/routes/connection/+page.ts
@@ -0,0 +1,9 @@
+import { redirect } from '@sveltejs/kit';
+import { authState } from '$lib/state/auth.svelte';
+import type { PageLoad } from './$types';
+
+export const load: PageLoad = () => {
+ if (!authState.isAuthenticated) {
+ throw redirect(302, '/login');
+ }
+};
diff --git a/frontend/src/routes/issues/+page.svelte b/frontend/src/routes/issues/+page.svelte
index 0d42a0a2..b14f490e 100644
--- a/frontend/src/routes/issues/+page.svelte
+++ b/frontend/src/routes/issues/+page.svelte
@@ -7,6 +7,7 @@
import { Button } from "$lib/components/ui/button";
import * as Select from "$lib/components/ui/select";
import { Skeleton } from "$lib/components/ui/skeleton";
+ import { projectsState } from '$lib/state/projects.svelte';
type ExceptionGroup = {
exceptionHash: string;
@@ -69,7 +70,7 @@
search: searchQuery.trim()
};
- const response = await api.post('/exception-stack-traces', requestBody);
+ const response = await api.post('/exception-stack-traces', requestBody, { projectId: projectsState.currentProjectId ?? undefined });
exceptions = response.data || [];
total = response.pagination.total;
@@ -118,45 +119,40 @@
});
</script>
-<div class="space-y-4">
- <div class="flex items-center justify-between">
+<div class="space-y-6">
+ <!-- Header with Title and Search + Period Filter -->
+ <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h2 class="text-3xl font-bold tracking-tight">Issues</h2>
- </div>
-
- <div class="flex items-center space-x-2">
- <Input
- placeholder="Search exceptions..."
- class="h-8 w-[150px] lg:w-[250px]"
- bind:value={searchQuery}
- oninput={handleSearchInput}
- />
-
- <Select.Root
- type="single"
- bind:value={daysBack}
- onValueChange={(v) => {
- if (v) {
- page = 1;
- loadData();
- }
- }}
- >
- <Select.Trigger class="h-8 w-[120px]">
- {daysBackLabel}
- </Select.Trigger>
- <Select.Content>
- {#each daysOptions as option}
- <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>
- {/each}
- </Select.Content>
- </Select.Root>
-
- <div class="ml-auto">
- <Button variant="outline" size="sm" onclick={loadData} class="h-8">Refresh</Button>
+ <div class="flex">
+ <Input
+ placeholder="Search exceptions..."
+ class="h-9 w-[250px] lg:w-[320px] rounded-r-none border-r-0 focus:relative focus:z-10"
+ bind:value={searchQuery}
+ oninput={handleSearchInput}
+ />
+ <Select.Root
+ type="single"
+ bind:value={daysBack}
+ onValueChange={(v) => {
+ if (v) {
+ page = 1;
+ loadData();
+ }
+ }}
+ >
+ <Select.Trigger class="h-9 w-[110px] rounded-l-none -ml-px focus:relative focus:z-10">
+ {daysBackLabel}
+ </Select.Trigger>
+ <Select.Content>
+ {#each daysOptions as option}
+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
</div>
</div>
- <div class="rounded-md border">
+ <div class="rounded-md border overflow-hidden">
<Table.Root>
<Table.Header>
<Table.Row>
diff --git a/frontend/src/routes/issues/[exceptionHash]/+page.svelte b/frontend/src/routes/issues/[exceptionHash]/+page.svelte
index 40351027..00acc2dd 100644
--- a/frontend/src/routes/issues/[exceptionHash]/+page.svelte
+++ b/frontend/src/routes/issues/[exceptionHash]/+page.svelte
@@ -8,6 +8,7 @@
import * as Table from "$lib/components/ui/table";
import { Skeleton } from "$lib/components/ui/skeleton";
import { ErrorDisplay } from "$lib/components/ui/error-display";
+ import { projectsState } from '$lib/state/projects.svelte';
type ExceptionGroup = {
exceptionHash: string;
@@ -48,7 +49,7 @@
page: currentPage,
pageSize: pageSize
}
- });
+ }, { projectId: projectsState.currentProjectId ?? undefined });
group = response.group;
occurrences = response.occurrences || [];
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index 06158875..b150e986 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -7,6 +7,7 @@
import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
import { CircleAlert } from "@lucide/svelte";
import { authState } from '$lib/state/auth.svelte';
+ import { projectsState } from '$lib/state/projects.svelte';
import { themeState } from '$lib/state/theme.svelte';
let appToken = $state('');
@@ -32,6 +33,10 @@
// If successful, store token (store handles localStorage)
authState.setToken(appToken);
+
+ // Load projects after successful login
+ await projectsState.loadProjects();
+
goto('/');
} catch (e) {
error = 'Invalid APP_TOKEN';
diff --git a/frontend/src/routes/transactions/+page.svelte b/frontend/src/routes/transactions/+page.svelte
index 6d0932d7..6a015e07 100644
--- a/frontend/src/routes/transactions/+page.svelte
+++ b/frontend/src/routes/transactions/+page.svelte
@@ -5,9 +5,11 @@
import * as Table from "$lib/components/ui/table";
import { Button } from "$lib/components/ui/button";
import { Skeleton } from "$lib/components/ui/skeleton";
- import { Input } from "$lib/components/ui/input";
- import { Label } from "$lib/components/ui/label";
+ import * as Select from "$lib/components/ui/select";
import { ArrowUpDown, ArrowDown } from "@lucide/svelte";
+ import { TimeRangePicker } from "$lib/components/ui/time-range-picker";
+ import { CalendarDate, getLocalTimeZone, today } from "@internationalized/date";
+ import { projectsState } from '$lib/state/projects.svelte';
type EndpointStats = {
endpoint: string;
@@ -30,35 +32,43 @@
let total = $state(0);
let totalPages = $state(0);
- // Date Range State (separate date and time)
- let fromDateValue = $state('');
- let fromTimeValue = $state('');
- let toDateValue = $state('');
- let toTimeValue = $state('');
+ // Date Range State
+ let fromDate = $state<CalendarDate>(today(getLocalTimeZone()).subtract({ days: 7 }));
+ let toDate = $state<CalendarDate>(today(getLocalTimeZone()));
+ let fromTime = $state('00:00');
+ let toTime = $state('23:59');
// Sorting
let orderBy = $state<SortField>('count');
- // Initialize dates to last 7 days
- function initDates() {
- const now = new Date();
- const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
+ // Page size options
+ const pageSizeOptions = [
+ { value: "10", label: "10" },
+ { value: "20", label: "20" },
+ { value: "50", label: "50" },
+ { value: "100", label: "100" }
+ ];
- toDateValue = now.toISOString().slice(0, 10);
- toTimeValue = now.toTimeString().slice(0, 5);
- fromDateValue = sevenDaysAgo.toISOString().slice(0, 10);
- fromTimeValue = sevenDaysAgo.toTimeString().slice(0, 5);
- }
+ const pageSizeLabel = $derived(pageSizeOptions.find(o => o.value === pageSize.toString())?.label ?? pageSize.toString());
// Combine date and time into ISO datetime string
function getFromDateTime(): string {
- if (!fromDateValue) return '';
- return `${fromDateValue}T${fromTimeValue || '00:00'}`;
+ const dateStr = `${fromDate.year}-${String(fromDate.month).padStart(2, '0')}-${String(fromDate.day).padStart(2, '0')}`;
+ return `${dateStr}T${fromTime || '00:00'}`;
}
function getToDateTime(): string {
- if (!toDateValue) return '';
- return `${toDateValue}T${toTimeValue || '23:59'}`;
+ const dateStr = `${toDate.year}-${String(toDate.month).padStart(2, '0')}-${String(toDate.day).padStart(2, '0')}`;
+ return `${dateStr}T${toTime || '23:59'}`;
+ }
+
+ function handleTimeRangeChange(from: { date: CalendarDate; time: string }, to: { date: CalendarDate; time: string }) {
+ fromDate = from.date;
+ fromTime = from.time;
+ toDate = to.date;
+ toTime = to.time;
+ page = 1;
+ loadData();
}
function formatDuration(nanoseconds: number): string {
@@ -87,7 +97,7 @@
}
};
- const response = await api.post('/transactions/grouped', requestBody);
+ const response = await api.post('/transactions/grouped', requestBody, { projectId: projectsState.currentProjectId ?? undefined });
endpoints = response.data || [];
total = response.pagination.total;
@@ -107,6 +117,12 @@
}
}
+ function handlePageSizeChange(newPageSize: string) {
+ pageSize = parseInt(newPageSize);
+ page = 1;
+ loadData();
+ }
+
function handleSort(field: SortField) {
orderBy = field;
page = 1;
@@ -122,61 +138,25 @@
}
onMount(() => {
- initDates();
loadData();
});
</script>
<div class="space-y-6">
- <div class="flex items-center justify-between">
+ <!-- Header with Title and Time Range Filter -->
+ <div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<h2 class="text-3xl font-bold tracking-tight">Transactions</h2>
- </div>
-
- <!-- Filters Bar -->
- <div class="flex flex-wrap items-end gap-4 p-4 rounded-lg border bg-card">
- <div class="flex flex-col gap-1.5">
- <Label for="from-date" class="text-xs text-muted-foreground">From Date</Label>
- <Input
- id="from-date"
- type="date"
- class="h-9 w-[140px]"
- bind:value={fromDateValue}
- />
- </div>
- <div class="flex flex-col gap-1.5">
- <Label for="from-time" class="text-xs text-muted-foreground">From Time</Label>
- <Input
- id="from-time"
- type="time"
- class="h-9 w-[110px]"
- bind:value={fromTimeValue}
- />
- </div>
- <div class="flex flex-col gap-1.5">
- <Label for="to-date" class="text-xs text-muted-foreground">To Date</Label>
- <Input
- id="to-date"
- type="date"
- class="h-9 w-[140px]"
- bind:value={toDateValue}
- />
- </div>
- <div class="flex flex-col gap-1.5">
- <Label for="to-time" class="text-xs text-muted-foreground">To Time</Label>
- <Input
- id="to-time"
- type="time"
- class="h-9 w-[110px]"
- bind:value={toTimeValue}
- />
- </div>
- <Button variant="default" size="sm" onclick={loadData} class="h-9">
- Go
- </Button>
+ <TimeRangePicker
+ bind:fromDate
+ bind:toDate
+ bind:fromTime
+ bind:toTime
+ onApply={handleTimeRangeChange}
+ />
</div>
<!-- Endpoints Table -->
- <div class="rounded-md border">
+ <div class="rounded-md border overflow-hidden">
<Table.Root>
<Table.Header>
<Table.Row>
@@ -300,6 +280,27 @@
{total} endpoint(s) found.
</div>
<div class="flex items-center space-x-6 lg:space-x-8">
+ <div class="flex items-center space-x-2">
+ <p class="text-sm font-medium">Rows per page</p>
+ <Select.Root
+ type="single"
+ value={pageSize.toString()}
+ onValueChange={(v) => {
+ if (v) {
+ handlePageSizeChange(v);
+ }
+ }}
+ >
+ <Select.Trigger class="h-8 w-[70px]">
+ {pageSizeLabel}
+ </Select.Trigger>
+ <Select.Content side="top">
+ {#each pageSizeOptions as option}
+ <Select.Item value={option.value} label={option.label}>{option.label}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
<div class="flex w-[100px] items-center justify-center text-sm font-medium">
Page {page} of {totalPages || 1}
</div>
diff --git a/frontend/src/routes/transactions/[endpoint]/+page.svelte b/frontend/src/routes/transactions/[endpoint]/+page.svelte
index dba7ab2d..d4422150 100644
--- a/frontend/src/routes/transactions/[endpoint]/+page.svelte
+++ b/frontend/src/routes/transactions/[endpoint]/+page.svelte
@@ -9,6 +9,7 @@
import { Label } from "$lib/components/ui/label";
import { ArrowLeft, ArrowUpDown, ArrowDown } from "@lucide/svelte";
import { ErrorDisplay } from "$lib/components/ui/error-display";
+ import { projectsState } from '$lib/state/projects.svelte';
type Transaction = {
id: string;
@@ -116,7 +117,7 @@
}
};
- const response = await api.post(`/transactions/endpoint?endpoint=${encodeURIComponent(data.endpoint)}`, requestBody);
+ const response = await api.post(`/transactions/endpoint?endpoint=${encodeURIComponent(data.endpoint)}`, requestBody, { projectId: projectsState.currentProjectId ?? undefined });
transactions = response.data || [];
total = response.pagination.total;
@@ -210,7 +211,7 @@
<Input
id="from-date"
type="date"
- class="h-9 w-[140px]"
+ class="h-9 w-[150px]"
bind:value={fromDateValue}
/>
</div>
@@ -219,7 +220,7 @@
<Input
id="from-time"
type="time"
- class="h-9 w-[110px]"
+ class="h-9 w-[120px]"
bind:value={fromTimeValue}
/>
</div>
@@ -228,7 +229,7 @@
<Input
id="to-date"
type="date"
- class="h-9 w-[140px]"
+ class="h-9 w-[150px]"
bind:value={toDateValue}
/>
</div>
@@ -237,7 +238,7 @@
<Input
id="to-time"
type="time"
- class="h-9 w-[110px]"
+ class="h-9 w-[120px]"
bind:value={toTimeValue}
/>
</div>
diff --git a/frontend/static/chi.png b/frontend/static/chi.png
new file mode 100644
index 00000000..eb3bf5a5
Binary files /dev/null and b/frontend/static/chi.png differ
diff --git a/frontend/static/custom.png b/frontend/static/custom.png
new file mode 100644
index 00000000..6512cf46
Binary files /dev/null and b/frontend/static/custom.png differ
diff --git a/frontend/static/fasthttp.png b/frontend/static/fasthttp.png
new file mode 100644
index 00000000..f9ebe781
Binary files /dev/null and b/frontend/static/fasthttp.png differ
diff --git a/frontend/static/gin.png b/frontend/static/gin.png
new file mode 100644
index 00000000..7f20970b
Binary files /dev/null and b/frontend/static/gin.png differ
diff --git a/frontend/static/stdlib.png b/frontend/static/stdlib.png
new file mode 100644
index 00000000..6fc50870
Binary files /dev/null and b/frontend/static/stdlib.png differ