Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

chore: massive tracing addition (hunt down bugs)

Matthew Kilgoreefd388c1f6d7
diff --git a/backend/app/api/app.go b/backend/app/api/app.go
index abbbcc07..df07d775 100644
--- a/backend/app/api/app.go
+++ b/backend/app/api/app.go
@@ -21,7 +21,7 @@ type app struct {
bus *eventbus.EventBus
authLimiter *authRateLimiter
notifierTestLimiter *simpleRateLimiter
- otel *otel.Provider
+ otel *otel.Provider
}
func new(conf *config.Config) *app {
diff --git a/backend/app/api/handlers/v1/v1_ctrl_auth.go b/backend/app/api/handlers/v1/v1_ctrl_auth.go
index cc9078ea..77e65c12 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_auth.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_auth.go
@@ -14,6 +14,7 @@ import (
"github.com/samber/lo"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+ "go.opentelemetry.io/otel/attribute"
)
const (
@@ -101,28 +102,37 @@ func (ctrl *V1Controller) HandleAuthLogin(ps ...AuthProvider) errchain.HandlerFu
})
return func(w http.ResponseWriter, r *http.Request) error {
- // Extract provider query
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleAuthLogin")
+ defer span.End()
+
provider := r.URL.Query().Get("provider")
if provider == "" {
provider = "local"
}
+ span.SetAttributes(attribute.String("auth.provider", provider))
- // Block local only when disabled
if provider == "local" && !ctrl.config.Options.AllowLocalLogin {
+ span.SetAttributes(attribute.String("auth.outcome", "local_disabled"))
return validate.NewRequestError(fmt.Errorf("local login is not enabled"), http.StatusForbidden)
}
- // Get the provider
p, ok := providers[provider]
if !ok {
+ span.SetAttributes(attribute.String("auth.outcome", "unknown_provider"))
return validate.NewRequestError(errors.New("invalid auth provider"), http.StatusBadRequest)
}
- newToken, err := p.Authenticate(w, r)
+ newToken, err := p.Authenticate(w, r.WithContext(spanCtx))
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("auth.outcome", "authenticate_failed"))
log.Warn().Err(err).Msg("authentication failed")
return validate.NewUnauthorizedError()
}
+ span.SetAttributes(
+ attribute.String("auth.outcome", "success"),
+ attribute.String("auth.session.expires_at", newToken.ExpiresAt.Format(time.RFC3339)),
+ )
ctrl.setCookies(w, noPort(r.Host), newToken.Raw, newToken.ExpiresAt, true, newToken.AttachmentToken)
return server.JSON(w, http.StatusOK, TokenResponse{
@@ -142,16 +152,23 @@ func (ctrl *V1Controller) HandleAuthLogin(ps ...AuthProvider) errchain.HandlerFu
// @Security Bearer
func (ctrl *V1Controller) HandleAuthLogout() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- token := services.UseTokenCtx(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleAuthLogout")
+ defer span.End()
+
+ token := services.UseTokenCtx(spanCtx)
if token == "" {
+ span.SetAttributes(attribute.String("logout.outcome", "no_token"))
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
}
- err := ctrl.svc.User.Logout(r.Context(), token)
+ err := ctrl.svc.User.Logout(spanCtx, token)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("logout.outcome", "delete_failed"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("logout.outcome", "success"))
ctrl.unsetCookies(w, noPort(r.Host))
return server.JSON(w, http.StatusNoContent, nil)
}
@@ -168,16 +185,26 @@ func (ctrl *V1Controller) HandleAuthLogout() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleAuthRefresh() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- requestToken := services.UseTokenCtx(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleAuthRefresh")
+ defer span.End()
+
+ requestToken := services.UseTokenCtx(spanCtx)
if requestToken == "" {
+ span.SetAttributes(attribute.String("refresh.outcome", "no_token"))
return validate.NewRequestError(errors.New("no token within request context"), http.StatusUnauthorized)
}
- newToken, err := ctrl.svc.User.RenewToken(r.Context(), requestToken)
+ newToken, err := ctrl.svc.User.RenewToken(spanCtx, requestToken)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("refresh.outcome", "renew_failed"))
return validate.NewUnauthorizedError()
}
+ span.SetAttributes(
+ attribute.String("refresh.outcome", "success"),
+ attribute.String("refresh.expires_at", newToken.ExpiresAt.Format(time.RFC3339)),
+ )
ctrl.setCookies(w, noPort(r.Host), newToken.Raw, newToken.ExpiresAt, false, newToken.AttachmentToken)
return server.JSON(w, http.StatusOK, newToken)
}
@@ -295,19 +322,27 @@ func (ctrl *V1Controller) unsetCookies(w http.ResponseWriter, domain string) {
// @Router /v1/users/login/oidc [GET]
func (ctrl *V1Controller) HandleOIDCLogin() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- // Forbidden if OIDC is not enabled
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleOIDCLogin")
+ defer span.End()
+
if !ctrl.config.OIDC.Enabled {
+ span.SetAttributes(attribute.String("oidc.outcome", "disabled"))
return validate.NewRequestError(fmt.Errorf("OIDC is not enabled"), http.StatusForbidden)
}
- // Check if OIDC provider is available
if ctrl.oidcProvider == nil {
+ span.SetAttributes(attribute.String("oidc.outcome", "provider_unavailable"))
log.Error().Msg("OIDC provider not initialized")
return validate.NewRequestError(errors.New("OIDC provider not available"), http.StatusInternalServerError)
}
- // Initiate OIDC flow
- _, err := ctrl.oidcProvider.InitiateOIDCFlow(w, r)
+ _, err := ctrl.oidcProvider.InitiateOIDCFlow(w, r.WithContext(spanCtx))
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("oidc.outcome", "initiate_failed"))
+ } else {
+ span.SetAttributes(attribute.String("oidc.outcome", "initiated"))
+ }
return err
}
}
@@ -322,26 +357,36 @@ func (ctrl *V1Controller) HandleOIDCLogin() errchain.HandlerFunc {
// @Router /v1/users/login/oidc/callback [GET]
func (ctrl *V1Controller) HandleOIDCCallback() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- // Forbidden if OIDC is not enabled
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleOIDCCallback",
+ attribute.Bool("oidc.has_code", r.URL.Query().Get("code") != ""),
+ attribute.Bool("oidc.has_state", r.URL.Query().Get("state") != ""),
+ )
+ defer span.End()
+
if !ctrl.config.OIDC.Enabled {
+ span.SetAttributes(attribute.String("oidc.outcome", "disabled"))
return validate.NewRequestError(fmt.Errorf("OIDC is not enabled"), http.StatusForbidden)
}
- // Check if OIDC provider is available
if ctrl.oidcProvider == nil {
+ span.SetAttributes(attribute.String("oidc.outcome", "provider_unavailable"))
log.Error().Msg("OIDC provider not initialized")
return validate.NewRequestError(errors.New("OIDC provider not available"), http.StatusInternalServerError)
}
- // Handle callback
- newToken, err := ctrl.oidcProvider.HandleCallback(w, r)
+ newToken, err := ctrl.oidcProvider.HandleCallback(w, r.WithContext(spanCtx))
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("oidc.outcome", "callback_failed"))
log.Err(err).Msg("OIDC callback failed")
http.Redirect(w, r, "/?oidc_error=oidc_auth_failed", http.StatusFound)
return nil
}
- // Set cookies and redirect to home
+ span.SetAttributes(
+ attribute.String("oidc.outcome", "success"),
+ attribute.String("session.expires_at", newToken.ExpiresAt.Format(time.RFC3339)),
+ )
ctrl.setCookies(w, noPort(r.Host), newToken.Raw, newToken.ExpiresAt, true, newToken.AttachmentToken)
http.Redirect(w, r, "/home", http.StatusFound)
return nil
diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities.go b/backend/app/api/handlers/v1/v1_ctrl_entities.go
index 1960f135..4fce02dc 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_entities.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_entities.go
@@ -1,6 +1,7 @@
package v1
import (
+ "context"
"database/sql"
"encoding/csv"
"errors"
@@ -20,8 +21,28 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
"github.com/sysadminsmedia/homebox/backend/internal/web/adapters"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
)
+func entityCtrlTracer() trace.Tracer {
+ return otel.Tracer("controller")
+}
+
+func recordCtrlSpanError(span trace.Span, err error) {
+ if err == nil {
+ return
+ }
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+}
+
+func startEntityCtrlSpan(ctx context.Context, name string, attrs ...attribute.KeyValue) (context.Context, trace.Span) {
+ return entityCtrlTracer().Start(ctx, name, trace.WithAttributes(attrs...))
+}
+
// HandleEntitiesGetAll godoc
//
// @Summary Query All Entities
@@ -88,20 +109,43 @@ func (ctrl *V1Controller) HandleEntitiesGetAll() errchain.HandlerFunc {
}
return func(w http.ResponseWriter, r *http.Request) error {
- ctx := services.NewContext(r.Context())
query := extractQuery(r)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntitiesGetAll",
+ attribute.String("query.search", query.Search),
+ attribute.Int("query.page", query.Page),
+ attribute.Int("query.page_size", query.PageSize),
+ attribute.Int("query.tag_ids.count", len(query.TagIDs)),
+ attribute.Int("query.parent_ids.count", len(query.ParentIDs)),
+ attribute.Int("query.fields.count", len(query.Fields)),
+ attribute.Bool("query.include_archived", query.IncludeArchived),
+ attribute.Bool("query.filter_children", query.FilterChildren),
+ attribute.Bool("query.only_with_photo", query.OnlyWithPhoto),
+ attribute.Bool("query.only_without_photo", query.OnlyWithoutPhoto),
+ attribute.String("query.order_by", query.OrderBy),
+ attribute.Bool("query.is_location.set", query.IsLocation != nil),
+ attribute.Bool("query.is_location.value", query.IsLocation != nil && *query.IsLocation),
+ attribute.Bool("query.asset_id.set", !query.AssetID.Nil()),
+ )
+ defer span.End()
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
items, err := ctrl.repo.Entities.QueryByGroup(ctx, ctx.GID, query)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
+ span.SetAttributes(attribute.Int("response.items.count", 0))
return server.JSON(w, http.StatusOK, repo.PaginationResult[repo.EntitySummary]{
Items: []repo.EntitySummary{},
})
}
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to get entities")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ _, totalSpan := startEntityCtrlSpan(spanCtx, "controller.V1.HandleEntitiesGetAll.totalPrice",
+ attribute.Int("items.count", len(items.Items)))
totalPrice := new(big.Int)
for _, item := range items.Items {
if !item.SoldTime.IsZero() {
@@ -111,6 +155,14 @@ func (ctrl *V1Controller) HandleEntitiesGetAll() errchain.HandlerFunc {
}
totalPriceFloat, _ := new(big.Float).Quo(new(big.Float).SetInt(totalPrice), big.NewFloat(100)).Float64()
+ totalSpan.SetAttributes(attribute.Float64("total_price", totalPriceFloat))
+ totalSpan.End()
+
+ span.SetAttributes(
+ attribute.Int("response.items.count", len(items.Items)),
+ attribute.Int("response.total", items.Total),
+ attribute.Float64("response.total_price", totalPriceFloat),
+ )
return server.JSON(w, http.StatusOK, repo.EntityListResult{
PaginationResult: items,
@@ -130,8 +182,19 @@ func (ctrl *V1Controller) HandleEntitiesGetAll() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityFullPath() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) ([]repo.EntityPath, error) {
- auth := services.NewContext(r.Context())
- return ctrl.repo.Entities.PathForEntity(auth, auth.GID, ID)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityFullPath",
+ attribute.String("entity.id", ID.String()))
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
+ out, err := ctrl.repo.Entities.PathForEntity(auth, auth.GID, ID)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("path.depth", len(out)))
+ return out, nil
}
return adapters.CommandID("id", fn, http.StatusOK)
@@ -148,7 +211,24 @@ func (ctrl *V1Controller) HandleEntityFullPath() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntitiesCreate() errchain.HandlerFunc {
fn := func(r *http.Request, body repo.EntityCreate) (repo.EntityOut, error) {
- return ctrl.svc.Entities.Create(services.NewContext(r.Context()), body)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntitiesCreate",
+ attribute.String("entity.name", body.Name),
+ attribute.Float64("entity.quantity", body.Quantity),
+ attribute.Bool("entity.parent_id.set", body.ParentID != uuid.Nil),
+ attribute.Bool("entity.entity_type_id.set", body.EntityTypeID != uuid.Nil),
+ attribute.Int("entity.tags.count", len(body.TagIDs)),
+ )
+ defer span.End()
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
+ out, err := ctrl.svc.Entities.Create(ctx, body)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.String("entity.id", out.ID.String()))
+ return out, nil
}
return adapters.Action(fn, http.StatusCreated)
@@ -165,9 +245,17 @@ func (ctrl *V1Controller) HandleEntitiesCreate() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityGet() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (repo.EntityOut, error) {
- auth := services.NewContext(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityGet",
+ attribute.String("entity.id", ID.String()))
+ defer span.End()
- return ctrl.repo.Entities.GetOneByGroup(auth, auth.GID, ID)
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
+ out, err := ctrl.repo.Entities.GetOneByGroup(auth, auth.GID, ID)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ }
+ return out, err
}
return adapters.CommandID("id", fn, http.StatusOK)
@@ -184,8 +272,16 @@ func (ctrl *V1Controller) HandleEntityGet() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityDelete() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID) (any, error) {
- auth := services.NewContext(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityDelete",
+ attribute.String("entity.id", ID.String()))
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
err := ctrl.repo.Entities.DeleteByGroup(auth, auth.GID, ID)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ }
return nil, err
}
@@ -204,10 +300,27 @@ func (ctrl *V1Controller) HandleEntityDelete() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityUpdate() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, body repo.EntityUpdate) (repo.EntityOut, error) {
- auth := services.NewContext(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityUpdate",
+ attribute.String("entity.id", ID.String()),
+ attribute.String("entity.name", body.Name),
+ attribute.Float64("entity.quantity", body.Quantity),
+ attribute.Bool("entity.archived", body.Archived),
+ attribute.Bool("entity.parent_id.set", body.ParentID != uuid.Nil),
+ attribute.Int("entity.tags.count", len(body.TagIDs)),
+ attribute.Int("entity.fields.count", len(body.Fields)),
+ attribute.Bool("entity.sync_child_locations", body.SyncChildEntityLocations),
+ )
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
body.ID = ID
- return ctrl.repo.Entities.UpdateByGroup(auth, auth.GID, body)
+ out, err := ctrl.repo.Entities.UpdateByGroup(auth, auth.GID, body)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ }
+ return out, err
}
return adapters.ActionID("id", fn, http.StatusOK)
@@ -225,15 +338,31 @@ func (ctrl *V1Controller) HandleEntityUpdate() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityPatch() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, body repo.EntityPatch) (repo.EntityOut, error) {
- auth := services.NewContext(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityPatch",
+ attribute.String("entity.id", ID.String()),
+ attribute.Bool("patch.import_ref.set", body.ImportRef != nil),
+ attribute.Bool("patch.quantity.set", body.Quantity != nil),
+ attribute.Bool("patch.parent_id.set", body.ParentID != uuid.Nil),
+ attribute.Bool("patch.entity_type_id.set", body.EntityTypeID != uuid.Nil),
+ attribute.Bool("patch.tag_ids.set", body.TagIDs != nil),
+ )
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
body.ID = ID
err := ctrl.repo.Entities.Patch(auth, auth.GID, ID, body)
if err != nil {
+ recordCtrlSpanError(span, err)
return repo.EntityOut{}, err
}
- return ctrl.repo.Entities.GetOneByGroup(auth, auth.GID, ID)
+ out, err := ctrl.repo.Entities.GetOneByGroup(auth, auth.GID, ID)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ }
+ return out, err
}
return adapters.ActionID("id", fn, http.StatusOK)
@@ -251,8 +380,23 @@ func (ctrl *V1Controller) HandleEntityPatch() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityDuplicate() errchain.HandlerFunc {
fn := func(r *http.Request, ID uuid.UUID, options repo.DuplicateOptions) (repo.EntityOut, error) {
- ctx := services.NewContext(r.Context())
- return ctrl.svc.Entities.Duplicate(ctx, ctx.GID, ID, options)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityDuplicate",
+ attribute.String("entity.source_id", ID.String()),
+ attribute.Bool("options.copy_maintenance", options.CopyMaintenance),
+ attribute.Bool("options.copy_attachments", options.CopyAttachments),
+ attribute.Bool("options.copy_custom_fields", options.CopyCustomFields),
+ )
+ defer span.End()
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
+ out, err := ctrl.svc.Entities.Duplicate(ctx, ctx.GID, ID, options)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.String("entity.id", out.ID.String()))
+ return out, nil
}
return adapters.ActionID("id", fn, http.StatusCreated)
@@ -268,8 +412,18 @@ func (ctrl *V1Controller) HandleEntityDuplicate() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleGetAllCustomFieldNames() errchain.HandlerFunc {
fn := func(r *http.Request) ([]string, error) {
- auth := services.NewContext(r.Context())
- return ctrl.repo.Entities.GetAllCustomFieldNames(auth, auth.GID)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleGetAllCustomFieldNames")
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
+ out, err := ctrl.repo.Entities.GetAllCustomFieldNames(auth, auth.GID)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("names.count", len(out)))
+ return out, nil
}
return adapters.Command(fn, http.StatusOK)
@@ -290,8 +444,19 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() errchain.HandlerFunc {
}
fn := func(r *http.Request, q query) ([]string, error) {
- auth := services.NewContext(r.Context())
- return ctrl.repo.Entities.GetAllCustomFieldValues(auth, auth.GID, q.Field)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleGetAllCustomFieldValues",
+ attribute.String("field.name", q.Field))
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
+ out, err := ctrl.repo.Entities.GetAllCustomFieldValues(auth, auth.GID, q.Field)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("values.count", len(out)))
+ return out, nil
}
return adapters.Query(fn, http.StatusOK)
@@ -309,26 +474,40 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntitiesImport() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntitiesImport")
+ defer span.End()
+
+ _, parseSpan := startEntityCtrlSpan(spanCtx, "controller.V1.HandleEntitiesImport.parseForm")
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
if err != nil {
+ recordCtrlSpanError(parseSpan, err)
+ parseSpan.End()
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to parse multipart form")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
file, _, err := r.FormFile("csv")
if err != nil {
+ recordCtrlSpanError(parseSpan, err)
+ parseSpan.End()
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to get file from form")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ parseSpan.End()
defer func() { _ = file.Close() }()
- auth := services.NewContext(r.Context())
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
- _, err = ctrl.svc.Entities.CsvImport(r.Context(), auth.GID, file)
+ count, err := ctrl.svc.Entities.CsvImport(spanCtx, auth.GID, file)
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to import entities")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.Int("rows.imported.count", count))
w.WriteHeader(http.StatusNoContent)
return nil
@@ -346,8 +525,19 @@ func (ctrl *V1Controller) HandleEntitiesImport() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc {
fn := func(r *http.Request, query repo.TreeQuery) ([]repo.TreeItem, error) {
- auth := services.NewContext(r.Context())
- return ctrl.repo.Entities.Tree(auth, auth.GID, query)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleLocationTreeQuery",
+ attribute.Bool("query.with_items", query.WithItems))
+ defer span.End()
+
+ auth := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", auth.GID.String()))
+ out, err := ctrl.repo.Entities.Tree(auth, auth.GID, query)
+ if err != nil {
+ recordCtrlSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("tree.roots.count", len(out)))
+ return out, nil
}
return adapters.Query(fn, http.StatusOK)
@@ -362,13 +552,19 @@ func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleEntitiesExport() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- ctx := services.NewContext(r.Context())
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntitiesExport")
+ defer span.End()
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
- csvData, err := ctrl.svc.Entities.ExportCSV(r.Context(), ctx.GID, GetHBURL(r, &ctrl.config.Options, ctrl.url))
+ csvData, err := ctrl.svc.Entities.ExportCSV(spanCtx, ctx.GID, GetHBURL(r, &ctrl.config.Options, ctrl.url))
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to export entities")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.Int("csv.rows.count", len(csvData)))
timestamp := time.Now().Format("2006-01-02_15-04-05")
filename := fmt.Sprintf("homebox-entities_%s.csv", timestamp)
@@ -376,9 +572,12 @@ func (ctrl *V1Controller) HandleEntitiesExport() errchain.HandlerFunc {
w.Header().Set("Content-Type", "text/csv")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment;filename=%s", filename))
+ _, writeSpan := startEntityCtrlSpan(spanCtx, "controller.V1.HandleEntitiesExport.write",
+ attribute.Int("csv.rows.count", len(csvData)))
+ defer writeSpan.End()
writer := csv.NewWriter(w)
if err := writer.WriteAll(csvData); err != nil {
- // Headers already sent, can't write an HTTP error response
+ recordCtrlSpanError(writeSpan, err)
log.Err(err).Msg("failed to write CSV export response")
}
return nil
diff --git a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
index 589a8b0c..fe5d4417 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_entities_attachments.go
@@ -15,6 +15,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+ "go.opentelemetry.io/otel/attribute"
"gocloud.dev/blob"
_ "gocloud.dev/blob/azureblob"
@@ -49,8 +50,15 @@ func sanitizeAttachmentName(name string) string {
// @Security Bearer
func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleEntityAttachmentCreate")
+ defer span.End()
+
+ _, parseSpan := startEntityCtrlSpan(spanCtx, "controller.V1.HandleEntityAttachmentCreate.parseForm")
err := r.ParseMultipartForm(ctrl.maxUploadSize << 20)
if err != nil {
+ recordCtrlSpanError(parseSpan, err)
+ parseSpan.End()
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to parse multipart form")
return validate.NewRequestError(errors.New("failed to parse multipart form"), http.StatusBadRequest)
}
@@ -64,6 +72,9 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
log.Debug().Msg("file for attachment is missing")
errs = errs.Append("file", "file is required")
default:
+ recordCtrlSpanError(parseSpan, err)
+ parseSpan.End()
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to get file from form")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
@@ -74,8 +85,10 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
log.Debug().Msg("failed to get name from form")
errs = errs.Append("name", "name is required")
}
+ parseSpan.End()
if !errs.Nil() {
+ span.SetAttributes(attribute.String("response.status", "validation_error"))
return server.JSON(w, http.StatusUnprocessableEntity, errs)
}
@@ -83,7 +96,6 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
attachmentType := r.FormValue("type")
if attachmentType == "" {
- // Attempt to auto-detect the type of the file
ext := filepath.Ext(attachmentName)
switch strings.ToLower(ext) {
@@ -102,10 +114,19 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
id, err := ctrl.routeID(r)
if err != nil {
+ recordCtrlSpanError(span, err)
return err
}
- ctx := services.NewContext(r.Context())
+ span.SetAttributes(
+ attribute.String("entity.id", id.String()),
+ attribute.String("attachment.name", attachmentName),
+ attribute.String("attachment.type", attachmentType),
+ attribute.Bool("attachment.primary", primary),
+ )
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
item, err := ctrl.svc.Entities.AttachmentAdd(
ctx,
@@ -116,6 +137,7 @@ func (ctrl *V1Controller) HandleEntityAttachmentCreate() errchain.HandlerFunc {
file,
)
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to add attachment")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
@@ -166,35 +188,72 @@ func (ctrl *V1Controller) HandleEntityAttachmentUpdate() errchain.HandlerFunc {
}
func (ctrl *V1Controller) handleEntityAttachmentsHandler(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.handleEntityAttachmentsHandler",
+ attribute.String("http.method", r.Method))
+ defer span.End()
+
ID, err := ctrl.routeID(r)
if err != nil {
+ recordCtrlSpanError(span, err)
return err
}
attachmentID, err := ctrl.routeUUID(r, "attachment_id")
if err != nil {
+ recordCtrlSpanError(span, err)
return err
}
- ctx := services.NewContext(r.Context())
+ span.SetAttributes(
+ attribute.String("entity.id", ID.String()),
+ attribute.String("attachment.id", attachmentID.String()),
+ )
+
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("group.id", ctx.GID.String()))
+
switch r.Method {
case http.MethodGet:
- doc, err := ctrl.svc.Entities.AttachmentPath(r.Context(), ctx.GID, attachmentID)
+ getCtx, getSpan := startEntityCtrlSpan(spanCtx, "controller.V1.handleEntityAttachmentsHandler.get")
+ defer getSpan.End()
+
+ doc, err := ctrl.svc.Entities.AttachmentPath(getCtx, ctx.GID, attachmentID)
if err != nil {
+ recordCtrlSpanError(getSpan, err)
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to get attachment path")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ getSpan.SetAttributes(
+ attribute.String("attachment.path", doc.Path),
+ attribute.String("attachment.mime_type", doc.MimeType),
+ attribute.String("attachment.title", doc.Title),
+ )
- bucket, err := blob.OpenBucket(ctx, ctrl.repo.Attachments.GetConnString())
+ bucketCtx, bucketSpan := startEntityCtrlSpan(getCtx, "controller.V1.handleEntityAttachmentsHandler.openBucket")
+ bucket, err := blob.OpenBucket(bucketCtx, ctrl.repo.Attachments.GetConnString())
if err != nil {
+ recordCtrlSpanError(bucketSpan, err)
+ bucketSpan.End()
+ recordCtrlSpanError(getSpan, err)
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to open bucket")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
- file, err := bucket.NewReader(ctx, ctrl.repo.Attachments.GetFullPath(doc.Path), nil)
+ bucketSpan.End()
+
+ readerCtx, readerSpan := startEntityCtrlSpan(getCtx, "controller.V1.handleEntityAttachmentsHandler.openReader")
+ file, err := bucket.NewReader(readerCtx, ctrl.repo.Attachments.GetFullPath(doc.Path), nil)
if err != nil {
+ recordCtrlSpanError(readerSpan, err)
+ readerSpan.End()
+ recordCtrlSpanError(getSpan, err)
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to open file")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ readerSpan.End()
+
defer func(file *blob.Reader) {
err := file.Close()
if err != nil {
@@ -208,7 +267,6 @@ func (ctrl *V1Controller) handleEntityAttachmentsHandler(w http.ResponseWriter,
}
}(bucket)
- // Set the Content-Disposition header for RFC6266 compliance
disposition := "attachment"
if isSafeInlineType(doc.MimeType) {
disposition = "inline"
@@ -218,34 +276,43 @@ func (ctrl *V1Controller) handleEntityAttachmentsHandler(w http.ResponseWriter,
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Download-Options", "noopen")
- // Set strict CSP for all attachments to prevent any script execution
- // Even for "safe" types, we want to ensure no inline scripts can execute
w.Header().Set("Content-Security-Policy", "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox;")
+
+ _, serveSpan := startEntityCtrlSpan(getCtx, "controller.V1.handleEntityAttachmentsHandler.serveContent",
+ attribute.String("attachment.disposition", disposition))
http.ServeContent(w, r, doc.Title, doc.CreatedAt, file)
+ serveSpan.End()
return nil
- // Delete Attachment Handler
case http.MethodDelete:
- err = ctrl.svc.Entities.AttachmentDelete(r.Context(), ctx.GID, attachmentID)
+ err = ctrl.svc.Entities.AttachmentDelete(spanCtx, ctx.GID, attachmentID)
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to delete attachment")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
return server.JSON(w, http.StatusNoContent, nil)
- // Update Attachment Handler
case http.MethodPut:
var attachment repo.ItemAttachmentUpdate
err = server.Decode(r, &attachment)
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to decode attachment")
return validate.NewRequestError(err, http.StatusBadRequest)
}
attachment.ID = attachmentID
+ span.SetAttributes(
+ attribute.String("attachment.type", attachment.Type),
+ attribute.String("attachment.title", attachment.Title),
+ attribute.Bool("attachment.primary", attachment.Primary),
+ )
+
val, err := ctrl.svc.Entities.AttachmentUpdate(ctx, ctx.GID, ID, &attachment)
if err != nil {
+ recordCtrlSpanError(span, err)
log.Err(err).Msg("failed to update attachment")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
diff --git a/backend/app/api/handlers/v1/v1_ctrl_user.go b/backend/app/api/handlers/v1/v1_ctrl_user.go
index d7d3e850..f8772d23 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_user.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_user.go
@@ -12,6 +12,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting/eventbus"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/internal/sys/validate"
+ "go.opentelemetry.io/otel/attribute"
)
// HandleUserRegistration godoc
@@ -25,27 +26,46 @@ import (
// @Router /v1/users/register [Post]
func (ctrl *V1Controller) HandleUserRegistration() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- // Forbidden if local login is not enabled
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserRegistration")
+ defer span.End()
+
if !ctrl.config.Options.AllowLocalLogin {
+ span.SetAttributes(attribute.String("registration.outcome", "local_login_disabled"))
return validate.NewRequestError(fmt.Errorf("local login is not enabled"), http.StatusForbidden)
}
regData := services.UserRegistration{}
if err := server.Decode(r, &regData); err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("registration.outcome", "decode_failed"))
log.Err(err).Msg("failed to decode user registration data")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(
+ attribute.Int("user.name.length", len(regData.Name)),
+ attribute.Int("user.email.length", len(regData.Email)),
+ attribute.Int("user.password.length", len(regData.Password)),
+ attribute.Bool("registration.has_group_token", regData.GroupToken != ""),
+ )
if !ctrl.allowRegistration && regData.GroupToken == "" {
+ span.SetAttributes(attribute.String("registration.outcome", "registration_disabled"))
return validate.NewRequestError(fmt.Errorf("user registration disabled"), http.StatusForbidden)
}
- _, err := ctrl.svc.User.RegisterUser(r.Context(), regData)
+ usr, err := ctrl.svc.User.RegisterUser(spanCtx, regData)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("registration.outcome", "register_failed"))
log.Err(err).Msg("failed to register user")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(
+ attribute.String("registration.outcome", "success"),
+ attribute.String("user.id", usr.ID.String()),
+ attribute.String("group.id", usr.DefaultGroupID.String()),
+ )
return server.JSON(w, http.StatusNoContent, nil)
}
@@ -61,12 +81,19 @@ func (ctrl *V1Controller) HandleUserRegistration() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelf() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- token := services.UseTokenCtx(r.Context())
- usr, err := ctrl.svc.User.GetSelf(r.Context(), token)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelf")
+ defer span.End()
+
+ token := services.UseTokenCtx(spanCtx)
+ span.SetAttributes(attribute.Bool("token.present", token != ""))
+ usr, err := ctrl.svc.User.GetSelf(spanCtx, token)
if usr.ID == uuid.Nil || err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("self.outcome", "lookup_failed"))
log.Err(err).Msg("failed to get user")
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))
return server.JSON(w, http.StatusOK, Wrap(usr))
}
@@ -83,17 +110,26 @@ func (ctrl *V1Controller) HandleUserSelf() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelfUpdate() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelfUpdate")
+ defer span.End()
+
updateData := repo.UserUpdate{}
if err := server.Decode(r, &updateData); err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("update.outcome", "decode_failed"))
log.Err(err).Msg("failed to decode user update data")
return validate.NewRequestError(err, http.StatusBadRequest)
}
- actor := services.UseUserCtx(r.Context())
- newData, err := ctrl.svc.User.UpdateSelf(r.Context(), actor.ID, updateData)
+ actor := services.UseUserCtx(spanCtx)
+ span.SetAttributes(attribute.String("user.id", actor.ID.String()))
+ newData, err := ctrl.svc.User.UpdateSelf(spanCtx, actor.ID, updateData)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("update.outcome", "service_failed"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("update.outcome", "success"))
return server.JSON(w, http.StatusOK, Wrap(newData))
}
@@ -109,14 +145,22 @@ func (ctrl *V1Controller) HandleUserSelfUpdate() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelfDelete() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelfDelete")
+ defer span.End()
+
if ctrl.isDemo {
+ span.SetAttributes(attribute.String("delete.outcome", "demo_blocked"))
return validate.NewRequestError(nil, http.StatusForbidden)
}
- actor := services.UseUserCtx(r.Context())
- if err := ctrl.svc.User.DeleteSelf(r.Context(), actor.ID); err != nil {
+ actor := services.UseUserCtx(spanCtx)
+ span.SetAttributes(attribute.String("user.id", actor.ID.String()))
+ if err := ctrl.svc.User.DeleteSelf(spanCtx, actor.ID); err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("delete.outcome", "delete_failed"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("delete.outcome", "success"))
return server.JSON(w, http.StatusNoContent, nil)
}
@@ -132,11 +176,17 @@ func (ctrl *V1Controller) HandleUserSelfDelete() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelfSettingsGet() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
- actor := services.UseUserCtx(r.Context())
- settings, err := ctrl.svc.User.GetSettings(r.Context(), actor.ID)
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelfSettingsGet")
+ defer span.End()
+
+ actor := services.UseUserCtx(spanCtx)
+ span.SetAttributes(attribute.String("user.id", actor.ID.String()))
+ settings, err := ctrl.svc.User.GetSettings(spanCtx, actor.ID)
if err != nil {
+ recordCtrlSpanError(span, err)
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.Int("settings.keys.count", len(settings)))
w.Header().Set("Cache-Control", "no-store")
return server.JSON(w, http.StatusOK, Wrap(settings))
@@ -154,27 +204,37 @@ func (ctrl *V1Controller) HandleUserSelfSettingsGet() errchain.HandlerFunc {
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelfSettingsUpdate() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelfSettingsUpdate")
+ defer span.End()
- // Cap body to prevent DOS via large payloads.
r.Body = http.MaxBytesReader(w, r.Body, 64*1024)
var settings map[string]interface{}
if err := server.Decode(r, &settings); err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("settings.outcome", "decode_failed"))
log.Err(err).Msg("failed to decode user settings data")
return validate.NewRequestError(err, http.StatusBadRequest)
}
+ span.SetAttributes(attribute.Int("settings.keys.count", len(settings)))
- actor := services.UseUserCtx(r.Context())
- if err := ctrl.svc.User.SetSettings(r.Context(), actor.ID, settings); err != nil {
+ actor := services.UseUserCtx(spanCtx)
+ span.SetAttributes(attribute.String("user.id", actor.ID.String()))
+ if err := ctrl.svc.User.SetSettings(spanCtx, actor.ID, settings); err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("settings.outcome", "set_failed"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
- ctx := services.NewContext(r.Context())
+ ctx := services.NewContext(spanCtx)
ctrl.bus.Publish(eventbus.EventUserMutation, eventbus.GroupMutationEvent{GID: ctx.GID})
- newSettings, err := ctrl.svc.User.GetSettings(r.Context(), actor.ID)
+ newSettings, err := ctrl.svc.User.GetSettings(spanCtx, actor.ID)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("settings.outcome", "reload_failed"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("settings.outcome", "success"))
w.Header().Set("Cache-Control", "no-store")
return server.JSON(w, http.StatusOK, Wrap(newSettings))
@@ -198,22 +258,36 @@ type (
// @Security Bearer
func (ctrl *V1Controller) HandleUserSelfChangePassword() errchain.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := startEntityCtrlSpan(r.Context(), "controller.V1.HandleUserSelfChangePassword")
+ defer span.End()
+
if ctrl.isDemo {
+ span.SetAttributes(attribute.String("change_password.outcome", "demo_blocked"))
return validate.NewRequestError(nil, http.StatusForbidden)
}
var cp ChangePassword
err := server.Decode(r, &cp)
if err != nil {
+ recordCtrlSpanError(span, err)
+ span.SetAttributes(attribute.String("change_password.outcome", "decode_failed"))
log.Err(err).Msg("user failed to change password")
}
+ span.SetAttributes(
+ attribute.Int("password.current.length", len(cp.Current)),
+ attribute.Int("password.new.length", len(cp.New)),
+ )
- ctx := services.NewContext(r.Context())
+ ctx := services.NewContext(spanCtx)
+ span.SetAttributes(attribute.String("user.id", ctx.UID.String()))
ok := ctrl.svc.User.ChangePassword(ctx, cp.Current, cp.New)
+ span.SetAttributes(attribute.Bool("change_password.ok", ok))
if !ok {
+ span.SetAttributes(attribute.String("change_password.outcome", "service_rejected"))
return validate.NewRequestError(err, http.StatusInternalServerError)
}
+ span.SetAttributes(attribute.String("change_password.outcome", "success"))
return server.JSON(w, http.StatusNoContent, nil)
}
diff --git a/backend/app/api/middleware.go b/backend/app/api/middleware.go
index 2529fa01..7c6ea469 100644
--- a/backend/app/api/middleware.go
+++ b/backend/app/api/middleware.go
@@ -19,8 +19,24 @@ import (
"github.com/google/uuid"
"github.com/hay-kot/httpkit/errchain"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
)
+func mwTracer() trace.Tracer {
+ return otel.Tracer("middleware")
+}
+
+func recordMwSpanError(span trace.Span, err error) {
+ if err == nil {
+ return
+ }
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+}
+
type tokenHasKey struct {
key string
}
@@ -42,38 +58,53 @@ const (
func (a *app) mwRoles(rm RoleMode, required ...string) errchain.Middleware {
return func(next errchain.Handler) errchain.Handler {
return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
- ctx := r.Context()
-
- maybeToken := ctx.Value(hashedToken)
+ spanCtx, span := mwTracer().Start(r.Context(), "middleware.mwRoles",
+ trace.WithAttributes(
+ attribute.Int("roles.required.count", len(required)),
+ attribute.StringSlice("roles.required", required),
+ attribute.Int("roles.mode", int(rm)),
+ ))
+ defer span.End()
+
+ maybeToken := spanCtx.Value(hashedToken)
if maybeToken == nil {
panic("mwRoles: token not found in context, you must call mwAuthToken before mwRoles")
}
token := maybeToken.(string)
- roles, err := a.repos.AuthTokens.GetRoles(r.Context(), token)
+ roles, err := a.repos.AuthTokens.GetRoles(spanCtx, token)
if err != nil {
+ recordMwSpanError(span, err)
return err
}
+ span.SetAttributes(attribute.Int("roles.actual.count", roles.Len()))
outer:
switch rm {
case RoleModeOr:
for _, role := range required {
if roles.Contains(role) {
+ span.SetAttributes(attribute.String("roles.outcome", "ok_or"))
break outer
}
}
+ span.SetAttributes(attribute.String("roles.outcome", "forbidden_or"))
return validate.NewRequestError(errors.New("Forbidden"), http.StatusForbidden)
case RoleModeAnd:
for _, req := range required {
if !roles.Contains(req) {
+ span.SetAttributes(
+ attribute.String("roles.outcome", "forbidden_and"),
+ attribute.String("roles.missing", req),
+ )
return validate.NewRequestError(errors.New("Unauthorized"), http.StatusForbidden)
}
}
+ span.SetAttributes(attribute.String("roles.outcome", "ok_and"))
}
- return next.ServeHTTP(w, r)
+ return next.ServeHTTP(w, r.WithContext(spanCtx))
})
}
}
@@ -112,49 +143,82 @@ func getQuery(r *http.Request) (string, error) {
// - query = "?access_token=1234567890"
func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := mwTracer().Start(r.Context(), "middleware.mwAuthToken",
+ trace.WithAttributes(
+ attribute.String("http.method", r.Method),
+ attribute.String("http.path", r.URL.Path),
+ ))
+ defer span.End()
+
var requestToken string
+ tokenSource := "none"
- // We ignore the error to allow the next strategy to be attempted
{
cookies, _ := v1.GetCookies(r)
if cookies != nil {
requestToken = cookies.Token
+ tokenSource = "cookie"
}
}
if requestToken == "" {
- keyFuncs := [...]KeyFunc{
- getBearer,
- getQuery,
+ keyFuncs := [...]struct {
+ name string
+ fn KeyFunc
+ }{
+ {"bearer", getBearer},
+ {"query", getQuery},
}
- for _, keyFunc := range keyFuncs {
- token, err := keyFunc(r)
+ for _, kf := range keyFuncs {
+ token, err := kf.fn(r)
if err == nil {
requestToken = token
+ tokenSource = kf.name
break
}
}
}
+ span.SetAttributes(
+ attribute.String("auth.token.source", tokenSource),
+ attribute.Bool("auth.token.present", requestToken != ""),
+ )
+
if requestToken == "" {
+ span.SetAttributes(attribute.String("auth.outcome", "no_token"))
return validate.NewRequestError(errors.New("authorization header or query is required"), http.StatusUnauthorized)
}
+ hadBearerPrefix := strings.HasPrefix(requestToken, "Bearer ")
requestToken = strings.TrimPrefix(requestToken, "Bearer ")
+ span.SetAttributes(
+ attribute.Bool("auth.token.had_bearer_prefix", hadBearerPrefix),
+ attribute.Int("auth.token.length", len(requestToken)),
+ )
- r = r.WithContext(context.WithValue(r.Context(), hashedToken, requestToken))
+ r = r.WithContext(context.WithValue(spanCtx, hashedToken, requestToken))
usr, err := a.services.User.GetSelf(r.Context(), requestToken)
- // Check the database for the token
if err != nil {
if ent.IsNotFound(err) {
+ span.SetAttributes(attribute.String("auth.outcome", "token_not_found"))
return validate.NewRequestError(errors.New("valid authorization token is required"), http.StatusUnauthorized)
}
+ recordMwSpanError(span, err)
+ span.SetAttributes(attribute.String("auth.outcome", "lookup_error"))
return err
}
+ span.SetAttributes(
+ attribute.String("auth.outcome", "authenticated"),
+ attribute.String("user.id", usr.ID.String()),
+ attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
+ attribute.Int("user.groups.count", len(usr.GroupIDs)),
+ attribute.Bool("user.is_superuser", usr.IsSuperuser),
+ )
+
r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))
return next.ServeHTTP(w, r)
})
@@ -166,32 +230,44 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
// WARNING: This middleware _MUST_ be called after mwAuthToken
func (a *app) mwTenant(next errchain.Handler) errchain.Handler {
return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
- ctx := r.Context()
+ spanCtx, span := mwTracer().Start(r.Context(), "middleware.mwTenant")
+ defer span.End()
- // Get the user from context (set by mwAuthToken)
- user := services.UseUserCtx(ctx)
+ user := services.UseUserCtx(spanCtx)
if user == nil {
- return validate.NewRequestError(errors.New("user context not found"), http.StatusInternalServerError)
+ err := errors.New("user context not found")
+ recordMwSpanError(span, err)
+ span.SetAttributes(attribute.String("tenant.outcome", "no_user_ctx"))
+ return validate.NewRequestError(err, http.StatusInternalServerError)
}
tenantID := user.DefaultGroupID
+ tenantSource := "default"
- // Check for X-Tenant header or tenant query parameter
tenantHeader := r.Header.Get("X-Tenant")
if tenantHeader == "" {
tenantHeader = r.URL.Query().Get("tenant")
+ if tenantHeader != "" {
+ tenantSource = "query"
+ }
+ } else {
+ tenantSource = "header"
}
if tenantHeader != "" {
parsedTenantID, err := uuid.Parse(tenantHeader)
if err != nil {
+ recordMwSpanError(span, err)
+ span.SetAttributes(
+ attribute.String("tenant.outcome", "parse_failed"),
+ attribute.String("tenant.source", tenantSource),
+ )
return validate.NewRequestError(errors.New("invalid X-Tenant header format"), http.StatusBadRequest)
}
tenantID = parsedTenantID
}
- // Validate user has access to the resolved tenant (whether from header or default group)
hasAccess := false
for _, gid := range user.GroupIDs {
if gid == tenantID {
@@ -200,12 +276,21 @@ func (a *app) mwTenant(next errchain.Handler) errchain.Handler {
}
}
+ span.SetAttributes(
+ attribute.String("user.id", user.ID.String()),
+ attribute.String("tenant.id", tenantID.String()),
+ attribute.String("tenant.source", tenantSource),
+ attribute.Int("user.groups.count", len(user.GroupIDs)),
+ attribute.Bool("tenant.has_access", hasAccess),
+ )
+
if !hasAccess {
+ span.SetAttributes(attribute.String("tenant.outcome", "forbidden"))
return validate.NewRequestError(errors.New("user does not have access to the requested tenant"), http.StatusForbidden)
}
- // Set the tenant in context
- r = r.WithContext(services.SetTenantCtx(ctx, tenantID))
+ span.SetAttributes(attribute.String("tenant.outcome", "ok"))
+ r = r.WithContext(services.SetTenantCtx(spanCtx, tenantID))
return next.ServeHTTP(w, r)
})
}
@@ -303,25 +388,38 @@ func (l *authRateLimiter) Stop() {
// mwAuthRateLimit enforces request throttling for authentication endpoints with an exponential backoff.
func (a *app) mwAuthRateLimit(next errchain.Handler) errchain.Handler {
return errchain.HandlerFunc(func(w http.ResponseWriter, r *http.Request) error {
+ spanCtx, span := mwTracer().Start(r.Context(), "middleware.mwAuthRateLimit")
+ defer span.End()
+
limiter := a.authLimiter
if limiter == nil || !limiter.cfg.Enabled {
- return next.ServeHTTP(w, r)
+ span.SetAttributes(attribute.String("rate_limit.outcome", "disabled"))
+ return next.ServeHTTP(w, r.WithContext(spanCtx))
}
key := limiter.keyForRequest(r, a.conf.Options.TrustProxy)
now := limiter.nowFn()
+ span.SetAttributes(attribute.String("rate_limit.key", key))
if retryAfter, allowed := limiter.shouldAllow(key, now); !allowed {
seconds := int(retryAfter.Round(time.Second).Seconds())
if seconds < 0 {
seconds = 0
}
+ span.SetAttributes(
+ attribute.String("rate_limit.outcome", "blocked"),
+ attribute.Int("rate_limit.retry_after_seconds", seconds),
+ )
w.Header().Set("Retry-After", strconv.Itoa(seconds))
return validate.NewRequestError(errors.New("too many authentication attempts"), http.StatusTooManyRequests)
}
- err := next.ServeHTTP(w, r)
+ err := next.ServeHTTP(w, r.WithContext(spanCtx))
limiter.record(key, now, err == nil)
+ span.SetAttributes(
+ attribute.String("rate_limit.outcome", "allowed"),
+ attribute.Bool("rate_limit.recorded_success", err == nil),
+ )
return err
})
}
diff --git a/backend/app/api/providers/local.go b/backend/app/api/providers/local.go
index b60dbf2f..bf579c99 100644
--- a/backend/app/api/providers/local.go
+++ b/backend/app/api/providers/local.go
@@ -4,6 +4,10 @@ import (
"net/http"
"github.com/sysadminsmedia/homebox/backend/internal/core/services"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
)
type LocalProvider struct {
@@ -21,10 +25,33 @@ func (p *LocalProvider) Name() string {
}
func (p *LocalProvider) Authenticate(w http.ResponseWriter, r *http.Request) (services.UserAuthTokenDetail, error) {
+ ctx, span := otel.Tracer("provider").Start(r.Context(), "provider.LocalProvider.Authenticate",
+ trace.WithAttributes(
+ attribute.String("http.method", r.Method),
+ attribute.String("http.content_type", r.Header.Get("Content-Type")),
+ ))
+ defer span.End()
+
loginForm, err := getLoginForm(r)
if err != nil {
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+ span.SetAttributes(attribute.String("login.outcome", "form_decode_failed"))
return services.UserAuthTokenDetail{}, err
}
+ span.SetAttributes(
+ attribute.Int("login.username.length", len(loginForm.Username)),
+ attribute.Int("login.password.length", len(loginForm.Password)),
+ attribute.Bool("login.stay_logged_in", loginForm.StayLoggedIn),
+ )
- return p.service.Login(r.Context(), loginForm.Username, loginForm.Password, loginForm.StayLoggedIn)
+ out, err := p.service.Login(ctx, loginForm.Username, loginForm.Password, loginForm.StayLoggedIn)
+ if err != nil {
+ span.SetAttributes(attribute.String("login.outcome", "service_login_failed"))
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+ return out, err
+ }
+ span.SetAttributes(attribute.String("login.outcome", "success"))
+ return out, nil
}
diff --git a/backend/internal/core/services/service_entities.go b/backend/internal/core/services/service_entities.go
index 9013edee..8915df53 100644
--- a/backend/internal/core/services/service_entities.go
+++ b/backend/internal/core/services/service_entities.go
@@ -11,8 +11,24 @@ import (
"github.com/samber/lo"
"github.com/sysadminsmedia/homebox/backend/internal/core/services/reporting"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
)
+func entityServiceTracer() trace.Tracer {
+ return otel.Tracer("service")
+}
+
+func recordServiceSpanError(span trace.Span, err error) {
+ if err == nil {
+ return
+ }
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+}
+
var (
ErrNotFound = errors.New("not found")
ErrFileNotFound = errors.New("file not found")
@@ -27,65 +43,128 @@ type EntityService struct {
}
func (svc *EntityService) Create(ctx Context, entity repo.EntityCreate) (repo.EntityOut, error) {
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.EntityService.Create",
+ trace.WithAttributes(
+ attribute.String("group.id", ctx.GID.String()),
+ attribute.String("entity.name", entity.Name),
+ attribute.Bool("svc.auto_increment_asset_id", svc.autoIncrementAssetID),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
if svc.autoIncrementAssetID {
highest, err := svc.repo.Entities.GetHighestAssetID(ctx, ctx.GID)
if err != nil {
+ recordServiceSpanError(span, err)
return repo.EntityOut{}, err
}
entity.AssetID = highest + 1
+ span.SetAttributes(attribute.Int64("entity.asset_id", int64(entity.AssetID)))
}
- return svc.repo.Entities.Create(ctx, ctx.GID, entity)
+ out, err := svc.repo.Entities.Create(ctx, ctx.GID, entity)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.String("entity.id", out.ID.String()))
+ return out, nil
}
func (svc *EntityService) Duplicate(ctx Context, gid, id uuid.UUID, options repo.DuplicateOptions) (repo.EntityOut, error) {
- return svc.repo.Entities.Duplicate(ctx, gid, id, options)
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.EntityService.Duplicate",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.source_id", id.String()),
+ attribute.Bool("options.copy_maintenance", options.CopyMaintenance),
+ attribute.Bool("options.copy_attachments", options.CopyAttachments),
+ attribute.Bool("options.copy_custom_fields", options.CopyCustomFields),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
+ out, err := svc.repo.Entities.Duplicate(ctx, gid, id, options)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.String("entity.id", out.ID.String()))
+ return out, nil
}
func (svc *EntityService) EnsureAssetID(ctx context.Context, gid uuid.UUID) (int, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.EnsureAssetID",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
items, err := svc.repo.Entities.GetAllZeroAssetID(ctx, gid)
if err != nil {
+ recordServiceSpanError(span, err)
return 0, err
}
+ span.SetAttributes(attribute.Int("entities.zero_asset_id.count", len(items)))
highest, err := svc.repo.Entities.GetHighestAssetID(ctx, gid)
if err != nil {
+ recordServiceSpanError(span, err)
return 0, err
}
+ _, updateSpan := entityServiceTracer().Start(ctx, "service.EntityService.EnsureAssetID.update",
+ trace.WithAttributes(attribute.Int("entities.count", len(items))))
+ defer updateSpan.End()
+
finished := 0
for _, item := range items {
highest++
err = svc.repo.Entities.SetAssetID(ctx, gid, item.ID, highest)
if err != nil {
+ recordServiceSpanError(updateSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
finished++
}
+ updateSpan.SetAttributes(attribute.Int("entities.updated.count", finished))
+ span.SetAttributes(attribute.Int("entities.updated.count", finished))
return finished, nil
}
func (svc *EntityService) EnsureImportRef(ctx context.Context, gid uuid.UUID) (int, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.EnsureImportRef",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
ids, err := svc.repo.Entities.GetAllZeroImportRef(ctx, gid)
if err != nil {
+ recordServiceSpanError(span, err)
return 0, err
}
+ span.SetAttributes(attribute.Int("entities.zero_import_ref.count", len(ids)))
+
+ _, patchSpan := entityServiceTracer().Start(ctx, "service.EntityService.EnsureImportRef.patch",
+ trace.WithAttributes(attribute.Int("entities.count", len(ids))))
+ defer patchSpan.End()
finished := 0
for _, entityID := range ids {
ref := uuid.New().String()[0:8]
err = svc.repo.Entities.Patch(ctx, gid, entityID, repo.EntityPatch{ImportRef: &ref})
if err != nil {
+ recordServiceSpanError(patchSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
finished++
}
+ patchSpan.SetAttributes(attribute.Int("entities.patched.count", finished))
+ span.SetAttributes(attribute.Int("entities.patched.count", finished))
return finished, nil
}
@@ -101,26 +180,43 @@ func serializeLocation[T ~[]string](location T) string {
// 2. If the entity has an ImportRef and it exists it is skipped
// 3. Locations and Tags are created if they do not exist.
func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.Reader) (int, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.CsvImport",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ _, readSpan := entityServiceTracer().Start(ctx, "service.EntityService.CsvImport.readCsv")
sheet := reporting.IOSheet{}
err := sheet.Read(data)
if err != nil {
+ recordServiceSpanError(readSpan, err)
+ readSpan.End()
+ recordServiceSpanError(span, err)
return 0, err
}
+ readSpan.SetAttributes(attribute.Int("rows.count", len(sheet.Rows)))
+ readSpan.End()
+ span.SetAttributes(attribute.Int("rows.count", len(sheet.Rows)))
// ========================================
// Tags
var tagMap map[string]uuid.UUID
{
- tags, err := svc.repo.Tags.GetAll(ctx, gid)
+ tagsCtx, tagsSpan := entityServiceTracer().Start(ctx, "service.EntityService.CsvImport.loadTags")
+ tags, err := svc.repo.Tags.GetAll(tagsCtx, gid)
if err != nil {
+ recordServiceSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordServiceSpanError(span, err)
return 0, err
}
tagMap = lo.SliceToMap(tags, func(tag repo.TagSummary) (string, uuid.UUID) {
return tag.Name, tag.ID
})
+ tagsSpan.SetAttributes(attribute.Int("tags.count", len(tags)))
+ tagsSpan.End()
}
// ========================================
@@ -128,8 +224,12 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
locationMap := make(map[string]uuid.UUID)
{
- locations, err := svc.repo.Entities.Tree(ctx, gid, repo.TreeQuery{WithItems: false})
+ locsCtx, locsSpan := entityServiceTracer().Start(ctx, "service.EntityService.CsvImport.loadLocations")
+ locations, err := svc.repo.Entities.Tree(locsCtx, gid, repo.TreeQuery{WithItems: false})
if err != nil {
+ recordServiceSpanError(locsSpan, err)
+ locsSpan.End()
+ recordServiceSpanError(span, err)
return 0, err
}
@@ -149,6 +249,11 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
for _, location := range locations {
traverse(&location, []string{})
}
+ locsSpan.SetAttributes(
+ attribute.Int("locations.tree.count", len(locations)),
+ attribute.Int("locations.flat.count", len(locationMap)),
+ )
+ locsSpan.End()
}
// ========================================
@@ -159,48 +264,81 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
if svc.autoIncrementAssetID {
highestAID, err = svc.repo.Entities.GetHighestAssetID(ctx, gid)
if err != nil {
+ recordServiceSpanError(span, err)
return 0, err
}
}
+ importCtx, importSpan := entityServiceTracer().Start(ctx, "service.EntityService.CsvImport.importRows",
+ trace.WithAttributes(attribute.Int("rows.count", len(sheet.Rows))))
+ defer importSpan.End()
+
finished := 0
for i := range sheet.Rows {
row := sheet.Rows[i]
+ rowCtx, rowSpan := entityServiceTracer().Start(importCtx, "service.EntityService.CsvImport.row",
+ trace.WithAttributes(
+ attribute.Int("row.index", i),
+ attribute.String("row.name", row.Name),
+ attribute.String("row.import_ref", row.ImportRef),
+ attribute.Int("row.tags.count", len(row.TagStr)),
+ attribute.Int("row.location.depth", len(row.Location)),
+ ))
+ ctx := rowCtx
+
createRequired := true
- // ========================================
- // Preflight check for existing entity
if row.ImportRef != "" {
exists, err := svc.repo.Entities.CheckRef(ctx, gid, row.ImportRef)
if err != nil {
- return 0, fmt.Errorf("error checking for existing entity with ref %q: %w", row.ImportRef, err)
+ wrapped := fmt.Errorf("error checking for existing entity with ref %q: %w", row.ImportRef, err)
+ recordServiceSpanError(rowSpan, wrapped)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, wrapped)
+ recordServiceSpanError(span, wrapped)
+ return 0, wrapped
}
if exists {
createRequired = false
}
}
+ rowSpan.SetAttributes(attribute.Bool("row.create_required", createRequired))
// ========================================
// Pre-Create tags as necessary
tagIds := make([]uuid.UUID, len(row.TagStr))
- for j := range row.TagStr {
- tag := row.TagStr[j]
+ if len(row.TagStr) > 0 {
+ tagsCtx, tagsSpan := entityServiceTracer().Start(rowCtx, "service.EntityService.CsvImport.row.tags",
+ trace.WithAttributes(attribute.Int("tags.count", len(row.TagStr))))
+ tagsCreated := 0
+ for j := range row.TagStr {
+ tag := row.TagStr[j]
- id, ok := tagMap[tag]
- if !ok {
- newTag, err := svc.repo.Tags.Create(ctx, gid, repo.TagCreate{Name: tag})
- if err != nil {
- return 0, err
+ id, ok := tagMap[tag]
+ if !ok {
+ newTag, err := svc.repo.Tags.Create(tagsCtx, gid, repo.TagCreate{Name: tag})
+ if err != nil {
+ recordServiceSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
+ return 0, err
+ }
+ id = newTag.ID
+ tagsCreated++
}
- id = newTag.ID
- }
- tagIds[j] = id
- tagMap[tag] = id
+ tagIds[j] = id
+ tagMap[tag] = id
+ }
+ tagsSpan.SetAttributes(attribute.Int("tags.created.count", tagsCreated))
+ tagsSpan.End()
}
// ========================================
@@ -208,7 +346,10 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
path := serializeLocation(row.Location)
locationID, ok := locationMap[path]
- if !ok { // Traverse the path of LocationStr and check each path element to see if it exists already, if not create it.
+ if !ok {
+ locsCtx, locsSpan := entityServiceTracer().Start(rowCtx, "service.EntityService.CsvImport.row.locations",
+ trace.WithAttributes(attribute.Int("location.depth", len(row.Location))))
+ locsCreated := 0
paths := []string{}
for i, pathElement := range row.Location {
paths = append(paths, pathElement)
@@ -218,28 +359,41 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
if !ok {
parentID := uuid.Nil
- // Get the parent ID
if i > 0 {
parentPath := serializeLocation(row.Location[:i])
parentID = locationMap[parentPath]
}
- newLocation, err := svc.repo.Entities.CreateContainer(ctx, gid, repo.EntityCreate{
+ newLocation, err := svc.repo.Entities.CreateContainer(locsCtx, gid, repo.EntityCreate{
ParentID: parentID,
Name: pathElement,
})
if err != nil {
+ recordServiceSpanError(locsSpan, err)
+ locsSpan.End()
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
locationID = newLocation.ID
+ locsCreated++
}
locationMap[path] = locationID
}
+ locsSpan.SetAttributes(attribute.Int("locations.created.count", locsCreated))
+ locsSpan.End()
locationID, ok = locationMap[path]
if !ok {
- return 0, errors.New("failed to create location")
+ err := errors.New("failed to create location")
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
+ return 0, err
}
}
@@ -267,18 +421,32 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
entity, err = svc.repo.Entities.Create(ctx, gid, newEntity)
if err != nil {
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
default:
entity, err = svc.repo.Entities.GetByRef(ctx, gid, row.ImportRef)
if err != nil {
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
}
if entity.ID == uuid.Nil {
- return 0, fmt.Errorf("entity ID is nil for entity with import ref %q", row.ImportRef)
+ wrapped := fmt.Errorf("entity ID is nil for entity with import ref %q", row.ImportRef)
+ recordServiceSpanError(rowSpan, wrapped)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, wrapped)
+ recordServiceSpanError(span, wrapped)
+ return 0, wrapped
}
+ rowSpan.SetAttributes(attribute.String("entity.id", entity.ID.String()))
fields := lo.Map(row.Fields, func(f reporting.ExportItemFields, _ int) repo.EntityFieldData {
return repo.EntityFieldData{
@@ -323,36 +491,87 @@ func (svc *EntityService) CsvImport(ctx context.Context, gid uuid.UUID, data io.
_, err = svc.repo.Entities.UpdateByGroup(ctx, gid, updateEntity)
if err != nil {
+ recordServiceSpanError(rowSpan, err)
+ rowSpan.End()
+ recordServiceSpanError(importSpan, err)
+ recordServiceSpanError(span, err)
return 0, err
}
finished++
+ rowSpan.End()
}
+ importSpan.SetAttributes(attribute.Int("rows.imported.count", finished))
+ span.SetAttributes(attribute.Int("rows.imported.count", finished))
return finished, nil
}
func (svc *EntityService) ExportCSV(ctx context.Context, gid uuid.UUID, hbURL string) ([][]string, error) {
- items, err := svc.repo.Entities.GetAll(ctx, gid)
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.ExportCSV",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ loadCtx, loadSpan := entityServiceTracer().Start(ctx, "service.EntityService.ExportCSV.load")
+ items, err := svc.repo.Entities.GetAll(loadCtx, gid)
if err != nil {
+ recordServiceSpanError(loadSpan, err)
+ loadSpan.End()
+ recordServiceSpanError(span, err)
return nil, err
}
+ loadSpan.SetAttributes(attribute.Int("entities.count", len(items)))
+ loadSpan.End()
+ span.SetAttributes(attribute.Int("entities.count", len(items)))
+ readCtx, readSpan := entityServiceTracer().Start(ctx, "service.EntityService.ExportCSV.readItems")
sheet := reporting.IOSheet{}
-
- err = sheet.ReadItems(ctx, items, gid, svc.repo, hbURL)
+ err = sheet.ReadItems(readCtx, items, gid, svc.repo, hbURL)
if err != nil {
+ recordServiceSpanError(readSpan, err)
+ readSpan.End()
+ recordServiceSpanError(span, err)
return nil, err
}
+ readSpan.End()
- return sheet.CSV()
+ _, csvSpan := entityServiceTracer().Start(ctx, "service.EntityService.ExportCSV.encode")
+ defer csvSpan.End()
+ rows, err := sheet.CSV()
+ if err != nil {
+ recordServiceSpanError(csvSpan, err)
+ recordServiceSpanError(span, err)
+ return nil, err
+ }
+ csvSpan.SetAttributes(attribute.Int("rows.count", len(rows)))
+ return rows, nil
}
func (svc *EntityService) ExportBillOfMaterialsCSV(ctx context.Context, gid uuid.UUID) ([]byte, error) {
- items, err := svc.repo.Entities.GetAll(ctx, gid)
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.ExportBillOfMaterialsCSV",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ loadCtx, loadSpan := entityServiceTracer().Start(ctx, "service.EntityService.ExportBillOfMaterialsCSV.load")
+ items, err := svc.repo.Entities.GetAll(loadCtx, gid)
if err != nil {
+ recordServiceSpanError(loadSpan, err)
+ loadSpan.End()
+ recordServiceSpanError(span, err)
return nil, err
}
+ loadSpan.SetAttributes(attribute.Int("entities.count", len(items)))
+ loadSpan.End()
+ span.SetAttributes(attribute.Int("entities.count", len(items)))
- return reporting.BillOfMaterialsCSV(items)
+ _, encodeSpan := entityServiceTracer().Start(ctx, "service.EntityService.ExportBillOfMaterialsCSV.encode")
+ defer encodeSpan.End()
+ out, err := reporting.BillOfMaterialsCSV(items)
+ if err != nil {
+ recordServiceSpanError(encodeSpan, err)
+ recordServiceSpanError(span, err)
+ return nil, err
+ }
+ encodeSpan.SetAttributes(attribute.Int("bytes.size", len(out)))
+ return out, nil
}
diff --git a/backend/internal/core/services/service_items_attachments.go b/backend/internal/core/services/service_items_attachments.go
index 99a47302..4e1db467 100644
--- a/backend/internal/core/services/service_items_attachments.go
+++ b/backend/internal/core/services/service_items_attachments.go
@@ -9,11 +9,21 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/attachment"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
)
func (svc *EntityService) AttachmentPath(ctx context.Context, gid uuid.UUID, attachmentID uuid.UUID) (*ent.Attachment, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.AttachmentPath",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("attachment.id", attachmentID.String()),
+ ))
+ defer span.End()
+
attachment, err := svc.repo.Attachments.Get(ctx, gid, attachmentID)
if err != nil {
+ recordServiceSpanError(span, err)
return nil, err
}
@@ -21,48 +31,101 @@ func (svc *EntityService) AttachmentPath(ctx context.Context, gid uuid.UUID, att
}
func (svc *EntityService) AttachmentUpdate(ctx Context, gid uuid.UUID, entityID uuid.UUID, data *repo.ItemAttachmentUpdate) (repo.EntityOut, error) {
- // Update Attachment
- attachment, err := svc.repo.Attachments.Update(ctx, gid, data.ID, data)
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.EntityService.AttachmentUpdate",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", entityID.String()),
+ attribute.String("attachment.id", data.ID.String()),
+ attribute.String("attachment.type", data.Type),
+ attribute.String("attachment.title", data.Title),
+ attribute.Bool("attachment.primary", data.Primary),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
+ updateCtx, updateSpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentUpdate.update")
+ attachment, err := svc.repo.Attachments.Update(updateCtx, gid, data.ID, data)
if err != nil {
+ recordServiceSpanError(updateSpan, err)
+ updateSpan.End()
+ recordServiceSpanError(span, err)
return repo.EntityOut{}, err
}
+ updateSpan.End()
- // Update Document
- attDoc := attachment
- _, err = svc.repo.Attachments.Rename(ctx, gid, attDoc.ID, data.Title)
+ renameCtx, renameSpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentUpdate.rename")
+ _, err = svc.repo.Attachments.Rename(renameCtx, gid, attachment.ID, data.Title)
if err != nil {
+ recordServiceSpanError(renameSpan, err)
+ renameSpan.End()
+ recordServiceSpanError(span, err)
return repo.EntityOut{}, err
}
+ renameSpan.End()
- return svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ out, err := svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
}
// AttachmentAdd adds an attachment to an entity by creating an entry in the Documents table and linking it to the Attachment
// Table and Entities table. The file provided via the reader is stored on the file system based on the provided
// relative path during construction of the service.
func (svc *EntityService) AttachmentAdd(ctx Context, entityID uuid.UUID, filename string, attachmentType attachment.Type, primary bool, file io.Reader) (repo.EntityOut, error) {
- // Get the Entity
- _, err := svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.EntityService.AttachmentAdd",
+ trace.WithAttributes(
+ attribute.String("group.id", ctx.GID.String()),
+ attribute.String("entity.id", entityID.String()),
+ attribute.String("attachment.filename", filename),
+ attribute.String("attachment.type", attachmentType.String()),
+ attribute.Bool("attachment.primary", primary),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
+ verifyCtx, verifySpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentAdd.verifyEntity")
+ _, err := svc.repo.Entities.GetOneByGroup(verifyCtx, ctx.GID, entityID)
if err != nil {
+ recordServiceSpanError(verifySpan, err)
+ verifySpan.End()
+ recordServiceSpanError(span, err)
return repo.EntityOut{}, err
}
+ verifySpan.End()
- // Create the attachment
- _, err = svc.repo.Attachments.Create(ctx, entityID, repo.ItemCreateAttachment{Title: filename, Content: file}, attachmentType, primary)
+ createCtx, createSpan := entityServiceTracer().Start(spanCtx, "service.EntityService.AttachmentAdd.create")
+ _, err = svc.repo.Attachments.Create(createCtx, entityID, repo.ItemCreateAttachment{Title: filename, Content: file}, attachmentType, primary)
if err != nil {
+ recordServiceSpanError(createSpan, err)
+ createSpan.End()
+ recordServiceSpanError(span, err)
log.Err(err).Msg("failed to create attachment")
return repo.EntityOut{}, err
}
+ createSpan.End()
- return svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ out, err := svc.repo.Entities.GetOneByGroup(ctx, ctx.GID, entityID)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
}
func (svc *EntityService) AttachmentDelete(ctx context.Context, gid uuid.UUID, attachmentID uuid.UUID) error {
- // Delete the attachment
+ ctx, span := entityServiceTracer().Start(ctx, "service.EntityService.AttachmentDelete",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("attachment.id", attachmentID.String()),
+ ))
+ defer span.End()
+
err := svc.repo.Attachments.Delete(ctx, gid, attachmentID)
if err != nil {
+ recordServiceSpanError(span, err)
return err
}
- return err
+ return nil
}
diff --git a/backend/internal/core/services/service_user.go b/backend/internal/core/services/service_user.go
index d7e45a44..fc7c4fc2 100644
--- a/backend/internal/core/services/service_user.go
+++ b/backend/internal/core/services/service_user.go
@@ -13,6 +13,8 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authroles"
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
"github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
)
var (
@@ -46,6 +48,15 @@ type (
// RegisterUser creates a new user and group in the data with the provided data. It also bootstraps the user's group
// with default Tags and Locations.
func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration) (repo.UserOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser",
+ trace.WithAttributes(
+ attribute.Int("user.name.length", len(data.Name)),
+ attribute.Int("user.email.length", len(data.Email)),
+ attribute.Int("user.password.length", len(data.Password)),
+ attribute.Bool("registration.has_group_token", data.GroupToken != ""),
+ ))
+ defer span.End()
+
log.Debug().
Str("name", data.Name).
Str("email", data.Email).
@@ -63,33 +74,64 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
switch data.GroupToken {
case "":
+ groupCtx, groupSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.createGroup")
log.Debug().Msg("creating new group")
creatingGroup = true
- group, err = svc.repos.Groups.GroupCreate(ctx, fmt.Sprintf("%s's Home", data.Name), uuid.Nil)
+ group, err = svc.repos.Groups.GroupCreate(groupCtx, fmt.Sprintf("%s's Home", data.Name), uuid.Nil)
if err != nil {
+ recordServiceSpanError(groupSpan, err)
+ groupSpan.End()
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to create group")
return repo.UserOut{}, err
}
+ groupSpan.SetAttributes(attribute.String("group.id", group.ID.String()))
+ groupSpan.End()
default:
+ joinCtx, joinSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.joinGroup")
log.Debug().Msg("joining existing group")
- token, err = svc.repos.Groups.InvitationGet(ctx, hasher.HashToken(data.GroupToken))
+ token, err = svc.repos.Groups.InvitationGet(joinCtx, hasher.HashToken(data.GroupToken))
if err != nil {
+ recordServiceSpanError(joinSpan, err)
+ joinSpan.End()
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to get invitation token")
return repo.UserOut{}, err
}
if token.ExpiresAt.Before(time.Now()) {
- return repo.UserOut{}, errors.New("invitation expired")
+ err := errors.New("invitation expired")
+ joinSpan.SetAttributes(attribute.String("invitation.error", "expired"))
+ recordServiceSpanError(joinSpan, err)
+ joinSpan.End()
+ recordServiceSpanError(span, err)
+ return repo.UserOut{}, err
}
if token.Uses <= 0 {
- return repo.UserOut{}, errors.New("invitation used up")
+ err := errors.New("invitation used up")
+ joinSpan.SetAttributes(attribute.String("invitation.error", "used_up"))
+ recordServiceSpanError(joinSpan, err)
+ joinSpan.End()
+ recordServiceSpanError(span, err)
+ return repo.UserOut{}, err
}
group = token.Group
+ joinSpan.SetAttributes(
+ attribute.String("group.id", group.ID.String()),
+ attribute.Int("invitation.uses_remaining", token.Uses),
+ )
+ joinSpan.End()
}
- hashed, err := hasher.HashPassword(data.Password)
+ span.SetAttributes(
+ attribute.String("group.id", group.ID.String()),
+ attribute.Bool("registration.creating_group", creatingGroup),
+ )
+
+ hashed, err := hasher.HashPasswordCtx(ctx, data.Password)
if err != nil {
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to hash password")
return repo.UserOut{}, err
}
@@ -104,37 +146,60 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
usr, err := svc.repos.Users.Create(ctx, usrCreate)
if err != nil {
+ recordServiceSpanError(span, err)
return repo.UserOut{}, err
}
+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))
log.Debug().Msg("user created")
// Create the default tags and locations for the group.
if creatingGroup {
+ bootstrapCtx, bootstrapSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.bootstrap")
log.Debug().Msg("creating default tags")
+ tagsCreated := 0
for _, tag := range defaultTags() {
- _, err := svc.repos.Tags.Create(ctx, usr.DefaultGroupID, tag)
+ _, err := svc.repos.Tags.Create(bootstrapCtx, usr.DefaultGroupID, tag)
if err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
+ bootstrapSpan.End()
+ recordServiceSpanError(span, err)
return repo.UserOut{}, err
}
+ tagsCreated++
}
log.Debug().Msg("creating default locations")
+ locsCreated := 0
for _, loc := range defaultLocations() {
- _, err := svc.repos.Entities.CreateContainer(ctx, usr.DefaultGroupID, loc)
+ _, err := svc.repos.Entities.CreateContainer(bootstrapCtx, usr.DefaultGroupID, loc)
if err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
+ bootstrapSpan.End()
+ recordServiceSpanError(span, err)
return repo.UserOut{}, err
}
+ locsCreated++
}
+ bootstrapSpan.SetAttributes(
+ attribute.Int("tags.created.count", tagsCreated),
+ attribute.Int("locations.created.count", locsCreated),
+ )
+ bootstrapSpan.End()
}
// Decrement the invitation token if it was used.
if token.ID != uuid.Nil {
+ decCtx, decSpan := entityServiceTracer().Start(ctx, "service.UserService.RegisterUser.decrementInvitation")
log.Debug().Msg("decrementing invitation token")
- err = svc.repos.Groups.InvitationDecrement(ctx, token.ID)
+ err = svc.repos.Groups.InvitationDecrement(decCtx, token.ID)
if err != nil {
+ recordServiceSpanError(decSpan, err)
+ decSpan.End()
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to update invitation token")
return repo.UserOut{}, err
}
+ decSpan.End()
}
return usr, nil
@@ -142,29 +207,62 @@ func (svc *UserService) RegisterUser(ctx context.Context, data UserRegistration)
// GetSelf returns the user that is currently logged in based of the token provided within
func (svc *UserService) GetSelf(ctx context.Context, requestToken string) (repo.UserOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.GetSelf",
+ trace.WithAttributes(attribute.Int("token.length", len(requestToken))))
+ defer span.End()
+
hash := hasher.HashToken(requestToken)
- return svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
+ out, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
+ if err != nil {
+ span.SetAttributes(attribute.Bool("user.found", false))
+ if !ent.IsNotFound(err) {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
+ }
+ span.SetAttributes(
+ attribute.Bool("user.found", true),
+ attribute.String("user.id", out.ID.String()),
+ )
+ return out, nil
}
func (svc *UserService) UpdateSelf(ctx context.Context, id uuid.UUID, data repo.UserUpdate) (repo.UserOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.UpdateSelf",
+ trace.WithAttributes(attribute.String("user.id", id.String())))
+ defer span.End()
+
err := svc.repos.Users.Update(ctx, id, data)
if err != nil {
+ recordServiceSpanError(span, err)
return repo.UserOut{}, err
}
- return svc.repos.Users.GetOneID(ctx, id)
+ out, err := svc.repos.Users.GetOneID(ctx, id)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
}
// ============================================================================
// User Authentication
func (svc *UserService) createSessionToken(ctx context.Context, userID uuid.UUID, extendedSession bool) (UserAuthTokenDetail, error) {
- attachmentToken := hasher.GenerateToken()
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.createSessionToken",
+ trace.WithAttributes(
+ attribute.String("user.id", userID.String()),
+ attribute.Bool("session.extended", extendedSession),
+ ))
+ defer span.End()
+
+ attachmentToken := hasher.GenerateTokenCtx(ctx)
expiresAt := time.Now().Add(oneWeek)
if extendedSession {
expiresAt = time.Now().Add(oneWeek * 4)
}
+ span.SetAttributes(attribute.String("session.expires_at", expiresAt.Format(time.RFC3339)))
attachmentData := repo.UserAuthTokenCreate{
UserID: userID,
@@ -172,22 +270,32 @@ func (svc *UserService) createSessionToken(ctx context.Context, userID uuid.UUID
ExpiresAt: expiresAt,
}
- _, err := svc.repos.AuthTokens.CreateToken(ctx, attachmentData, authroles.RoleAttachments)
+ attCtx, attSpan := entityServiceTracer().Start(ctx, "service.UserService.createSessionToken.attachmentToken")
+ _, err := svc.repos.AuthTokens.CreateToken(attCtx, attachmentData, authroles.RoleAttachments)
if err != nil {
+ recordServiceSpanError(attSpan, err)
+ attSpan.End()
+ recordServiceSpanError(span, err)
return UserAuthTokenDetail{}, err
}
+ attSpan.End()
- userToken := hasher.GenerateToken()
+ userToken := hasher.GenerateTokenCtx(ctx)
data := repo.UserAuthTokenCreate{
UserID: userID,
TokenHash: userToken.Hash,
ExpiresAt: expiresAt,
}
- created, err := svc.repos.AuthTokens.CreateToken(ctx, data, authroles.RoleUser)
+ userCtx, userSpan := entityServiceTracer().Start(ctx, "service.UserService.createSessionToken.userToken")
+ created, err := svc.repos.AuthTokens.CreateToken(userCtx, data, authroles.RoleUser)
if err != nil {
+ recordServiceSpanError(userSpan, err)
+ userSpan.End()
+ recordServiceSpanError(span, err)
return UserAuthTokenDetail{}, err
}
+ userSpan.End()
return UserAuthTokenDetail{
Raw: userToken.Raw,
@@ -196,46 +304,102 @@ func (svc *UserService) createSessionToken(ctx context.Context, userID uuid.UUID
}, nil
}
+// Login is the main local-credential login path. The span and its sub-spans capture
+// every branch (user-not-found, OIDC-only user, password mismatch, password rehash)
+// so an intermittent password rejection trace points directly at the failing step.
func (svc *UserService) Login(ctx context.Context, username, password string, extendedSession bool) (UserAuthTokenDetail, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.Login",
+ trace.WithAttributes(
+ attribute.Int("user.email.length", len(username)),
+ attribute.Int("password.length", len(password)),
+ attribute.Bool("session.extended", extendedSession),
+ ))
+ defer span.End()
+
usr, err := svc.repos.Users.GetOneEmail(ctx, username)
if err != nil {
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.String("login.outcome", "user_not_found"),
+ )
// SECURITY: Perform hash to ensure response times are the same
- hasher.CheckPasswordHash("not-a-real-password", "not-a-real-password")
+ _, dummySpan := entityServiceTracer().Start(ctx, "service.UserService.Login.timingDummy",
+ trace.WithAttributes(attribute.String("reason", "user_not_found")))
+ hasher.CheckPasswordHashCtx(ctx, "not-a-real-password", "not-a-real-password")
+ dummySpan.End()
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
+ span.SetAttributes(
+ attribute.Bool("user.found", true),
+ attribute.String("user.id", usr.ID.String()),
+ attribute.Bool("user.has_password_hash", usr.PasswordHash != ""),
+ attribute.Bool("user.has_oidc", usr.OidcIssuer != nil && usr.OidcSubject != nil),
+ )
// SECURITY: Deny login for users with null or empty password (OIDC users)
if usr.PasswordHash == "" {
log.Warn().Str("email", username).Msg("Login attempt blocked for user with null password (likely OIDC user)")
- // SECURITY: Perform hash to ensure response times are the same
- hasher.CheckPasswordHash("not-a-real-password", "not-a-real-password")
+ span.SetAttributes(attribute.String("login.outcome", "blocked_no_password_hash"))
+ _, dummySpan := entityServiceTracer().Start(ctx, "service.UserService.Login.timingDummy",
+ trace.WithAttributes(attribute.String("reason", "no_password_hash")))
+ hasher.CheckPasswordHashCtx(ctx, "not-a-real-password", "not-a-real-password")
+ dummySpan.End()
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
- check, rehash := hasher.CheckPasswordHash(password, usr.PasswordHash)
+ check, rehash := hasher.CheckPasswordHashCtx(ctx, password, usr.PasswordHash)
+ span.SetAttributes(
+ attribute.Bool("password.match", check),
+ attribute.Bool("password.rehash_needed", rehash),
+ )
if !check {
+ span.SetAttributes(attribute.String("login.outcome", "password_mismatch"))
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
if rehash {
- hash, err := hasher.HashPassword(password)
+ rehashCtx, rehashSpan := entityServiceTracer().Start(ctx, "service.UserService.Login.rehash",
+ trace.WithAttributes(attribute.String("user.id", usr.ID.String())))
+ hash, err := hasher.HashPasswordCtx(rehashCtx, password)
if err != nil {
+ recordServiceSpanError(rehashSpan, err)
+ rehashSpan.End()
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to hash password")
return UserAuthTokenDetail{}, err
}
- err = svc.repos.Users.ChangePassword(ctx, usr.ID, hash)
+ err = svc.repos.Users.ChangePassword(rehashCtx, usr.ID, hash)
if err != nil {
+ recordServiceSpanError(rehashSpan, err)
+ rehashSpan.End()
+ recordServiceSpanError(span, err)
return UserAuthTokenDetail{}, err
}
+ rehashSpan.End()
+ }
+
+ span.SetAttributes(attribute.String("login.outcome", "success"))
+ out, err := svc.createSessionToken(ctx, usr.ID, extendedSession)
+ if err != nil {
+ recordServiceSpanError(span, err)
}
- return svc.createSessionToken(ctx, usr.ID, extendedSession)
+ return out, err
}
// LoginOIDC creates a session token for a user authenticated via OIDC.
// It now uses issuer + subject for identity association (OIDC spec compliance).
// If the user doesn't exist, it will create one.
func (svc *UserService) LoginOIDC(ctx context.Context, issuer, subject, email, name string) (UserAuthTokenDetail, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.LoginOIDC",
+ trace.WithAttributes(
+ attribute.String("oidc.issuer", issuer),
+ attribute.Int("oidc.subject.length", len(subject)),
+ attribute.Int("oidc.email.length", len(email)),
+ attribute.Int("oidc.name.length", len(name)),
+ ))
+ defer span.End()
+
issuer = strings.TrimSpace(issuer)
subject = strings.TrimSpace(subject)
email = strings.ToLower(strings.TrimSpace(email))
@@ -243,6 +407,7 @@ func (svc *UserService) LoginOIDC(ctx context.Context, issuer, subject, email, n
if issuer == "" || subject == "" {
log.Warn().Str("issuer", issuer).Str("subject", subject).Msg("OIDC login missing issuer or subject")
+ span.SetAttributes(attribute.String("oidc.outcome", "missing_issuer_or_subject"))
return UserAuthTokenDetail{}, ErrorInvalidLogin
}
@@ -250,54 +415,84 @@ func (svc *UserService) LoginOIDC(ctx context.Context, issuer, subject, email, n
usr, err := svc.repos.Users.GetOneOIDC(ctx, issuer, subject)
if err != nil {
if !ent.IsNotFound(err) {
+ recordServiceSpanError(span, err)
log.Err(err).Str("issuer", issuer).Str("subject", subject).Msg("failed to lookup user by OIDC identity")
return UserAuthTokenDetail{}, err
}
// Not found: attempt migration path by email (legacy) if email provided
if email != "" {
- legacyUsr, lerr := svc.repos.Users.GetOneEmail(ctx, email)
+ migrationCtx, migrationSpan := entityServiceTracer().Start(ctx, "service.UserService.LoginOIDC.legacyEmailMigration")
+ legacyUsr, lerr := svc.repos.Users.GetOneEmail(migrationCtx, email)
if lerr == nil {
log.Info().Str("email", email).Str("issuer", issuer).Str("subject", subject).Msg("migrating legacy email-based OIDC user to issuer+subject")
- // Update user with OIDC identity fields
- if uerr := svc.repos.Users.SetOIDCIdentity(ctx, legacyUsr.ID, issuer, subject); uerr == nil {
+ if uerr := svc.repos.Users.SetOIDCIdentity(migrationCtx, legacyUsr.ID, issuer, subject); uerr == nil {
usr = legacyUsr
+ migrationSpan.SetAttributes(
+ attribute.String("oidc.migration.outcome", "migrated"),
+ attribute.String("user.id", legacyUsr.ID.String()),
+ )
} else {
+ migrationSpan.SetAttributes(attribute.String("oidc.migration.outcome", "set_identity_failed"))
+ recordServiceSpanError(migrationSpan, uerr)
log.Err(uerr).Str("email", email).Msg("failed to set OIDC identity on legacy user")
}
+ } else {
+ migrationSpan.SetAttributes(attribute.String("oidc.migration.outcome", "no_legacy_user"))
}
+ migrationSpan.End()
}
}
// Create user if still not resolved
if usr.ID == uuid.Nil {
log.Debug().Str("issuer", issuer).Str("subject", subject).Msg("OIDC user not found, creating new user")
+ span.SetAttributes(attribute.String("oidc.outcome", "creating_user"))
usr, err = svc.registerOIDCUser(ctx, issuer, subject, email, name)
if err != nil {
if ent.IsConstraintError(err) {
if usr2, gerr := svc.repos.Users.GetOneOIDC(ctx, issuer, subject); gerr == nil {
log.Info().Str("issuer", issuer).Str("subject", subject).Msg("OIDC user created concurrently; proceeding")
usr = usr2
+ span.SetAttributes(attribute.String("oidc.outcome", "concurrent_create_resolved"))
} else {
+ recordServiceSpanError(span, gerr)
log.Err(gerr).Str("issuer", issuer).Str("subject", subject).Msg("failed to fetch user after constraint error")
return UserAuthTokenDetail{}, gerr
}
} else {
+ recordServiceSpanError(span, err)
log.Err(err).Str("issuer", issuer).Str("subject", subject).Msg("failed to create OIDC user")
return UserAuthTokenDetail{}, err
}
}
+ } else {
+ span.SetAttributes(attribute.String("oidc.outcome", "existing_user"))
}
- return svc.createSessionToken(ctx, usr.ID, true)
+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))
+ out, err := svc.createSessionToken(ctx, usr.ID, true)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
}
// registerOIDCUser creates a new user for OIDC authentication with issuer+subject identity.
func (svc *UserService) registerOIDCUser(ctx context.Context, issuer, subject, email, name string) (repo.UserOut, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.registerOIDCUser",
+ trace.WithAttributes(
+ attribute.String("oidc.issuer", issuer),
+ attribute.Int("oidc.subject.length", len(subject)),
+ ))
+ defer span.End()
+
group, err := svc.repos.Groups.GroupCreate(ctx, "Home", uuid.Nil)
if err != nil {
+ recordServiceSpanError(span, err)
log.Err(err).Msg("Failed to create group for OIDC user")
return repo.UserOut{}, err
}
+ span.SetAttributes(attribute.String("group.id", group.ID.String()))
usrCreate := repo.UserCreate{
Name: name,
@@ -310,112 +505,222 @@ func (svc *UserService) registerOIDCUser(ctx context.Context, issuer, subject, e
entUser, err := svc.repos.Users.CreateWithOIDC(ctx, usrCreate, issuer, subject)
if err != nil {
+ recordServiceSpanError(span, err)
return repo.UserOut{}, err
}
+ span.SetAttributes(attribute.String("user.id", entUser.ID.String()))
+ bootstrapCtx, bootstrapSpan := entityServiceTracer().Start(ctx, "service.UserService.registerOIDCUser.bootstrap")
log.Debug().Str("issuer", issuer).Str("subject", subject).Msg("creating default tags for OIDC user")
+ tagsCreated := 0
for _, tag := range defaultTags() {
- _, err := svc.repos.Tags.Create(ctx, group.ID, tag)
+ _, err := svc.repos.Tags.Create(bootstrapCtx, group.ID, tag)
if err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
log.Err(err).Msg("Failed to create default tag")
+ continue
}
+ tagsCreated++
}
log.Debug().Str("issuer", issuer).Str("subject", subject).Msg("creating default locations for OIDC user")
+ locsCreated := 0
for _, loc := range defaultLocations() {
- _, err := svc.repos.Entities.CreateContainer(ctx, group.ID, loc)
+ _, err := svc.repos.Entities.CreateContainer(bootstrapCtx, group.ID, loc)
if err != nil {
+ recordServiceSpanError(bootstrapSpan, err)
log.Err(err).Msg("Failed to create default location")
+ continue
}
+ locsCreated++
}
+ bootstrapSpan.SetAttributes(
+ attribute.Int("tags.created.count", tagsCreated),
+ attribute.Int("locations.created.count", locsCreated),
+ )
+ bootstrapSpan.End()
return entUser, nil
}
func (svc *UserService) Logout(ctx context.Context, token string) error {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.Logout",
+ trace.WithAttributes(attribute.Int("token.length", len(token))))
+ defer span.End()
+
hash := hasher.HashToken(token)
err := svc.repos.AuthTokens.DeleteToken(ctx, hash)
+ recordServiceSpanError(span, err)
return err
}
func (svc *UserService) RenewToken(ctx context.Context, token string) (UserAuthTokenDetail, error) {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.RenewToken",
+ trace.WithAttributes(attribute.Int("token.length", len(token))))
+ defer span.End()
+
hash := hasher.HashToken(token)
dbToken, err := svc.repos.AuthTokens.GetUserFromToken(ctx, hash)
if err != nil {
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.String("renew.outcome", "invalid_token"),
+ )
+ if !ent.IsNotFound(err) {
+ recordServiceSpanError(span, err)
+ }
return UserAuthTokenDetail{}, ErrorInvalidToken
}
+ span.SetAttributes(
+ attribute.Bool("user.found", true),
+ attribute.String("user.id", dbToken.ID.String()),
+ )
- return svc.createSessionToken(ctx, dbToken.ID, false)
+ out, err := svc.createSessionToken(ctx, dbToken.ID, false)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ }
+ return out, err
}
// DeleteSelf deletes the user that is currently logged based of the provided UUID
// There is _NO_ protection against deleting the wrong user, as such this should only
// be used when the identify of the user has been confirmed.
func (svc *UserService) DeleteSelf(ctx context.Context, id uuid.UUID) error {
- return svc.repos.Users.Delete(ctx, id)
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.DeleteSelf",
+ trace.WithAttributes(attribute.String("user.id", id.String())))
+ defer span.End()
+
+ err := svc.repos.Users.Delete(ctx, id)
+ recordServiceSpanError(span, err)
+ return err
}
func (svc *UserService) ChangePassword(ctx Context, current string, new string) (ok bool) {
+ spanCtx, span := entityServiceTracer().Start(ctx.Context, "service.UserService.ChangePassword",
+ trace.WithAttributes(
+ attribute.String("user.id", ctx.UID.String()),
+ attribute.Int("password.current.length", len(current)),
+ attribute.Int("password.new.length", len(new)),
+ ))
+ defer span.End()
+ ctx.Context = spanCtx
+
usr, err := svc.repos.Users.GetOneID(ctx, ctx.UID)
if err != nil {
+ recordServiceSpanError(span, err)
+ span.SetAttributes(attribute.String("change_password.outcome", "user_not_found"))
return false
}
- match, _ := hasher.CheckPasswordHash(current, usr.PasswordHash)
+ match, _ := hasher.CheckPasswordHashCtx(spanCtx, current, usr.PasswordHash)
+ span.SetAttributes(attribute.Bool("password.current.match", match))
if !match {
+ span.SetAttributes(attribute.String("change_password.outcome", "current_password_incorrect"))
log.Err(errors.New("current password is incorrect")).Msg("Failed to change password")
return false
}
- hashed, err := hasher.HashPassword(new)
+ hashed, err := hasher.HashPasswordCtx(spanCtx, new)
if err != nil {
+ recordServiceSpanError(span, err)
+ span.SetAttributes(attribute.String("change_password.outcome", "hash_failed"))
log.Err(err).Msg("Failed to hash password")
return false
}
err = svc.repos.Users.ChangePassword(ctx.Context, ctx.UID, hashed)
if err != nil {
+ recordServiceSpanError(span, err)
+ span.SetAttributes(attribute.String("change_password.outcome", "persist_failed"))
log.Err(err).Msg("Failed to change password")
return false
}
+ span.SetAttributes(attribute.String("change_password.outcome", "success"))
return true
}
func (svc *UserService) GetSettings(ctx context.Context, uid uuid.UUID) (map[string]interface{}, error) {
- return svc.repos.Users.GetSettings(ctx, uid)
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.GetSettings",
+ trace.WithAttributes(attribute.String("user.id", uid.String())))
+ defer span.End()
+
+ out, err := svc.repos.Users.GetSettings(ctx, uid)
+ if err != nil {
+ recordServiceSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("settings.keys.count", len(out)))
+ return out, nil
}
func (svc *UserService) SetSettings(ctx context.Context, uid uuid.UUID, settings map[string]interface{}) error {
- return svc.repos.Users.SetSettings(ctx, uid, settings)
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.SetSettings",
+ trace.WithAttributes(
+ attribute.String("user.id", uid.String()),
+ attribute.Int("settings.keys.count", len(settings)),
+ ))
+ defer span.End()
+
+ err := svc.repos.Users.SetSettings(ctx, uid, settings)
+ recordServiceSpanError(span, err)
+ return err
}
// EnsureUserPassword ensures that the user with the given email has the specified password. If the password does not match, it updates the user's password to the new value.
// WARNING: This method bypasses normal checks, it should only be used for demos and/or superuser level administrative processes.
func (svc *UserService) EnsureUserPassword(ctx context.Context, email, password string) error {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.EnsureUserPassword",
+ trace.WithAttributes(
+ attribute.Int("user.email.length", len(email)),
+ attribute.Int("password.length", len(password)),
+ ))
+ defer span.End()
+
usr, err := svc.repos.Users.GetOneEmailNoEdges(ctx, email)
if err != nil {
+ if !ent.IsNotFound(err) {
+ recordServiceSpanError(span, err)
+ }
+ span.SetAttributes(attribute.String("ensure.outcome", "user_not_found"))
return err
}
+ span.SetAttributes(attribute.String("user.id", usr.ID.String()))
+
match := false
if usr.PasswordHash != "" {
- match, _ = hasher.CheckPasswordHash(password, usr.PasswordHash)
+ match, _ = hasher.CheckPasswordHashCtx(ctx, password, usr.PasswordHash)
}
+ span.SetAttributes(attribute.Bool("password.match", match))
if !match {
- hash, herr := hasher.HashPassword(password)
+ hash, herr := hasher.HashPasswordCtx(ctx, password)
if herr != nil {
+ recordServiceSpanError(span, herr)
+ span.SetAttributes(attribute.String("ensure.outcome", "hash_failed"))
return herr
}
if cerr := svc.repos.Users.ChangePassword(ctx, usr.ID, hash); cerr != nil {
+ recordServiceSpanError(span, cerr)
+ span.SetAttributes(attribute.String("ensure.outcome", "persist_failed"))
return cerr
}
+ span.SetAttributes(attribute.String("ensure.outcome", "rehashed"))
+ return nil
}
+ span.SetAttributes(attribute.String("ensure.outcome", "noop_match"))
return nil
}
// ExistsByEmail returns true if a user with the given email exists.
func (svc *UserService) ExistsByEmail(ctx context.Context, email string) bool {
+ ctx, span := entityServiceTracer().Start(ctx, "service.UserService.ExistsByEmail",
+ trace.WithAttributes(attribute.Int("user.email.length", len(email))))
+ defer span.End()
+
_, err := svc.repos.Users.GetOneEmailNoEdges(ctx, email)
- return err == nil
+ exists := err == nil
+ span.SetAttributes(attribute.Bool("user.exists", exists))
+ return exists
}
diff --git a/backend/internal/data/repo/repo_entities.go b/backend/internal/data/repo/repo_entities.go
index a5c39a30..78162ad6 100644
--- a/backend/internal/data/repo/repo_entities.go
+++ b/backend/internal/data/repo/repo_entities.go
@@ -22,8 +22,24 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/predicate"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/tag"
"github.com/sysadminsmedia/homebox/backend/internal/data/types"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
)
+func entityTracer() trace.Tracer {
+ return otel.Tracer("data")
+}
+
+func recordSpanError(span trace.Span, err error) {
+ if err == nil {
+ return
+ }
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+}
+
type EntityRepository struct {
db *ent.Client
bus *eventbus.EventBus
@@ -73,10 +89,10 @@ type (
EntityCreate struct {
ImportRef string `json:"-"`
- ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
- Name string `json:"name" validate:"required,min=1,max=255"`
+ ParentID uuid.UUID `json:"parentId" extensions:"x-nullable"`
+ Name string `json:"name" validate:"required,min=1,max=255"`
Quantity float64 `json:"quantity"`
- Description string `json:"description" validate:"max=1000"`
+ Description string `json:"description" validate:"max=1000"`
AssetID AssetID `json:"-"`
EntityTypeID uuid.UUID `json:"entityTypeId"`
@@ -85,11 +101,11 @@ type (
}
EntityUpdate struct {
- ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
+ ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
ID uuid.UUID `json:"id"`
- AssetID AssetID `json:"assetId" swaggertype:"string"`
- Name string `json:"name" validate:"required,min=1,max=255"`
- Description string `json:"description" validate:"max=1000"`
+ AssetID AssetID `json:"assetId" swaggertype:"string"`
+ Name string `json:"name" validate:"required,min=1,max=255"`
+ Description string `json:"description" validate:"max=1000"`
Quantity float64 `json:"quantity"`
Insured bool `json:"insured"`
Archived bool `json:"archived"`
@@ -127,11 +143,11 @@ type (
EntityPatch struct {
ID uuid.UUID `json:"id"`
- Quantity *float64 `json:"quantity,omitempty" extensions:"x-nullable,x-omitempty"`
- ImportRef *string `json:"-" extensions:"x-nullable,x-omitempty"`
- ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
- EntityTypeID uuid.UUID `json:"entityTypeId" extensions:"x-nullable,x-omitempty"`
- TagIDs []uuid.UUID `json:"tagIds" extensions:"x-nullable,x-omitempty"`
+ Quantity *float64 `json:"quantity,omitempty" extensions:"x-nullable,x-omitempty"`
+ ImportRef *string `json:"-" extensions:"x-nullable,x-omitempty"`
+ ParentID uuid.UUID `json:"parentId" extensions:"x-nullable,x-omitempty"`
+ EntityTypeID uuid.UUID `json:"entityTypeId" extensions:"x-nullable,x-omitempty"`
+ TagIDs []uuid.UUID `json:"tagIds" extensions:"x-nullable,x-omitempty"`
}
EntitySummary struct {
@@ -341,6 +357,13 @@ func mapEntityOut(e *ent.Entity) EntityOut {
// resolveDefaultEntityType finds or creates the default entity type for a group.
func (r *EntityRepository) resolveDefaultEntityType(ctx context.Context, gid uuid.UUID, isLocation bool) (uuid.UUID, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.resolveDefaultEntityType",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Bool("entity_type.is_location", isLocation),
+ ))
+ defer span.End()
+
et, err := r.db.EntityType.Query().
Where(
entitytype.HasGroupWith(group.ID(gid)),
@@ -354,19 +377,29 @@ func (r *EntityRepository) resolveDefaultEntityType(ctx context.Context, gid uui
if isLocation {
name = "Location"
}
+ createCtx, createSpan := entityTracer().Start(ctx, "repo.EntityRepository.resolveDefaultEntityType.create",
+ trace.WithAttributes(attribute.String("entity_type.name", name)))
created, err := r.db.EntityType.Create().
SetName(name).
SetDescription("").
SetIsLocation(isLocation).
SetGroupID(gid).
- Save(ctx)
+ Save(createCtx)
if err != nil {
+ recordSpanError(createSpan, err)
+ createSpan.End()
+ recordSpanError(span, err)
return uuid.Nil, err
}
+ createSpan.SetAttributes(attribute.String("entity_type.id", created.ID.String()))
+ createSpan.End()
+ span.SetAttributes(attribute.String("entity_type.id", created.ID.String()))
return created.ID, nil
}
+ recordSpanError(span, err)
return uuid.Nil, err
}
+ span.SetAttributes(attribute.String("entity_type.id", et.ID.String()))
return et.ID, nil
}
@@ -377,6 +410,13 @@ func (r *EntityRepository) publishMutationEvent(gid uuid.UUID) {
}
func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...predicate.Entity) (EntityOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.getOneTx",
+ trace.WithAttributes(
+ attribute.Bool("tx", tx != nil),
+ attribute.Int("predicate.count", len(where)),
+ ))
+ defer span.End()
+
var q *ent.EntityQuery
if tx != nil {
q = tx.Entity.Query().Where(where...)
@@ -384,7 +424,7 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...pr
q = r.db.Entity.Query().Where(where...)
}
- return mapEntityOutErr(q.
+ out, err := mapEntityOutErr(q.
WithFields().
WithTag().
WithParent().
@@ -396,6 +436,18 @@ func (r *EntityRepository) getOneTx(ctx context.Context, tx *ent.Tx, where ...pr
WithAttachments().
Only(ctx),
)
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(
+ attribute.String("entity.id", out.ID.String()),
+ attribute.Int("entity.fields.count", len(out.Fields)),
+ attribute.Int("entity.tags.count", len(out.Tags)),
+ attribute.Int("entity.attachments.count", len(out.Attachments)),
+ attribute.Int("entity.children.count", len(out.Children)),
+ )
+ return out, nil
}
func (r *EntityRepository) getOne(ctx context.Context, where ...predicate.Entity) (EntityOut, error) {
@@ -404,25 +456,93 @@ func (r *EntityRepository) getOne(ctx context.Context, where ...predicate.Entity
// GetOne returns a single entity by ID. If the entity does not exist, an error is returned.
func (r *EntityRepository) GetOne(ctx context.Context, id uuid.UUID) (EntityOut, error) {
- return r.getOne(ctx, entity.ID(id))
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetOne",
+ trace.WithAttributes(attribute.String("entity.id", id.String())))
+ defer span.End()
+
+ out, err := r.getOne(ctx, entity.ID(id))
+ recordSpanError(span, err)
+ return out, err
}
func (r *EntityRepository) CheckRef(ctx context.Context, gid uuid.UUID, ref string) (bool, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.CheckRef",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.import_ref", ref),
+ ))
+ defer span.End()
+
q := r.db.Entity.Query().Where(entity.HasGroupWith(group.ID(gid)))
- return q.Where(entity.ImportRef(ref)).Exist(ctx)
+ exists, err := q.Where(entity.ImportRef(ref)).Exist(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ return exists, err
+ }
+ span.SetAttributes(attribute.Bool("entity.exists", exists))
+ return exists, nil
}
func (r *EntityRepository) GetByRef(ctx context.Context, gid uuid.UUID, ref string) (EntityOut, error) {
- return r.getOne(ctx, entity.ImportRef(ref), entity.HasGroupWith(group.ID(gid)))
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetByRef",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.import_ref", ref),
+ ))
+ defer span.End()
+
+ out, err := r.getOne(ctx, entity.ImportRef(ref), entity.HasGroupWith(group.ID(gid)))
+ recordSpanError(span, err)
+ return out, err
}
// GetOneByGroup returns a single entity by ID, verified to belong to a specific group.
func (r *EntityRepository) GetOneByGroup(ctx context.Context, gid, id uuid.UUID) (EntityOut, error) {
- return r.getOne(ctx, entity.ID(id), entity.HasGroupWith(group.ID(gid)))
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetOneByGroup",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ ))
+ defer span.End()
+
+ out, err := r.getOne(ctx, entity.ID(id), entity.HasGroupWith(group.ID(gid)))
+ recordSpanError(span, err)
+ return out, err
+}
+
+func entityQuerySpanAttrs(gid uuid.UUID, q EntityQuery) []attribute.KeyValue {
+ isLocSet := q.IsLocation != nil
+ isLocValue := false
+ if isLocSet {
+ isLocValue = *q.IsLocation
+ }
+ return []attribute.KeyValue{
+ attribute.String("group.id", gid.String()),
+ attribute.Int("query.page", q.Page),
+ attribute.Int("query.page_size", q.PageSize),
+ attribute.String("query.search", q.Search),
+ attribute.Int("query.tag_ids.count", len(q.TagIDs)),
+ attribute.Bool("query.negate_tags", q.NegateTags),
+ attribute.Int("query.parent_ids.count", len(q.ParentIDs)),
+ attribute.Int("query.parent_item_ids.count", len(q.ParentItemIDs)),
+ attribute.Int("query.fields.count", len(q.Fields)),
+ attribute.Bool("query.only_with_photo", q.OnlyWithPhoto),
+ attribute.Bool("query.only_without_photo", q.OnlyWithoutPhoto),
+ attribute.Bool("query.include_archived", q.IncludeArchived),
+ attribute.Bool("query.filter_children", q.FilterChildren),
+ attribute.String("query.order_by", q.OrderBy),
+ attribute.Bool("query.is_location.set", isLocSet),
+ attribute.Bool("query.is_location.value", isLocValue),
+ attribute.Bool("query.asset_id.set", !q.AssetID.Nil()),
+ }
}
// QueryByGroup returns a list of entities that belong to a specific group based on the provided query.
func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q EntityQuery) (PaginationResult[EntitySummary], error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup",
+ trace.WithAttributes(entityQuerySpanAttrs(gid, q)...))
+ defer span.End()
+
qb := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
)
@@ -478,13 +598,18 @@ func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q En
{
if len(q.TagIDs) > 0 {
tagRepo := &TagRepository{r.db, r.bus}
- descendants, err := tagRepo.GetDescendantTagIDs(ctx, q.TagIDs)
+ ctxDescendants, descSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.tagDescendants",
+ trace.WithAttributes(attribute.Int("query.tag_ids.count", len(q.TagIDs))))
+ descendants, err := tagRepo.GetDescendantTagIDs(ctxDescendants, q.TagIDs)
if err != nil {
+ recordSpanError(descSpan, err)
log.Warn().Err(err).Msg("failed to get descendant tags, using only direct tags")
descendants = q.TagIDs
} else if len(descendants) == 0 {
descendants = q.TagIDs
}
+ descSpan.SetAttributes(attribute.Int("query.tag_descendants.count", len(descendants)))
+ descSpan.End()
var tagPredicates []predicate.Entity
if !q.NegateTags {
@@ -549,10 +674,18 @@ func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q En
qb = qb.Where(entity.And(andPredicates...))
}
- count, err := qb.Count(ctx)
+ span.SetAttributes(attribute.Int("query.predicates.and.count", len(andPredicates)))
+
+ countCtx, countSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.count")
+ count, err := qb.Count(countCtx)
if err != nil {
+ recordSpanError(countSpan, err)
+ countSpan.End()
+ recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
+ countSpan.SetAttributes(attribute.Int("query.total.count", count))
+ countSpan.End()
// Order
switch q.OrderBy {
@@ -583,24 +716,40 @@ func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q En
Limit(q.PageSize)
}
- entities, err := mapEntitiesSummaryErr(qb.All(ctx))
+ fetchCtx, fetchSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.fetch")
+ entities, err := mapEntitiesSummaryErr(qb.All(fetchCtx))
if err != nil {
+ recordSpanError(fetchSpan, err)
+ fetchSpan.End()
+ recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
+ fetchSpan.SetAttributes(attribute.Int("query.results.count", len(entities)))
+ fetchSpan.End()
// Populate ItemCount for location-type entities
if q.IsLocation != nil && *q.IsLocation && len(entities) > 0 {
+ childCtx, childSpan := entityTracer().Start(ctx, "repo.EntityRepository.QueryByGroup.childItemCounts",
+ trace.WithAttributes(attribute.Int("locations.count", len(entities))))
ids := lo.Map(entities, func(e EntitySummary, _ int) uuid.UUID { return e.ID })
- counts, cErr := r.getChildItemCounts(ctx, gid, ids)
- if cErr == nil {
+ counts, cErr := r.getChildItemCounts(childCtx, gid, ids)
+ if cErr != nil {
+ recordSpanError(childSpan, cErr)
+ } else {
for i := range entities {
if c, ok := counts[entities[i].ID]; ok {
entities[i].ItemCount = c
}
}
}
+ childSpan.End()
}
+ span.SetAttributes(
+ attribute.Int("query.results.count", len(entities)),
+ attribute.Int("query.total.count", count),
+ )
+
return PaginationResult[EntitySummary]{
Page: q.Page,
PageSize: q.PageSize,
@@ -611,6 +760,13 @@ func (r *EntityRepository) QueryByGroup(ctx context.Context, gid uuid.UUID, q En
// getChildItemCounts returns a map of entity ID → sum of child item quantities for the given location IDs.
func (r *EntityRepository) getChildItemCounts(ctx context.Context, gid uuid.UUID, locationIDs []uuid.UUID) (map[uuid.UUID]float64, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.getChildItemCounts",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Int("locations.count", len(locationIDs)),
+ ))
+ defer span.End()
+
if len(locationIDs) == 0 {
return nil, nil
}
@@ -637,6 +793,7 @@ func (r *EntityRepository) getChildItemCounts(ctx context.Context, gid uuid.UUID
rows, err := r.db.Sql().QueryContext(ctx, query, args...)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
defer func() { _ = rows.Close() }()
@@ -646,15 +803,30 @@ func (r *EntityRepository) getChildItemCounts(ctx context.Context, gid uuid.UUID
var parentID uuid.UUID
var count float64
if err := rows.Scan(&parentID, &count); err != nil {
+ recordSpanError(span, err)
return nil, err
}
result[parentID] = count
}
- return result, rows.Err()
+ if err := rows.Err(); err != nil {
+ recordSpanError(span, err)
+ return result, err
+ }
+ span.SetAttributes(attribute.Int("results.count", len(result)))
+ return result, nil
}
// QueryByAssetID returns entities by asset ID.
func (r *EntityRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, assetID AssetID, page int, pageSize int) (PaginationResult[EntitySummary], error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.QueryByAssetID",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Int64("entity.asset_id", int64(assetID)),
+ attribute.Int("query.page", page),
+ attribute.Int("query.page_size", pageSize),
+ ))
+ defer span.End()
+
qb := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
entity.AssetID(int64(assetID)),
@@ -676,9 +848,11 @@ func (r *EntityRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, as
All(ctx),
)
if err != nil {
+ recordSpanError(span, err)
return PaginationResult[EntitySummary]{}, err
}
+ span.SetAttributes(attribute.Int("query.results.count", len(entities)))
return PaginationResult[EntitySummary]{
Page: page,
PageSize: pageSize,
@@ -689,16 +863,30 @@ func (r *EntityRepository) QueryByAssetID(ctx context.Context, gid uuid.UUID, as
// GetAll returns all the entities in the database with the Tags, Parent, and EntityType eager loaded.
func (r *EntityRepository) GetAll(ctx context.Context, gid uuid.UUID) ([]EntityOut, error) {
- return mapEntitiesOutErr(r.db.Entity.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAll",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ out, err := mapEntitiesOutErr(r.db.Entity.Query().
Where(entity.HasGroupWith(group.ID(gid))).
WithTag().
WithParent().
WithEntityType().
WithFields().
All(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("entities.count", len(out)))
+ return out, nil
}
func (r *EntityRepository) GetAllZeroAssetID(ctx context.Context, gid uuid.UUID) ([]EntitySummary, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllZeroAssetID",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
q := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
entity.AssetID(0),
@@ -706,10 +894,23 @@ func (r *EntityRepository) GetAllZeroAssetID(ctx context.Context, gid uuid.UUID)
ent.Asc(entity.FieldCreatedAt),
)
- return mapEntitiesSummaryErr(q.All(ctx))
+ out, err := mapEntitiesSummaryErr(q.All(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("entities.count", len(out)))
+ return out, nil
}
func (r *EntityRepository) GetHighestAssetIDTx(ctx context.Context, tx *ent.Tx, gid uuid.UUID) (AssetID, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetHighestAssetIDTx",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Bool("tx", tx != nil),
+ ))
+ defer span.End()
+
var q *ent.EntityQuery
if tx != nil {
q = tx.Entity.Query().Where(
@@ -730,9 +931,11 @@ func (r *EntityRepository) GetHighestAssetIDTx(ctx context.Context, tx *ent.Tx,
if ent.IsNotFound(err) {
return 0, nil
}
+ recordSpanError(span, err)
return 0, err
}
+ span.SetAttributes(attribute.Int64("entity.asset_id.highest", result.AssetID))
return AssetID(result.AssetID), nil
}
@@ -741,12 +944,21 @@ func (r *EntityRepository) GetHighestAssetID(ctx context.Context, gid uuid.UUID)
}
func (r *EntityRepository) SetAssetID(ctx context.Context, gid uuid.UUID, id uuid.UUID, assetID AssetID) error {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.SetAssetID",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ attribute.Int64("entity.asset_id", int64(assetID)),
+ ))
+ defer span.End()
+
q := r.db.Entity.Update().Where(
entity.HasGroupWith(group.ID(gid)),
entity.ID(id),
)
_, err := q.SetAssetID(int64(assetID)).Save(ctx)
+ recordSpanError(span, err)
return err
}
@@ -759,7 +971,20 @@ func validateQuantity(op string, quantity float64) error {
}
func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data EntityCreate) (EntityOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Create",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.name", data.Name),
+ attribute.Float64("entity.quantity", data.Quantity),
+ attribute.Bool("entity.parent_id.set", data.ParentID != uuid.Nil),
+ attribute.Bool("entity.entity_type_id.set", data.EntityTypeID != uuid.Nil),
+ attribute.Int("entity.tags.count", len(data.TagIDs)),
+ attribute.Int64("entity.asset_id", int64(data.AssetID)),
+ ))
+ defer span.End()
+
if err := validateQuantity("create entity", data.Quantity); err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
@@ -781,6 +1006,7 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data Entit
// Auto-resolve default "Item" entity type for the group
etID, err := r.resolveDefaultEntityType(ctx, gid, false)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
q.SetEntityTypeID(etID)
@@ -792,11 +1018,15 @@ func (r *EntityRepository) Create(ctx context.Context, gid uuid.UUID, data Entit
result, err := q.Save(ctx)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ span.SetAttributes(attribute.String("entity.id", result.ID.String()))
r.publishMutationEvent(gid)
- return r.GetOne(ctx, result.ID)
+ out, err := r.GetOne(ctx, result.ID)
+ recordSpanError(span, err)
+ return out, err
}
// EntityCreateFromTemplate contains all data needed to create an entity from a template.
@@ -817,12 +1047,26 @@ type EntityCreateFromTemplate struct {
// CreateFromTemplate creates an entity with all template data in a single transaction.
func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUID, data EntityCreateFromTemplate) (EntityOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.CreateFromTemplate",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.name", data.Name),
+ attribute.Float64("entity.quantity", data.Quantity),
+ attribute.Bool("entity.parent_id.set", data.ParentID != uuid.Nil),
+ attribute.Bool("entity.entity_type_id.set", data.EntityTypeID != uuid.Nil),
+ attribute.Int("entity.tags.count", len(data.TagIDs)),
+ attribute.Int("entity.fields.count", len(data.Fields)),
+ ))
+ defer span.End()
+
if err := validateQuantity("create entity from template", data.Quantity); err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
tx, err := r.db.Tx(ctx)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
committed := false
@@ -837,12 +1081,17 @@ func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUID
// Get next asset ID within transaction
nextAssetID, err := r.GetHighestAssetIDTx(ctx, tx, gid)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
nextAssetID++
+ span.SetAttributes(attribute.Int64("entity.asset_id", int64(nextAssetID)))
// Create entity with all template data
newEntityID := uuid.New()
+ span.SetAttributes(attribute.String("entity.id", newEntityID.String()))
+
+ entityCtx, entitySpan := entityTracer().Start(ctx, "repo.EntityRepository.CreateFromTemplate.entity")
entityBuilder := tx.Entity.Create().
SetID(newEntityID).
SetName(data.Name).
@@ -868,88 +1117,148 @@ func (r *EntityRepository) CreateFromTemplate(ctx context.Context, gid uuid.UUID
entityBuilder.AddTagIDs(data.TagIDs...)
}
- _, err = entityBuilder.Save(ctx)
+ _, err = entityBuilder.Save(entityCtx)
if err != nil {
+ recordSpanError(entitySpan, err)
+ entitySpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ entitySpan.End()
- // Create custom fields
- for _, field := range data.Fields {
- _, err = tx.EntityField.Create().
- SetEntityID(newEntityID).
- SetType(entityfield.Type(field.Type)).
- SetName(field.Name).
- SetTextValue(field.TextValue).
- Save(ctx)
- if err != nil {
- return EntityOut{}, fmt.Errorf("failed to create field %s: %w", field.Name, err)
+ if len(data.Fields) > 0 {
+ fieldsCtx, fieldsSpan := entityTracer().Start(ctx, "repo.EntityRepository.CreateFromTemplate.fields",
+ trace.WithAttributes(attribute.Int("fields.count", len(data.Fields))))
+ for _, field := range data.Fields {
+ _, err = tx.EntityField.Create().
+ SetEntityID(newEntityID).
+ SetType(entityfield.Type(field.Type)).
+ SetName(field.Name).
+ SetTextValue(field.TextValue).
+ Save(fieldsCtx)
+ if err != nil {
+ wrapped := fmt.Errorf("failed to create field %s: %w", field.Name, err)
+ recordSpanError(fieldsSpan, wrapped)
+ fieldsSpan.End()
+ recordSpanError(span, wrapped)
+ return EntityOut{}, wrapped
+ }
}
+ fieldsSpan.End()
}
+ _, commitSpan := entityTracer().Start(ctx, "repo.EntityRepository.CreateFromTemplate.commit")
if err = tx.Commit(); err != nil {
+ recordSpanError(commitSpan, err)
+ commitSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ commitSpan.End()
committed = true
r.publishMutationEvent(gid)
- return r.GetOne(ctx, newEntityID)
+ out, err := r.GetOne(ctx, newEntityID)
+ recordSpanError(span, err)
+ return out, err
}
func (r *EntityRepository) Delete(ctx context.Context, id uuid.UUID) error {
- // Get the entity with its group and attachments before deletion
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Delete",
+ trace.WithAttributes(attribute.String("entity.id", id.String())))
+ defer span.End()
+
+ loadCtx, loadSpan := entityTracer().Start(ctx, "repo.EntityRepository.Delete.load")
e, err := r.db.Entity.Query().
Where(entity.ID(id)).
WithGroup().
WithAttachments().
- Only(ctx)
+ Only(loadCtx)
if err != nil {
+ recordSpanError(loadSpan, err)
+ loadSpan.End()
+ recordSpanError(span, err)
return err
}
+ loadSpan.End()
// Get the group ID for attachment deletion
var gid uuid.UUID
if e.Edges.Group != nil {
gid = e.Edges.Group.ID
}
+ span.SetAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Int("entity.attachments.count", len(e.Edges.Attachments)),
+ )
- // Delete all attachments (and their files) before deleting the entity
- for _, att := range e.Edges.Attachments {
- err := r.attachments.Delete(ctx, gid, att.ID)
- if err != nil {
- log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during entity deletion")
+ if len(e.Edges.Attachments) > 0 {
+ attCtx, attSpan := entityTracer().Start(ctx, "repo.EntityRepository.Delete.attachments",
+ trace.WithAttributes(attribute.Int("attachments.count", len(e.Edges.Attachments))))
+ for _, att := range e.Edges.Attachments {
+ err := r.attachments.Delete(attCtx, gid, att.ID)
+ if err != nil {
+ recordSpanError(attSpan, err)
+ log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during entity deletion")
+ }
}
+ attSpan.End()
}
+ _, deleteSpan := entityTracer().Start(ctx, "repo.EntityRepository.Delete.entity")
err = r.db.Entity.DeleteOneID(id).Exec(ctx)
if err != nil {
+ recordSpanError(deleteSpan, err)
+ deleteSpan.End()
+ recordSpanError(span, err)
return err
}
+ deleteSpan.End()
r.publishMutationEvent(id)
return nil
}
func (r *EntityRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID) error {
- // Get the entity with its attachments before deletion
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.DeleteByGroup",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ ))
+ defer span.End()
+
+ loadCtx, loadSpan := entityTracer().Start(ctx, "repo.EntityRepository.DeleteByGroup.load")
e, err := r.db.Entity.Query().
Where(
entity.ID(id),
entity.HasGroupWith(group.ID(gid)),
).
WithAttachments().
- Only(ctx)
+ Only(loadCtx)
if err != nil {
+ recordSpanError(loadSpan, err)
+ loadSpan.End()
+ recordSpanError(span, err)
return err
}
+ loadSpan.End()
- // Delete all attachments (and their files) before deleting the entity
- for _, att := range e.Edges.Attachments {
- err := r.attachments.Delete(ctx, gid, att.ID)
- if err != nil {
- log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during entity deletion")
+ span.SetAttributes(attribute.Int("entity.attachments.count", len(e.Edges.Attachments)))
+
+ if len(e.Edges.Attachments) > 0 {
+ attCtx, attSpan := entityTracer().Start(ctx, "repo.EntityRepository.DeleteByGroup.attachments",
+ trace.WithAttributes(attribute.Int("attachments.count", len(e.Edges.Attachments))))
+ for _, att := range e.Edges.Attachments {
+ err := r.attachments.Delete(attCtx, gid, att.ID)
+ if err != nil {
+ recordSpanError(attSpan, err)
+ log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during entity deletion")
+ }
}
+ attSpan.End()
}
+ _, deleteSpan := entityTracer().Start(ctx, "repo.EntityRepository.DeleteByGroup.entity")
_, err = r.db.Entity.
Delete().
Where(
@@ -957,46 +1266,74 @@ func (r *EntityRepository) DeleteByGroup(ctx context.Context, gid, id uuid.UUID)
entity.HasGroupWith(group.ID(gid)),
).Exec(ctx)
if err != nil {
+ recordSpanError(deleteSpan, err)
+ deleteSpan.End()
+ recordSpanError(span, err)
return err
}
+ deleteSpan.End()
r.publishMutationEvent(gid)
- return err
+ return nil
}
func (r *EntityRepository) WipeInventory(ctx context.Context, gid uuid.UUID, wipeTags bool, wipeContainers bool, wipeMaintenance bool) (int, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Bool("wipe.tags", wipeTags),
+ attribute.Bool("wipe.containers", wipeContainers),
+ attribute.Bool("wipe.maintenance", wipeMaintenance),
+ ))
+ defer span.End()
+
deleted := 0
// Wipe maintenance records if requested
// IMPORTANT: Must delete maintenance records BEFORE entities since they are linked to entities
if wipeMaintenance {
+ maintCtx, maintSpan := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory.maintenance")
maintenanceCount, err := r.db.MaintenanceEntry.Delete().
Where(maintenanceentry.HasEntityWith(entity.HasGroupWith(group.ID(gid)))).
- Exec(ctx)
+ Exec(maintCtx)
if err != nil {
+ recordSpanError(maintSpan, err)
log.Err(err).Msg("failed to delete maintenance entries during wipe inventory")
} else {
+ maintSpan.SetAttributes(attribute.Int("deleted.count", maintenanceCount))
log.Info().Int("count", maintenanceCount).Msg("deleted maintenance entries during wipe inventory")
deleted += maintenanceCount
}
+ maintSpan.End()
}
- // Get all entities for the group
+ loadCtx, loadSpan := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory.loadEntities")
entities, err := r.db.Entity.Query().
Where(entity.HasGroupWith(group.ID(gid))).
WithAttachments().
- All(ctx)
+ All(loadCtx)
if err != nil {
+ recordSpanError(loadSpan, err)
+ loadSpan.End()
+ recordSpanError(span, err)
return 0, err
}
+ loadSpan.SetAttributes(attribute.Int("entities.count", len(entities)))
+ loadSpan.End()
- // Delete each entity with its attachments
+ entCtx, entSpan := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory.deleteEntities",
+ trace.WithAttributes(attribute.Int("entities.count", len(entities))))
+ entityDeleted := 0
+ attachmentsDeleted := 0
for _, e := range entities {
for _, att := range e.Edges.Attachments {
- err := r.attachments.Delete(ctx, gid, att.ID)
+ err := r.attachments.Delete(entCtx, gid, att.ID)
if err != nil {
+ recordSpanError(entSpan, err)
log.Err(err).Str("attachment_id", att.ID.String()).Msg("failed to delete attachment during wipe inventory")
+ continue
}
+ attachmentsDeleted++
}
_, err = r.db.Entity.
@@ -1004,47 +1341,79 @@ func (r *EntityRepository) WipeInventory(ctx context.Context, gid uuid.UUID, wip
Where(
entity.ID(e.ID),
entity.HasGroupWith(group.ID(gid)),
- ).Exec(ctx)
+ ).Exec(entCtx)
if err != nil {
+ recordSpanError(entSpan, err)
log.Err(err).Str("entity_id", e.ID.String()).Msg("failed to delete entity during wipe inventory")
continue
}
- deleted++
+ entityDeleted++
}
+ entSpan.SetAttributes(
+ attribute.Int("entities.deleted.count", entityDeleted),
+ attribute.Int("attachments.deleted.count", attachmentsDeleted),
+ )
+ entSpan.End()
+ deleted += entityDeleted
// Wipe tags if requested
if wipeTags {
- tagCount, err := r.db.Tag.Delete().Where(tag.HasGroupWith(group.ID(gid))).Exec(ctx)
+ tagCtx, tagSpan := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory.tags")
+ tagCount, err := r.db.Tag.Delete().Where(tag.HasGroupWith(group.ID(gid))).Exec(tagCtx)
if err != nil {
+ recordSpanError(tagSpan, err)
log.Err(err).Msg("failed to delete tags during wipe inventory")
} else {
+ tagSpan.SetAttributes(attribute.Int("deleted.count", tagCount))
log.Info().Int("count", tagCount).Msg("deleted tags during wipe inventory")
deleted += tagCount
}
+ tagSpan.End()
}
// Wipe containers (location-type entities) if requested
if wipeContainers {
+ containerCtx, containerSpan := entityTracer().Start(ctx, "repo.EntityRepository.WipeInventory.containers")
containerCount, err := r.db.Entity.Delete().
Where(
entity.HasGroupWith(group.ID(gid)),
entity.HasEntityTypeWith(entitytype.IsLocation(true)),
- ).Exec(ctx)
+ ).Exec(containerCtx)
if err != nil {
+ recordSpanError(containerSpan, err)
log.Err(err).Msg("failed to delete containers during wipe inventory")
} else {
+ containerSpan.SetAttributes(attribute.Int("deleted.count", containerCount))
log.Info().Int("count", containerCount).Msg("deleted containers during wipe inventory")
deleted += containerCount
}
+ containerSpan.End()
}
+ span.SetAttributes(attribute.Int("deleted.count.total", deleted))
r.publishMutationEvent(gid)
return deleted, nil
}
func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, data EntityUpdate) (EntityOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", data.ID.String()),
+ attribute.String("entity.name", data.Name),
+ attribute.Float64("entity.quantity", data.Quantity),
+ attribute.Bool("entity.archived", data.Archived),
+ attribute.Bool("entity.parent_id.set", data.ParentID != uuid.Nil),
+ attribute.Bool("entity.entity_type_id.set", data.EntityTypeID != uuid.Nil),
+ attribute.Bool("entity.sync_child_locations", data.SyncChildEntityLocations),
+ attribute.Int("entity.tags.count", len(data.TagIDs)),
+ attribute.Int("entity.fields.count", len(data.Fields)),
+ ))
+ defer span.End()
+
if err := validateQuantity("update entity", data.Quantity); err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
@@ -1075,24 +1444,36 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat
q.SetEntityTypeID(data.EntityTypeID)
}
- currentTags, err := r.db.Entity.Query().Where(entity.ID(data.ID)).QueryTag().All(ctx)
+ tagsCtx, tagsSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.tags")
+ currentTags, err := r.db.Entity.Query().Where(entity.ID(data.ID)).QueryTag().All(tagsCtx)
if err != nil {
+ recordSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
set := newIDSet(currentTags)
+ added := 0
for _, l := range data.TagIDs {
if set.Contains(l) {
set.Remove(l)
continue
}
q.AddTagIDs(l)
+ added++
}
- if set.Len() > 0 {
+ removed := set.Len()
+ if removed > 0 {
q.RemoveTagIDs(set.Slice()...)
}
+ tagsSpan.SetAttributes(
+ attribute.Int("tags.added.count", added),
+ attribute.Int("tags.removed.count", removed),
+ )
+ tagsSpan.End()
if data.ParentID != uuid.Nil {
q.SetParentID(data.ParentID)
@@ -1101,40 +1482,64 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat
}
if data.SyncChildEntityLocations {
- children, err := r.db.Entity.Query().Where(entity.ID(data.ID)).QueryChildren().All(ctx)
+ syncCtx, syncSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.syncChildLocations")
+ children, err := r.db.Entity.Query().Where(entity.ID(data.ID)).QueryChildren().All(syncCtx)
if err != nil {
+ recordSpanError(syncSpan, err)
+ syncSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ syncSpan.SetAttributes(attribute.Int("children.count", len(children)))
+ updatedCount := 0
for _, child := range children {
if data.ParentID != uuid.Nil {
- childParent, err := child.QueryParent().First(ctx)
+ childParent, err := child.QueryParent().First(syncCtx)
if err != nil || childParent.ID != data.ParentID {
- err = child.Update().SetParentID(data.ParentID).Exec(ctx)
+ err = child.Update().SetParentID(data.ParentID).Exec(syncCtx)
if err != nil {
+ recordSpanError(syncSpan, err)
+ syncSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ updatedCount++
}
}
}
+ syncSpan.SetAttributes(attribute.Int("children.updated.count", updatedCount))
+ syncSpan.End()
}
+ _, execSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.exec")
err = q.Exec(ctx)
if err != nil {
+ recordSpanError(execSpan, err)
+ execSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ execSpan.End()
- fields, err := r.db.EntityField.Query().Where(entityfield.HasEntityWith(entity.ID(data.ID))).All(ctx)
+ fieldsCtx, fieldsSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateByGroup.fields",
+ trace.WithAttributes(attribute.Int("fields.input.count", len(data.Fields))))
+ fields, err := r.db.EntityField.Query().Where(entityfield.HasEntityWith(entity.ID(data.ID))).All(fieldsCtx)
if err != nil {
+ recordSpanError(fieldsSpan, err)
+ fieldsSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
fieldIds := newIDSet(fields)
+ fieldsSpan.SetAttributes(attribute.Int("fields.existing.count", len(fields)))
+ createdFields := 0
+ updatedFields := 0
// Update Existing Fields
for _, f := range data.Fields {
if f.ID == uuid.Nil {
- // Create New Field
_, err = r.db.EntityField.Create().
SetEntityID(data.ID).
SetType(entityfield.Type(f.Type)).
@@ -1142,10 +1547,14 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat
SetTextValue(f.TextValue).
SetNumberValue(f.NumberValue).
SetBooleanValue(f.BooleanValue).
- Save(ctx)
+ Save(fieldsCtx)
if err != nil {
+ recordSpanError(fieldsSpan, err)
+ fieldsSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ createdFields++
}
opt := r.db.EntityField.Update().
@@ -1159,32 +1568,51 @@ func (r *EntityRepository) UpdateByGroup(ctx context.Context, gid uuid.UUID, dat
SetNumberValue(f.NumberValue).
SetBooleanValue(f.BooleanValue)
- _, err = opt.Save(ctx)
+ _, err = opt.Save(fieldsCtx)
if err != nil {
+ recordSpanError(fieldsSpan, err)
+ fieldsSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ updatedFields++
fieldIds.Remove(f.ID)
continue
}
- // Delete Fields that are no longer present
+ deletedFields := 0
if fieldIds.Len() > 0 {
- _, err = r.db.EntityField.Delete().
+ deletedFields, err = r.db.EntityField.Delete().
Where(
entityfield.IDIn(fieldIds.Slice()...),
entityfield.HasEntityWith(entity.ID(data.ID)),
- ).Exec(ctx)
+ ).Exec(fieldsCtx)
if err != nil {
+ recordSpanError(fieldsSpan, err)
+ fieldsSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
}
+ fieldsSpan.SetAttributes(
+ attribute.Int("fields.created.count", createdFields),
+ attribute.Int("fields.updated.count", updatedFields),
+ attribute.Int("fields.deleted.count", deletedFields),
+ )
+ fieldsSpan.End()
r.publishMutationEvent(gid)
- return r.GetOne(ctx, data.ID)
+ out, err := r.GetOne(ctx, data.ID)
+ recordSpanError(span, err)
+ return out, err
}
func (r *EntityRepository) GetAllZeroImportRef(ctx context.Context, gid uuid.UUID) ([]uuid.UUID, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllZeroImportRef",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
var ids []uuid.UUID
err := r.db.Entity.Query().
@@ -1198,15 +1626,30 @@ func (r *EntityRepository) GetAllZeroImportRef(ctx context.Context, gid uuid.UUI
Select(entity.FieldID).
Scan(ctx, &ids)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
+ span.SetAttributes(attribute.Int("entities.count", len(ids)))
return ids, nil
}
func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data EntityPatch) error {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Patch",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ attribute.Bool("patch.import_ref.set", data.ImportRef != nil),
+ attribute.Bool("patch.quantity.set", data.Quantity != nil),
+ attribute.Bool("patch.parent_id.set", data.ParentID != uuid.Nil),
+ attribute.Bool("patch.entity_type_id.set", data.EntityTypeID != uuid.Nil),
+ attribute.Bool("patch.tag_ids.set", data.TagIDs != nil),
+ ))
+ defer span.End()
+
tx, err := r.db.Tx(ctx)
if err != nil {
+ recordSpanError(span, err)
return err
}
committed := false
@@ -1230,6 +1673,7 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
if data.Quantity != nil {
if err := validateQuantity("patch entity", *data.Quantity); err != nil {
+ recordSpanError(span, err)
return err
}
@@ -1244,14 +1688,24 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
q.SetEntityTypeID(data.EntityTypeID)
}
+ _, execSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.exec")
err = q.Exec(ctx)
if err != nil {
+ recordSpanError(execSpan, err)
+ execSpan.End()
+ recordSpanError(span, err)
return err
}
+ execSpan.End()
if data.TagIDs != nil {
- currentTags, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).QueryTag().All(ctx)
+ tagsCtx, tagsSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.tags",
+ trace.WithAttributes(attribute.Int("tags.input.count", len(data.TagIDs))))
+ currentTags, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).QueryTag().All(tagsCtx)
if err != nil {
+ recordSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordSpanError(span, err)
return err
}
set := newIDSet(currentTags)
@@ -1269,7 +1723,10 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
if err := tx.Entity.Update().
Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).
AddTagIDs(addTags...).
- Exec(ctx); err != nil {
+ Exec(tagsCtx); err != nil {
+ recordSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordSpanError(span, err)
return err
}
}
@@ -1277,37 +1734,68 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
if err := tx.Entity.Update().
Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).
RemoveTagIDs(set.Slice()...).
- Exec(ctx); err != nil {
+ Exec(tagsCtx); err != nil {
+ recordSpanError(tagsSpan, err)
+ tagsSpan.End()
+ recordSpanError(span, err)
return err
}
}
+ tagsSpan.SetAttributes(
+ attribute.Int("tags.added.count", len(addTags)),
+ attribute.Int("tags.removed.count", set.Len()),
+ )
+ tagsSpan.End()
}
if data.ParentID != uuid.Nil {
- entityEnt, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).Only(ctx)
+ syncCtx, syncSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.syncChildLocations")
+ entityEnt, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).Only(syncCtx)
if err != nil {
+ recordSpanError(syncSpan, err)
+ syncSpan.End()
+ recordSpanError(span, err)
return err
}
+ syncSpan.SetAttributes(attribute.Bool("entity.sync_child_locations", entityEnt.SyncChildEntityLocations))
if entityEnt.SyncChildEntityLocations {
- children, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).QueryChildren().All(ctx)
+ children, err := tx.Entity.Query().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).QueryChildren().All(syncCtx)
if err != nil {
+ recordSpanError(syncSpan, err)
+ syncSpan.End()
+ recordSpanError(span, err)
return err
}
+ updatedCount := 0
for _, child := range children {
- childParent, err := child.QueryParent().First(ctx)
+ childParent, err := child.QueryParent().First(syncCtx)
if err != nil || childParent.ID != data.ParentID {
- err = child.Update().SetParentID(data.ParentID).Exec(ctx)
+ err = child.Update().SetParentID(data.ParentID).Exec(syncCtx)
if err != nil {
+ recordSpanError(syncSpan, err)
+ syncSpan.End()
+ recordSpanError(span, err)
return err
}
+ updatedCount++
}
}
+ syncSpan.SetAttributes(
+ attribute.Int("children.count", len(children)),
+ attribute.Int("children.updated.count", updatedCount),
+ )
}
+ syncSpan.End()
}
+ _, commitSpan := entityTracer().Start(ctx, "repo.EntityRepository.Patch.commit")
if err := tx.Commit(); err != nil {
+ recordSpanError(commitSpan, err)
+ commitSpan.End()
+ recordSpanError(span, err)
return err
}
+ commitSpan.End()
committed = true
r.publishMutationEvent(gid)
@@ -1315,6 +1803,13 @@ func (r *EntityRepository) Patch(ctx context.Context, gid, id uuid.UUID, data En
}
func (r *EntityRepository) GetAllCustomFieldValues(ctx context.Context, gid uuid.UUID, name string) ([]string, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllCustomFieldValues",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("field.name", name),
+ ))
+ defer span.End()
+
type st struct {
Value string `json:"text_value"`
}
@@ -1333,17 +1828,24 @@ func (r *EntityRepository) GetAllCustomFieldValues(ctx context.Context, gid uuid
Select(entityfield.FieldTextValue).
Scan(ctx, &values)
if err != nil {
- return nil, fmt.Errorf("failed to get field values: %w", err)
+ wrapped := fmt.Errorf("failed to get field values: %w", err)
+ recordSpanError(span, wrapped)
+ return nil, wrapped
}
valueStrings := lo.Map(values, func(f st, _ int) string {
return f.Value
})
+ span.SetAttributes(attribute.Int("values.count", len(valueStrings)))
return valueStrings, nil
}
func (r *EntityRepository) GetAllCustomFieldNames(ctx context.Context, gid uuid.UUID) ([]string, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllCustomFieldNames",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
type st struct {
Name string `json:"name"`
}
@@ -1359,18 +1861,25 @@ func (r *EntityRepository) GetAllCustomFieldNames(ctx context.Context, gid uuid.
Select(entityfield.FieldName).
Scan(ctx, &fields)
if err != nil {
- return nil, fmt.Errorf("failed to get custom fields: %w", err)
+ wrapped := fmt.Errorf("failed to get custom fields: %w", err)
+ recordSpanError(span, wrapped)
+ return nil, wrapped
}
fieldNames := lo.Map(fields, func(f st, _ int) string {
return f.Name
})
+ span.SetAttributes(attribute.Int("names.count", len(fieldNames)))
return fieldNames, nil
}
// ZeroOutTimeFields sets all date fields to the beginning of the day.
func (r *EntityRepository) ZeroOutTimeFields(ctx context.Context, gid uuid.UUID) (int, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.ZeroOutTimeFields",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
q := r.db.Entity.Query().Where(
entity.HasGroupWith(group.ID(gid)),
entity.Or(
@@ -1383,15 +1892,28 @@ func (r *EntityRepository) ZeroOutTimeFields(ctx context.Context, gid uuid.UUID)
),
)
- entities, err := q.All(ctx)
+ loadCtx, loadSpan := entityTracer().Start(ctx, "repo.EntityRepository.ZeroOutTimeFields.load")
+ entities, err := q.All(loadCtx)
if err != nil {
- return -1, fmt.Errorf("ZeroOutTimeFields() -> failed to get entities: %w", err)
+ wrapped := fmt.Errorf("ZeroOutTimeFields() -> failed to get entities: %w", err)
+ recordSpanError(loadSpan, wrapped)
+ loadSpan.End()
+ recordSpanError(span, wrapped)
+ return -1, wrapped
}
+ loadSpan.SetAttributes(attribute.Int("entities.count", len(entities)))
+ loadSpan.End()
toDateOnly := func(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
}
+ _, updateSpan := entityTracer().Start(ctx, "repo.EntityRepository.ZeroOutTimeFields.update",
+ trace.WithAttributes(attribute.Int("entities.count", len(entities))))
+ defer func() {
+ updateSpan.End()
+ }()
+
updated := 0
for _, e := range entities {
@@ -1432,17 +1954,26 @@ func (r *EntityRepository) ZeroOutTimeFields(ctx context.Context, gid uuid.UUID)
_, err = updateQ.Save(ctx)
if err != nil {
- return updated, fmt.Errorf("ZeroOutTimeFields() -> failed to update entity: %w", err)
+ wrapped := fmt.Errorf("ZeroOutTimeFields() -> failed to update entity: %w", err)
+ recordSpanError(updateSpan, wrapped)
+ recordSpanError(span, wrapped)
+ return updated, wrapped
}
updated++
}
+ updateSpan.SetAttributes(attribute.Int("entities.updated.count", updated))
+ span.SetAttributes(attribute.Int("entities.updated.count", updated))
return updated, nil
}
func (r *EntityRepository) SetPrimaryPhotos(ctx context.Context, gid uuid.UUID) (int, error) {
- // All entities where there is no primary photo
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.SetPrimaryPhotos",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ loadCtx, loadSpan := entityTracer().Start(ctx, "repo.EntityRepository.SetPrimaryPhotos.load")
entityIDs, err := r.db.Entity.Query().
Where(
entity.HasGroupWith(group.ID(gid)),
@@ -1456,10 +1987,19 @@ func (r *EntityRepository) SetPrimaryPhotos(ctx context.Context, gid uuid.UUID)
),
),
).
- IDs(ctx)
+ IDs(loadCtx)
if err != nil {
+ recordSpanError(loadSpan, err)
+ loadSpan.End()
+ recordSpanError(span, err)
return -1, err
}
+ loadSpan.SetAttributes(attribute.Int("entities.count", len(entityIDs)))
+ loadSpan.End()
+
+ updateCtx, updateSpan := entityTracer().Start(ctx, "repo.EntityRepository.SetPrimaryPhotos.update",
+ trace.WithAttributes(attribute.Int("entities.count", len(entityIDs))))
+ defer updateSpan.End()
updated := 0
for _, id := range entityIDs {
@@ -1469,28 +2009,46 @@ func (r *EntityRepository) SetPrimaryPhotos(ctx context.Context, gid uuid.UUID)
attachment.TypeEQ(attachment.TypePhoto),
attachment.Primary(false),
).
- First(ctx)
+ First(updateCtx)
if err != nil {
+ recordSpanError(updateSpan, err)
+ recordSpanError(span, err)
return updated, err
}
_, err = r.db.Attachment.UpdateOne(a).
SetPrimary(true).
- Save(ctx)
+ Save(updateCtx)
if err != nil {
+ recordSpanError(updateSpan, err)
+ recordSpanError(span, err)
return updated, err
}
updated++
}
+ updateSpan.SetAttributes(attribute.Int("entities.updated.count", updated))
+ span.SetAttributes(attribute.Int("entities.updated.count", updated))
return updated, nil
}
// Duplicate creates a copy of an entity with configurable options for what data to copy.
func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, options DuplicateOptions) (EntityOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.source_id", id.String()),
+ attribute.Bool("options.copy_maintenance", options.CopyMaintenance),
+ attribute.Bool("options.copy_attachments", options.CopyAttachments),
+ attribute.Bool("options.copy_custom_fields", options.CopyCustomFields),
+ attribute.String("options.copy_prefix", options.CopyPrefix),
+ ))
+ defer span.End()
+
tx, err := r.db.Tx(ctx)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
committed := false
@@ -1505,11 +2063,13 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
// Get the original entity with all its data
originalEntity, err := r.getOneTx(ctx, tx, entity.ID(id), entity.HasGroupWith(group.ID(gid)))
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
nextAssetID, err := r.GetHighestAssetIDTx(ctx, tx, gid)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
nextAssetID++
@@ -1519,6 +2079,12 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
}
newEntityID := uuid.New()
+ span.SetAttributes(
+ attribute.String("entity.new_id", newEntityID.String()),
+ attribute.Int64("entity.new_asset_id", int64(nextAssetID)),
+ )
+
+ entityCtx, entitySpan := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate.entity")
entityBuilder := tx.Entity.Create().
SetID(newEntityID).
SetName(options.CopyPrefix + originalEntity.Name).
@@ -1560,13 +2126,20 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
entityBuilder.AddTagIDs(tagIDs...)
}
- _, err = entityBuilder.Save(ctx)
+ _, err = entityBuilder.Save(entityCtx)
if err != nil {
+ recordSpanError(entitySpan, err)
+ entitySpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ entitySpan.End()
// Copy custom fields if requested
if options.CopyCustomFields {
+ fieldsCtx, fieldsSpan := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate.fields",
+ trace.WithAttributes(attribute.Int("fields.count", len(originalEntity.Fields))))
+ copied := 0
for _, field := range originalEntity.Fields {
_, err = tx.EntityField.Create().
SetEntityID(newEntityID).
@@ -1575,21 +2148,29 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
SetTextValue(field.TextValue).
SetNumberValue(field.NumberValue).
SetBooleanValue(field.BooleanValue).
- Save(ctx)
+ Save(fieldsCtx)
if err != nil {
+ recordSpanError(fieldsSpan, err)
log.Warn().Err(err).Str("field_name", field.Name).Msg("failed to copy custom field during duplication")
continue
}
+ copied++
}
+ fieldsSpan.SetAttributes(attribute.Int("fields.copied.count", copied))
+ fieldsSpan.End()
}
// Copy attachments if requested
if options.CopyAttachments {
+ attCtx, attSpan := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate.attachments",
+ trace.WithAttributes(attribute.Int("attachments.count", len(originalEntity.Attachments))))
+ copied := 0
for _, att := range originalEntity.Attachments {
originalAttachment, err := tx.Attachment.Query().
Where(attachment.ID(att.ID)).
- Only(ctx)
+ Only(attCtx)
if err != nil {
+ recordSpanError(attSpan, err)
log.Warn().Err(err).Str("attachment_id", att.ID.String()).Msg("failed to find attachment during duplication")
continue
}
@@ -1601,20 +2182,29 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
SetPath(originalAttachment.Path).
SetMimeType(originalAttachment.MimeType).
SetPrimary(originalAttachment.Primary).
- Save(ctx)
+ Save(attCtx)
if err != nil {
+ recordSpanError(attSpan, err)
log.Warn().Err(err).Str("original_attachment_id", att.ID.String()).Msg("failed to copy attachment during duplication")
continue
}
+ copied++
}
+ attSpan.SetAttributes(attribute.Int("attachments.copied.count", copied))
+ attSpan.End()
}
// Copy maintenance entries if requested
if options.CopyMaintenance {
+ maintCtx, maintSpan := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate.maintenance")
maintenanceEntries, err := tx.MaintenanceEntry.Query().
Where(maintenanceentry.HasEntityWith(entity.ID(id))).
- All(ctx)
- if err == nil {
+ All(maintCtx)
+ if err != nil {
+ recordSpanError(maintSpan, err)
+ } else {
+ maintSpan.SetAttributes(attribute.Int("maintenance.count", len(maintenanceEntries)))
+ copied := 0
for _, entry := range maintenanceEntries {
_, err = tx.MaintenanceEntry.Create().
SetEntityID(newEntityID).
@@ -1623,22 +2213,33 @@ func (r *EntityRepository) Duplicate(ctx context.Context, gid, id uuid.UUID, opt
SetName(entry.Name).
SetDescription(entry.Description).
SetCost(entry.Cost).
- Save(ctx)
+ Save(maintCtx)
if err != nil {
+ recordSpanError(maintSpan, err)
log.Warn().Err(err).Str("maintenance_entry_id", entry.ID.String()).Msg("failed to copy maintenance entry during duplication")
continue
}
+ copied++
}
+ maintSpan.SetAttributes(attribute.Int("maintenance.copied.count", copied))
}
+ maintSpan.End()
}
+ _, commitSpan := entityTracer().Start(ctx, "repo.EntityRepository.Duplicate.commit")
if err := tx.Commit(); err != nil {
+ recordSpanError(commitSpan, err)
+ commitSpan.End()
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ commitSpan.End()
committed = true
r.publishMutationEvent(gid)
- return r.GetOne(ctx, newEntityID)
+ out, err := r.GetOne(ctx, newEntityID)
+ recordSpanError(span, err)
+ return out, err
}
// ============================================================================
@@ -1651,6 +2252,13 @@ type ContainerQuery struct {
// GetAllContainers returns all container entities (entity_type.is_location = true) with child entity counts.
func (r *EntityRepository) GetAllContainers(ctx context.Context, gid uuid.UUID, filter ContainerQuery) ([]EntityOutCount, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetAllContainers",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Bool("filter.children", filter.FilterChildren),
+ ))
+ defer span.End()
+
query := `--sql
SELECT
e.id,
@@ -1690,6 +2298,7 @@ func (r *EntityRepository) GetAllContainers(ctx context.Context, gid uuid.UUID,
rows, err := r.db.Sql().QueryContext(ctx, query, gid)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
defer func() { _ = rows.Close() }()
@@ -1702,6 +2311,7 @@ func (r *EntityRepository) GetAllContainers(ctx context.Context, gid uuid.UUID,
err := rows.Scan(&ct.ID, &ct.Name, &ct.Description, &ct.CreatedAt, &ct.UpdatedAt, &maybeCount)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
@@ -1712,12 +2322,24 @@ func (r *EntityRepository) GetAllContainers(ctx context.Context, gid uuid.UUID,
list = append(list, ct)
}
- return list, err
+ if err := rows.Err(); err != nil {
+ recordSpanError(span, err)
+ return list, err
+ }
+ span.SetAttributes(attribute.Int("containers.count", len(list)))
+ return list, nil
}
// GetContainerByGroup returns a single container entity by ID, verified to belong to a specific group.
func (r *EntityRepository) GetContainerByGroup(ctx context.Context, gid, id uuid.UUID) (EntityOut, error) {
- return mapEntityOutErr(r.db.Entity.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.GetContainerByGroup",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ ))
+ defer span.End()
+
+ out, err := mapEntityOutErr(r.db.Entity.Query().
Where(
entity.ID(id),
entity.HasGroupWith(group.ID(gid)),
@@ -1729,22 +2351,46 @@ func (r *EntityRepository) GetContainerByGroup(ctx context.Context, gid, id uuid
}).
WithEntityType().
Only(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("entity.children.count", len(out.Children)))
+ return out, nil
}
// CreateContainer creates a container entity (with a location-type entity_type).
func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, data EntityCreate) (EntityOut, error) {
- // Validate: if a parent is specified, it must also be a location-type entity
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.CreateContainer",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.name", data.Name),
+ attribute.Bool("entity.parent_id.set", data.ParentID != uuid.Nil),
+ attribute.Bool("entity.entity_type_id.set", data.EntityTypeID != uuid.Nil),
+ ))
+ defer span.End()
+
if data.ParentID != uuid.Nil {
+ validateCtx, validateSpan := entityTracer().Start(ctx, "repo.EntityRepository.CreateContainer.validateParent")
parentEntity, err := r.db.Entity.Query().
Where(entity.ID(data.ParentID)).
WithEntityType().
- Only(ctx)
+ Only(validateCtx)
if err != nil {
- return EntityOut{}, fmt.Errorf("parent entity not found: %w", err)
+ wrapped := fmt.Errorf("parent entity not found: %w", err)
+ recordSpanError(validateSpan, wrapped)
+ validateSpan.End()
+ recordSpanError(span, wrapped)
+ return EntityOut{}, wrapped
}
if parentEntity.Edges.EntityType == nil || !parentEntity.Edges.EntityType.IsLocation {
- return EntityOut{}, fmt.Errorf("locations can only have other locations as parents, not items")
+ wrapped := fmt.Errorf("locations can only have other locations as parents, not items")
+ recordSpanError(validateSpan, wrapped)
+ validateSpan.End()
+ recordSpanError(span, wrapped)
+ return EntityOut{}, wrapped
}
+ validateSpan.End()
}
q := r.db.Entity.Create().
@@ -1762,6 +2408,7 @@ func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, d
// Auto-resolve default "Location" entity type for the group
etID, err := r.resolveDefaultEntityType(ctx, gid, true)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
q.SetEntityTypeID(etID)
@@ -1769,9 +2416,11 @@ func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, d
result, err := q.Save(ctx)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
+ span.SetAttributes(attribute.String("entity.id", result.ID.String()))
result.Edges.Group = &ent.Group{ID: gid}
r.publishMutationEvent(gid)
return mapEntityOut(result), nil
@@ -1779,18 +2428,36 @@ func (r *EntityRepository) CreateContainer(ctx context.Context, gid uuid.UUID, d
// UpdateContainer updates a container entity.
func (r *EntityRepository) UpdateContainer(ctx context.Context, gid, id uuid.UUID, data EntityUpdate) (EntityOut, error) {
- // Validate: if a parent is specified, it must also be a location-type entity
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.UpdateContainer",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ attribute.String("entity.name", data.Name),
+ attribute.Bool("entity.parent_id.set", data.ParentID != uuid.Nil),
+ ))
+ defer span.End()
+
if data.ParentID != uuid.Nil {
+ validateCtx, validateSpan := entityTracer().Start(ctx, "repo.EntityRepository.UpdateContainer.validateParent")
parentEntity, err := r.db.Entity.Query().
Where(entity.ID(data.ParentID)).
WithEntityType().
- Only(ctx)
+ Only(validateCtx)
if err != nil {
- return EntityOut{}, fmt.Errorf("parent entity not found: %w", err)
+ wrapped := fmt.Errorf("parent entity not found: %w", err)
+ recordSpanError(validateSpan, wrapped)
+ validateSpan.End()
+ recordSpanError(span, wrapped)
+ return EntityOut{}, wrapped
}
if parentEntity.Edges.EntityType == nil || !parentEntity.Edges.EntityType.IsLocation {
- return EntityOut{}, fmt.Errorf("locations can only have other locations as parents, not items")
+ wrapped := fmt.Errorf("locations can only have other locations as parents, not items")
+ recordSpanError(validateSpan, wrapped)
+ validateSpan.End()
+ recordSpanError(span, wrapped)
+ return EntityOut{}, wrapped
}
+ validateSpan.End()
}
q := r.db.Entity.Update().
@@ -1809,17 +2476,28 @@ func (r *EntityRepository) UpdateContainer(ctx context.Context, gid, id uuid.UUI
_, err := q.Save(ctx)
if err != nil {
+ recordSpanError(span, err)
return EntityOut{}, err
}
r.publishMutationEvent(gid)
- return r.GetOne(ctx, id)
+ out, err := r.GetOne(ctx, id)
+ recordSpanError(span, err)
+ return out, err
}
// DeleteContainerByGroup deletes a container entity by group.
func (r *EntityRepository) DeleteContainerByGroup(ctx context.Context, gid, id uuid.UUID) error {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.DeleteContainerByGroup",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", id.String()),
+ ))
+ defer span.End()
+
_, err := r.db.Entity.Delete().Where(entity.ID(id), entity.HasGroupWith(group.ID(gid))).Exec(ctx)
if err != nil {
+ recordSpanError(span, err)
return err
}
r.publishMutationEvent(gid)
@@ -1863,6 +2541,13 @@ type EntityPath struct {
}
func (r *EntityRepository) PathForEntity(ctx context.Context, gid, entityID uuid.UUID) ([]EntityPath, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.PathForEntity",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.String("entity.id", entityID.String()),
+ ))
+ defer span.End()
+
query := `WITH RECURSIVE entity_path AS (
SELECT id, name, entity_children
FROM entities
@@ -1879,8 +2564,12 @@ func (r *EntityRepository) PathForEntity(ctx context.Context, gid, entityID uuid
SELECT id, name
FROM entity_path`
- rows, err := r.db.Sql().QueryContext(ctx, query, entityID, gid)
+ queryCtx, querySpan := entityTracer().Start(ctx, "repo.EntityRepository.PathForEntity.query")
+ rows, err := r.db.Sql().QueryContext(queryCtx, query, entityID, gid)
if err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
defer func() { _ = rows.Close() }()
@@ -1891,22 +2580,38 @@ func (r *EntityRepository) PathForEntity(ctx context.Context, gid, entityID uuid
var entry EntityPath
entry.Type = EntityPathTypeLocation
if err := rows.Scan(&entry.ID, &entry.Name); err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
path = append(path, entry)
}
if err := rows.Err(); err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
+ querySpan.SetAttributes(attribute.Int("path.depth", len(path)))
+ querySpan.End()
// Reverse the order so that the root is first
mutable.Reverse(path)
+ span.SetAttributes(attribute.Int("path.depth", len(path)))
return path, nil
}
func (r *EntityRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQuery) ([]TreeItem, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.EntityRepository.Tree",
+ trace.WithAttributes(
+ attribute.String("group.id", gid.String()),
+ attribute.Bool("query.with_items", tq.WithItems),
+ ))
+ defer span.End()
+
query := `
WITH recursive entity_tree(id, NAME, parent_id, level, node_type) AS
(
@@ -1991,8 +2696,12 @@ func (r *EntityRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQuery
query = strings.ReplaceAll(query, "{{ WITH_ITEMS_FROM }}", "")
}
- rows, err := r.db.Sql().QueryContext(ctx, query, gid)
+ queryCtx, querySpan := entityTracer().Start(ctx, "repo.EntityRepository.Tree.query")
+ rows, err := r.db.Sql().QueryContext(queryCtx, query, gid)
if err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
defer func() { _ = rows.Close() }()
@@ -2001,16 +2710,34 @@ func (r *EntityRepository) Tree(ctx context.Context, gid uuid.UUID, tq TreeQuery
for rows.Next() {
var item FlatTreeItem
if err := rows.Scan(&item.ID, &item.Name, &item.Level, &item.ParentID, &item.Type); err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
flatItems = append(flatItems, item)
}
if err := rows.Err(); err != nil {
+ recordSpanError(querySpan, err)
+ querySpan.End()
+ recordSpanError(span, err)
return nil, err
}
+ querySpan.SetAttributes(attribute.Int("flat_items.count", len(flatItems)))
+ querySpan.End()
- return ConvertEntitiesToTree(flatItems), nil
+ _, buildSpan := entityTracer().Start(ctx, "repo.EntityRepository.Tree.build",
+ trace.WithAttributes(attribute.Int("flat_items.count", len(flatItems))))
+ tree := ConvertEntitiesToTree(flatItems)
+ buildSpan.SetAttributes(attribute.Int("tree.roots.count", len(tree)))
+ buildSpan.End()
+
+ span.SetAttributes(
+ attribute.Int("flat_items.count", len(flatItems)),
+ attribute.Int("tree.roots.count", len(tree)),
+ )
+ return tree, nil
}
func ConvertEntitiesToTree(items []FlatTreeItem) []TreeItem {
diff --git a/backend/internal/data/repo/repo_item_attachments_test.go b/backend/internal/data/repo/repo_item_attachments_test.go
index c3f238b9..dc1e8099 100644
--- a/backend/internal/data/repo/repo_item_attachments_test.go
+++ b/backend/internal/data/repo/repo_item_attachments_test.go
@@ -358,10 +358,10 @@ func TestAttachmentRepo_MigrateLegacyFlatPaths(t *testing.T) {
for _, hash := range []string{"hash1.png", "hash2.png"} {
want := filepath.Join(root, ".data", "eb6bf410-a1a8-478d-a803-ca3948368a0c", "documents", hash)
_, err := os.Stat(want)
- assert.NoError(t, err, "expected migrated file at %s", want)
+ require.NoError(t, err, "expected migrated file at %s", want)
}
_, err := os.Stat(other)
- assert.NoError(t, err, "unrelated files at the bucket root should be left in place")
+ require.NoError(t, err, "unrelated files at the bucket root should be left in place")
// Idempotent: running again should be a no-op and not error.
require.NoError(t, r.MigrateLegacyFlatPaths())
diff --git a/backend/internal/data/repo/repo_tags_test.go b/backend/internal/data/repo/repo_tags_test.go
index 6eb91574..659d0ffc 100644
--- a/backend/internal/data/repo/repo_tags_test.go
+++ b/backend/internal/data/repo/repo_tags_test.go
@@ -141,7 +141,7 @@ func TestTagRepository_ParentChild(t *testing.T) {
// Fetch parent again, should have no children
foundParent, err = tRepos.Tags.GetOne(context.Background(), tGroup.ID, parentTag.ID)
require.NoError(t, err)
- assert.Len(t, foundParent.Children, 0)
+ assert.Empty(t, foundParent.Children)
}
func TestTagRepository_MaxDepth(t *testing.T) {
diff --git a/backend/internal/data/repo/repo_tokens.go b/backend/internal/data/repo/repo_tokens.go
index 5d3bba92..b407f034 100644
--- a/backend/internal/data/repo/repo_tokens.go
+++ b/backend/internal/data/repo/repo_tokens.go
@@ -11,6 +11,8 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/authtokens"
"github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
"github.com/sysadminsmedia/homebox/backend/pkgs/set"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
)
type TokenRepository struct {
@@ -36,6 +38,10 @@ func (u UserAuthToken) IsExpired() bool {
// GetUserFromToken get's a user from a token
func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (UserOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.GetUserFromToken",
+ trace.WithAttributes(attribute.Int("token.hash.length", len(token))))
+ defer span.End()
+
user, err := r.db.AuthTokens.Query().
Where(authtokens.Token(token)).
Where(authtokens.ExpiresAtGTE(time.Now())).
@@ -44,13 +50,27 @@ func (r *TokenRepository) GetUserFromToken(ctx context.Context, token []byte) (U
WithGroups().
Only(ctx)
if err != nil {
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.Bool("token.lookup.not_found", ent.IsNotFound(err)),
+ )
+ if !ent.IsNotFound(err) {
+ recordSpanError(span, err)
+ }
return UserOut{}, err
}
- return mapUserOut(user), nil
+ out := mapUserOut(user)
+ span.SetAttributes(attribute.Bool("user.found", true))
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, nil
}
func (r *TokenRepository) GetRoles(ctx context.Context, token string) (*set.Set[string], error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.GetRoles",
+ trace.WithAttributes(attribute.Int("token.length", len(token))))
+ defer span.End()
+
tokenHash := hasher.HashToken(token)
roles, err := r.db.AuthRoles.
@@ -60,6 +80,7 @@ func (r *TokenRepository) GetRoles(ctx context.Context, token string) (*set.Set[
)).
All(ctx)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
@@ -67,28 +88,50 @@ func (r *TokenRepository) GetRoles(ctx context.Context, token string) (*set.Set[
return role.Role.String()
})
+ span.SetAttributes(attribute.Int("roles.count", len(roleStrings)))
return new(set.New(roleStrings...)), nil
}
// CreateToken Creates a token for a user
func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthTokenCreate, roles ...authroles.Role) (UserAuthToken, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.CreateToken",
+ trace.WithAttributes(
+ attribute.String("user.id", createToken.UserID.String()),
+ attribute.String("token.expires_at", createToken.ExpiresAt.Format(time.RFC3339)),
+ attribute.Int("token.roles.count", len(roles)),
+ ))
+ defer span.End()
+
+ tokenCtx, tokenSpan := entityTracer().Start(ctx, "repo.TokenRepository.CreateToken.token")
dbToken, err := r.db.AuthTokens.Create().
SetToken(createToken.TokenHash).
SetUserID(createToken.UserID).
SetExpiresAt(createToken.ExpiresAt).
- Save(ctx)
+ Save(tokenCtx)
if err != nil {
+ recordSpanError(tokenSpan, err)
+ tokenSpan.End()
+ recordSpanError(span, err)
return UserAuthToken{}, err
}
-
- for _, role := range roles {
- _, err := r.db.AuthRoles.Create().
- SetRole(role).
- SetToken(dbToken).
- Save(ctx)
- if err != nil {
- return UserAuthToken{}, err
+ tokenSpan.End()
+
+ if len(roles) > 0 {
+ rolesCtx, rolesSpan := entityTracer().Start(ctx, "repo.TokenRepository.CreateToken.roles",
+ trace.WithAttributes(attribute.Int("roles.count", len(roles))))
+ for _, role := range roles {
+ _, err := r.db.AuthRoles.Create().
+ SetRole(role).
+ SetToken(dbToken).
+ Save(rolesCtx)
+ if err != nil {
+ recordSpanError(rolesSpan, err)
+ rolesSpan.End()
+ recordSpanError(span, err)
+ return UserAuthToken{}, err
+ }
}
+ rolesSpan.End()
}
return UserAuthToken{
@@ -103,21 +146,43 @@ func (r *TokenRepository) CreateToken(ctx context.Context, createToken UserAuthT
// DeleteToken remove a single token from the database - equivalent to revoke or logout
func (r *TokenRepository) DeleteToken(ctx context.Context, token []byte) error {
- _, err := r.db.AuthTokens.Delete().Where(authtokens.Token(token)).Exec(ctx)
- return err
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteToken",
+ trace.WithAttributes(attribute.Int("token.hash.length", len(token))))
+ defer span.End()
+
+ deleted, err := r.db.AuthTokens.Delete().Where(authtokens.Token(token)).Exec(ctx)
+ if err != nil {
+ recordSpanError(span, err)
+ return err
+ }
+ span.SetAttributes(attribute.Int("tokens.deleted.count", deleted))
+ return nil
}
// PurgeExpiredTokens removes all expired tokens from the database
func (r *TokenRepository) PurgeExpiredTokens(ctx context.Context) (int, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.PurgeExpiredTokens")
+ defer span.End()
+
tokensDeleted, err := r.db.AuthTokens.Delete().Where(authtokens.ExpiresAtLTE(time.Now())).Exec(ctx)
if err != nil {
+ recordSpanError(span, err)
return 0, err
}
+ span.SetAttributes(attribute.Int("tokens.deleted.count", tokensDeleted))
return tokensDeleted, nil
}
func (r *TokenRepository) DeleteAll(ctx context.Context) (int, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.TokenRepository.DeleteAll")
+ defer span.End()
+
amount, err := r.db.AuthTokens.Delete().Exec(ctx)
- return amount, err
+ if err != nil {
+ recordSpanError(span, err)
+ return 0, err
+ }
+ span.SetAttributes(attribute.Int("tokens.deleted.count", amount))
+ return amount, nil
}
diff --git a/backend/internal/data/repo/repo_users.go b/backend/internal/data/repo/repo_users.go
index c3a574c3..f6968d12 100644
--- a/backend/internal/data/repo/repo_users.go
+++ b/backend/internal/data/repo/repo_users.go
@@ -8,6 +8,8 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/ent"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/group"
"github.com/sysadminsmedia/homebox/backend/internal/data/ent/user"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/trace"
)
type UserRepository struct {
@@ -85,33 +87,110 @@ func mapUserSummary(user *ent.User) UserSummary {
}
}
+func userSpanAttrs(out UserOut) []attribute.KeyValue {
+ return []attribute.KeyValue{
+ attribute.String("user.id", out.ID.String()),
+ attribute.String("user.default_group_id", out.DefaultGroupID.String()),
+ attribute.Int("user.groups.count", len(out.GroupIDs)),
+ attribute.Bool("user.is_superuser", out.IsSuperuser),
+ attribute.Bool("user.is_owner", out.IsOwner),
+ attribute.Bool("user.has_password_hash", out.PasswordHash != ""),
+ attribute.Bool("user.has_oidc", out.OidcIssuer != nil && out.OidcSubject != nil),
+ }
+}
+
func (r *UserRepository) GetOneID(ctx context.Context, id uuid.UUID) (UserOut, error) {
- return mapUserOutErr(r.db.User.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetOneID",
+ trace.WithAttributes(attribute.String("user.id", id.String())))
+ defer span.End()
+
+ out, err := mapUserOutErr(r.db.User.Query().
Where(user.ID(id)).
WithGroups().
Only(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, nil
}
func (r *UserRepository) GetOneEmail(ctx context.Context, email string) (UserOut, error) {
- return mapUserOutErr(r.db.User.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetOneEmail",
+ trace.WithAttributes(attribute.Int("user.email.length", len(email))))
+ defer span.End()
+
+ out, err := mapUserOutErr(r.db.User.Query().
Where(user.EmailEqualFold(email)).
WithGroups().
Only(ctx),
)
+ if err != nil {
+ // "not found" is expected on bad logins; record on the span but don't mark
+ // it as an error status so dashboards aren't flooded with red.
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.String("user.lookup.error", err.Error()),
+ attribute.Bool("user.lookup.not_found", ent.IsNotFound(err)),
+ )
+ if !ent.IsNotFound(err) {
+ recordSpanError(span, err)
+ }
+ return out, err
+ }
+ span.SetAttributes(attribute.Bool("user.found", true))
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, nil
}
func (r *UserRepository) GetOneEmailNoEdges(ctx context.Context, email string) (UserOut, error) {
- return mapUserOutErr(r.db.User.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetOneEmailNoEdges",
+ trace.WithAttributes(attribute.Int("user.email.length", len(email))))
+ defer span.End()
+
+ out, err := mapUserOutErr(r.db.User.Query().
Where(user.EmailEqualFold(email)).
Only(ctx),
)
+ if err != nil {
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.Bool("user.lookup.not_found", ent.IsNotFound(err)),
+ )
+ if !ent.IsNotFound(err) {
+ recordSpanError(span, err)
+ }
+ return out, err
+ }
+ span.SetAttributes(attribute.Bool("user.found", true))
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, nil
}
func (r *UserRepository) GetAll(ctx context.Context) ([]UserOut, error) {
- return mapUsersOutErr(r.db.User.Query().WithGroups().All(ctx))
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetAll")
+ defer span.End()
+
+ out, err := mapUsersOutErr(r.db.User.Query().WithGroups().All(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("users.count", len(out)))
+ return out, nil
}
func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.Create",
+ trace.WithAttributes(
+ attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
+ attribute.Bool("user.is_superuser", usr.IsSuperuser),
+ attribute.Bool("user.is_owner", usr.IsOwner),
+ attribute.Bool("user.has_password", usr.Password != nil),
+ ))
+ defer span.End()
+
role := user.RoleUser
if usr.IsOwner {
role = user.RoleOwner
@@ -133,13 +212,31 @@ func (r *UserRepository) Create(ctx context.Context, usr UserCreate) (UserOut, e
entUser, err := createQuery.Save(ctx)
if err != nil {
+ recordSpanError(span, err)
return UserOut{}, err
}
- return r.GetOneID(ctx, entUser.ID)
+ span.SetAttributes(attribute.String("user.id", entUser.ID.String()))
+
+ out, err := r.GetOneID(ctx, entUser.ID)
+ if err != nil {
+ recordSpanError(span, err)
+ }
+ return out, err
}
func (r *UserRepository) CreateWithOIDC(ctx context.Context, usr UserCreate, issuer, subject string) (UserOut, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.CreateWithOIDC",
+ trace.WithAttributes(
+ attribute.String("user.default_group_id", usr.DefaultGroupID.String()),
+ attribute.Bool("user.is_superuser", usr.IsSuperuser),
+ attribute.Bool("user.is_owner", usr.IsOwner),
+ attribute.Bool("user.has_password", usr.Password != nil),
+ attribute.String("oidc.issuer", issuer),
+ attribute.Int("oidc.subject.length", len(subject)),
+ ))
+ defer span.End()
+
role := user.RoleUser
if usr.IsOwner {
role = user.RoleOwner
@@ -162,74 +259,172 @@ func (r *UserRepository) CreateWithOIDC(ctx context.Context, usr UserCreate, iss
entUser, err := createQuery.Save(ctx)
if err != nil {
+ recordSpanError(span, err)
return UserOut{}, err
}
- return r.GetOneID(ctx, entUser.ID)
+ span.SetAttributes(attribute.String("user.id", entUser.ID.String()))
+
+ out, err := r.GetOneID(ctx, entUser.ID)
+ if err != nil {
+ recordSpanError(span, err)
+ }
+ return out, err
}
func (r *UserRepository) Update(ctx context.Context, id uuid.UUID, data UserUpdate) error {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.Update",
+ trace.WithAttributes(attribute.String("user.id", id.String())))
+ defer span.End()
+
q := r.db.User.Update().
Where(user.ID(id)).
SetName(data.Name).
SetEmail(data.Email)
_, err := q.Save(ctx)
+ recordSpanError(span, err)
return err
}
func (r *UserRepository) UpdateDefaultGroup(ctx context.Context, id uuid.UUID, groupID uuid.UUID) error {
- return r.db.User.UpdateOneID(id).SetDefaultGroupID(groupID).Exec(ctx)
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.UpdateDefaultGroup",
+ trace.WithAttributes(
+ attribute.String("user.id", id.String()),
+ attribute.String("group.id", groupID.String()),
+ ))
+ defer span.End()
+
+ err := r.db.User.UpdateOneID(id).SetDefaultGroupID(groupID).Exec(ctx)
+ recordSpanError(span, err)
+ return err
}
func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.Delete",
+ trace.WithAttributes(attribute.String("user.id", id.String())))
+ defer span.End()
+
_, err := r.db.User.Delete().Where(user.ID(id)).Exec(ctx)
+ recordSpanError(span, err)
return err
}
func (r *UserRepository) DeleteAll(ctx context.Context) error {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.DeleteAll")
+ defer span.End()
+
_, err := r.db.User.Delete().Exec(ctx)
+ recordSpanError(span, err)
return err
}
func (r *UserRepository) GetSuperusers(ctx context.Context) ([]*ent.User, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetSuperusers")
+ defer span.End()
+
users, err := r.db.User.Query().Where(user.IsSuperuser(true)).All(ctx)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
-
+ span.SetAttributes(attribute.Int("users.count", len(users)))
return users, nil
}
func (r *UserRepository) ChangePassword(ctx context.Context, uid uuid.UUID, pw string) error {
- return r.db.User.UpdateOneID(uid).SetPassword(pw).Exec(ctx)
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.ChangePassword",
+ trace.WithAttributes(
+ attribute.String("user.id", uid.String()),
+ attribute.Int("password.hash.length", len(pw)),
+ ))
+ defer span.End()
+
+ err := r.db.User.UpdateOneID(uid).SetPassword(pw).Exec(ctx)
+ recordSpanError(span, err)
+ return err
}
func (r *UserRepository) SetSettings(ctx context.Context, uid uuid.UUID, settings map[string]interface{}) error {
- return r.db.User.UpdateOneID(uid).SetSettings(settings).Exec(ctx)
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.SetSettings",
+ trace.WithAttributes(
+ attribute.String("user.id", uid.String()),
+ attribute.Int("settings.keys.count", len(settings)),
+ ))
+ defer span.End()
+
+ err := r.db.User.UpdateOneID(uid).SetSettings(settings).Exec(ctx)
+ recordSpanError(span, err)
+ return err
}
func (r *UserRepository) GetSettings(ctx context.Context, uid uuid.UUID) (map[string]interface{}, error) {
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetSettings",
+ trace.WithAttributes(attribute.String("user.id", uid.String())))
+ defer span.End()
+
usr, err := r.db.User.Get(ctx, uid)
if err != nil {
+ recordSpanError(span, err)
return nil, err
}
+ span.SetAttributes(attribute.Int("settings.keys.count", len(usr.Settings)))
return usr.Settings, nil
}
func (r *UserRepository) SetOIDCIdentity(ctx context.Context, uid uuid.UUID, issuer, subject string) error {
- return r.db.User.UpdateOneID(uid).SetOidcIssuer(issuer).SetOidcSubject(subject).Exec(ctx)
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.SetOIDCIdentity",
+ trace.WithAttributes(
+ attribute.String("user.id", uid.String()),
+ attribute.String("oidc.issuer", issuer),
+ attribute.Int("oidc.subject.length", len(subject)),
+ ))
+ defer span.End()
+
+ err := r.db.User.UpdateOneID(uid).SetOidcIssuer(issuer).SetOidcSubject(subject).Exec(ctx)
+ recordSpanError(span, err)
+ return err
}
func (r *UserRepository) GetOneOIDC(ctx context.Context, issuer, subject string) (UserOut, error) {
- return mapUserOutErr(r.db.User.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetOneOIDC",
+ trace.WithAttributes(
+ attribute.String("oidc.issuer", issuer),
+ attribute.Int("oidc.subject.length", len(subject)),
+ ))
+ defer span.End()
+
+ out, err := mapUserOutErr(r.db.User.Query().
Where(user.OidcIssuerEQ(issuer), user.OidcSubjectEQ(subject)).
WithGroups().
Only(ctx))
+ if err != nil {
+ span.SetAttributes(
+ attribute.Bool("user.found", false),
+ attribute.Bool("user.lookup.not_found", ent.IsNotFound(err)),
+ )
+ if !ent.IsNotFound(err) {
+ recordSpanError(span, err)
+ }
+ return out, err
+ }
+ span.SetAttributes(attribute.Bool("user.found", true))
+ span.SetAttributes(userSpanAttrs(out)...)
+ return out, nil
}
func (r *UserRepository) GetUsersByGroupID(ctx context.Context, gid uuid.UUID) ([]UserSummary, error) {
- return mapUsersSummaryErr(r.db.User.Query().
+ ctx, span := entityTracer().Start(ctx, "repo.UserRepository.GetUsersByGroupID",
+ trace.WithAttributes(attribute.String("group.id", gid.String())))
+ defer span.End()
+
+ out, err := mapUsersSummaryErr(r.db.User.Query().
Where(user.HasGroupsWith(group.ID(gid))).
All(ctx))
+ if err != nil {
+ recordSpanError(span, err)
+ return out, err
+ }
+ span.SetAttributes(attribute.Int("users.count", len(out)))
+ return out, nil
}
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 4750c8d1..53b92e49 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -101,8 +101,8 @@ type OIDCConf struct {
}
type BarcodeAPIConf struct {
- TokenBarcodespider string `yaml:"token_barcodespider"`
- OpenFoodFactsContact string `yaml:"openfoodfacts_contact"`
+ TokenBarcodespider string `yaml:"token_barcodespider"`
+ OpenFoodFactsContact string `yaml:"openfoodfacts_contact"`
}
type AuthConfig struct {
diff --git a/backend/pkgs/hasher/password.go b/backend/pkgs/hasher/password.go
index 7a10fb03..d2675c3b 100644
--- a/backend/pkgs/hasher/password.go
+++ b/backend/pkgs/hasher/password.go
@@ -1,13 +1,19 @@
package hasher
import (
+ "context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
+ "errors"
"fmt"
"os"
"strings"
+ "go.opentelemetry.io/otel"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/codes"
+ "go.opentelemetry.io/otel/trace"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/bcrypt"
)
@@ -45,6 +51,18 @@ func init() { // nolint: gochecknoinits
}
}
+func hasherTracer() trace.Tracer {
+ return otel.Tracer("hasher")
+}
+
+func recordSpanError(span trace.Span, err error) {
+ if err == nil {
+ return
+ }
+ span.RecordError(err)
+ span.SetStatus(codes.Error, err.Error())
+}
+
func GenerateRandomBytes(n uint32) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
@@ -54,99 +72,327 @@ func GenerateRandomBytes(n uint32) ([]byte, error) {
return b, nil
}
+// HashPassword hashes the password with argon2id and returns the encoded hash. It is
+// equivalent to HashPasswordCtx with a Background context and exists for callers that
+// have no context to thread through.
func HashPassword(password string) (string, error) {
+ return HashPasswordCtx(context.Background(), password)
+}
+
+// HashPasswordCtx hashes the password with argon2id, emitting a span describing the work.
+// Splitting the salt and KDF into sub-spans makes it possible to correlate slow logins
+// with the argon2 derivation specifically.
+func HashPasswordCtx(ctx context.Context, password string) (string, error) {
+ ctx, span := hasherTracer().Start(ctx, "hasher.HashPassword",
+ trace.WithAttributes(
+ attribute.Bool("password.protection.enabled", enabled),
+ attribute.Int("password.length", len(password)),
+ ))
+ defer span.End()
+
if !enabled {
+ span.SetAttributes(attribute.String("password.algorithm", "plaintext-disabled"))
return password, nil
}
+ span.SetAttributes(
+ attribute.String("password.algorithm", "argon2id"),
+ attribute.Int64("argon2.memory_kib", int64(p.memory)),
+ attribute.Int64("argon2.iterations", int64(p.iterations)),
+ attribute.Int("argon2.parallelism", int(p.parallelism)),
+ attribute.Int64("argon2.salt_length", int64(p.saltLength)),
+ attribute.Int64("argon2.key_length", int64(p.keyLength)),
+ )
+
+ saltCtx, saltSpan := hasherTracer().Start(ctx, "hasher.HashPassword.salt")
salt, err := GenerateRandomBytes(p.saltLength)
if err != nil {
+ recordSpanError(saltSpan, err)
+ saltSpan.End()
+ recordSpanError(span, err)
return "", err
}
+ saltSpan.End()
+ _ = saltCtx
+
+ _, kdfSpan := hasherTracer().Start(ctx, "hasher.HashPassword.argon2.derive")
hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
+ kdfSpan.End()
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
encodedHash := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, 64*1024, 3, 2, b64Salt, b64Hash)
- return encodedHash, err
+ span.SetAttributes(attribute.Int("password.encoded_hash.length", len(encodedHash)))
+ return encodedHash, nil
}
-// CheckPasswordHash checks if the provided password matches the hash.
-// Additionally, it returns a boolean indicating whether the password should be rehashed.
+// CheckPasswordHash checks if the provided password matches the hash. It is equivalent
+// to CheckPasswordHashCtx with a Background context.
func CheckPasswordHash(password, hash string) (bool, bool) {
+ return CheckPasswordHashCtx(context.Background(), password, hash)
+}
+
+// CheckPasswordHashCtx checks the password and emits spans for each branch (argon2id
+// success, argon2id mismatch, bcrypt fallback, both-failed). Errors from the argon2
+// decode path are recorded on the span instead of being silently swallowed — that
+// silent swallowing was a major obstacle to debugging intermittent password rejections
+// from valid hashes.
+//
+// Returns (match, needsRehash). needsRehash is true when the stored hash was a
+// legacy bcrypt hash and the password matched; the caller is expected to rehash with
+// argon2id and persist.
+func CheckPasswordHashCtx(ctx context.Context, password, hash string) (bool, bool) {
+ ctx, span := hasherTracer().Start(ctx, "hasher.CheckPasswordHash",
+ trace.WithAttributes(
+ attribute.Bool("password.protection.enabled", enabled),
+ attribute.Int("password.length", len(password)),
+ attribute.Int("password.hash.length", len(hash)),
+ attribute.String("password.hash.prefix", hashPrefix(hash)),
+ ))
+ defer span.End()
+
if !enabled {
- return password == hash, false
- }
-
- // Compare Argon2id hash first
- match, err := comparePasswordAndHash(password, hash)
- if err != nil || !match {
- // If argon2id hash fails or doesn't match, try bcrypt
- err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
- if err == nil {
- // If bcrypt hash matches, return true and indicate rehashing
- return true, true
- } else {
- // If both fail, return false and indicate no rehashing
- return false, false
+ matched := password == hash
+ span.SetAttributes(
+ attribute.String("password.algorithm", "plaintext-disabled"),
+ attribute.Bool("password.match", matched),
+ attribute.String("password.outcome", outcomeForMatch(matched, "plaintext-disabled")),
+ )
+ return matched, false
+ }
+
+ match, decodeErr, compareErr := comparePasswordAndHash(ctx, password, hash)
+ span.SetAttributes(
+ attribute.Bool("password.argon2.decode_ok", decodeErr == nil),
+ attribute.Bool("password.argon2.compare_ok", compareErr == nil),
+ attribute.Bool("password.argon2.match", match),
+ )
+
+ switch {
+ case decodeErr != nil:
+ span.SetAttributes(attribute.String("password.argon2.decode_error", decodeErr.Error()))
+ recordSpanError(span, fmt.Errorf("argon2 decode failed: %w", decodeErr))
+ case compareErr != nil:
+ span.SetAttributes(attribute.String("password.argon2.compare_error", compareErr.Error()))
+ recordSpanError(span, fmt.Errorf("argon2 compare failed: %w", compareErr))
+ }
+
+ if decodeErr == nil && compareErr == nil && match {
+ span.SetAttributes(
+ attribute.String("password.algorithm", "argon2id"),
+ attribute.Bool("password.match", true),
+ attribute.Bool("password.rehash_needed", false),
+ attribute.String("password.outcome", "argon2id_match"),
+ )
+ return true, false
+ }
+
+ // Argon2 failed or didn't match — try bcrypt as a legacy fallback.
+ _, bcryptSpan := hasherTracer().Start(ctx, "hasher.CheckPasswordHash.bcrypt")
+ bcryptErr := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
+ bcryptSpan.SetAttributes(
+ attribute.Bool("password.bcrypt.match", bcryptErr == nil),
+ attribute.String("password.bcrypt.error", errString(bcryptErr)),
+ attribute.String("password.bcrypt.error_kind", bcryptErrorKind(bcryptErr)),
+ )
+ if bcryptErr != nil {
+ // Not a logical "error" if the hash simply isn't a bcrypt hash — that's the expected
+ // case when the stored hash is argon2id and the password didn't match. Don't mark the
+ // span as failed for that.
+ if !errors.Is(bcryptErr, bcrypt.ErrMismatchedHashAndPassword) && !errors.Is(bcryptErr, bcrypt.ErrHashTooShort) {
+ recordSpanError(bcryptSpan, bcryptErr)
}
}
- return match, false
+ bcryptSpan.End()
+
+ if bcryptErr == nil {
+ span.SetAttributes(
+ attribute.String("password.algorithm", "bcrypt"),
+ attribute.Bool("password.match", true),
+ attribute.Bool("password.rehash_needed", true),
+ attribute.String("password.outcome", "bcrypt_match_needs_rehash"),
+ )
+ return true, true
+ }
+
+ var outcome string
+ switch {
+ case decodeErr != nil:
+ outcome = "rejected_argon2_decode_failed"
+ case compareErr != nil:
+ outcome = "rejected_argon2_compare_failed"
+ default:
+ outcome = "rejected_argon2_mismatch_and_not_bcrypt"
+ }
+ span.SetAttributes(
+ attribute.Bool("password.match", false),
+ attribute.Bool("password.rehash_needed", false),
+ attribute.String("password.outcome", outcome),
+ )
+ return false, false
}
-func comparePasswordAndHash(password, encodedHash string) (match bool, err error) {
- // Extract the parameters, salt and derived key from the encoded password
- // hash.
- p, salt, hash, err := decodeHash(encodedHash)
+// comparePasswordAndHash returns (match, decodeErr, compareErr). Splitting the
+// errors lets callers distinguish "the stored hash is malformed" (a real bug)
+// from "the password didn't match" (expected for wrong passwords).
+func comparePasswordAndHash(ctx context.Context, password, encodedHash string) (match bool, decodeErr error, compareErr error) {
+ ctx, span := hasherTracer().Start(ctx, "hasher.comparePasswordAndHash")
+ defer span.End()
+
+ decodeCtx, decodeSpan := hasherTracer().Start(ctx, "hasher.comparePasswordAndHash.decode")
+ storedParams, salt, hash, err := decodeHash(encodedHash)
if err != nil {
- return false, err
+ decodeSpan.SetAttributes(
+ attribute.String("decode.error", err.Error()),
+ attribute.String("decode.error_kind", classifyDecodeError(err)),
+ )
+ recordSpanError(decodeSpan, err)
+ decodeSpan.End()
+ span.SetAttributes(attribute.Bool("decode.ok", false))
+ return false, err, nil
}
+ decodeSpan.SetAttributes(
+ attribute.Bool("decode.ok", true),
+ attribute.Int64("decode.argon2.memory_kib", int64(storedParams.memory)),
+ attribute.Int64("decode.argon2.iterations", int64(storedParams.iterations)),
+ attribute.Int("decode.argon2.parallelism", int(storedParams.parallelism)),
+ attribute.Int64("decode.argon2.salt_length", int64(storedParams.saltLength)),
+ attribute.Int64("decode.argon2.key_length", int64(storedParams.keyLength)),
+ )
+ decodeSpan.End()
+ _ = decodeCtx
- // Derive the key from the other password using the same parameters.
- otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
+ span.SetAttributes(
+ attribute.Bool("decode.ok", true),
+ attribute.Bool("params.match_current",
+ storedParams.memory == p.memory &&
+ storedParams.iterations == p.iterations &&
+ storedParams.parallelism == p.parallelism &&
+ storedParams.saltLength == p.saltLength &&
+ storedParams.keyLength == p.keyLength),
+ )
- // Check that the contents of the hashed passwords are identical. Note
- // that we are using the subtle.ConstantTimeCompare() function for this
- // to help prevent timing attacks.
- if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
- return true, nil
- }
- return false, nil
+ _, deriveSpan := hasherTracer().Start(ctx, "hasher.comparePasswordAndHash.derive")
+ otherHash := argon2.IDKey([]byte(password), salt, storedParams.iterations, storedParams.memory, storedParams.parallelism, storedParams.keyLength)
+ deriveSpan.End()
+
+ _, cmpSpan := hasherTracer().Start(ctx, "hasher.comparePasswordAndHash.constantTimeCompare")
+ matched := subtle.ConstantTimeCompare(hash, otherHash) == 1
+ cmpSpan.SetAttributes(attribute.Bool("compare.match", matched))
+ cmpSpan.End()
+
+ span.SetAttributes(attribute.Bool("compare.match", matched))
+ return matched, nil, nil
}
-func decodeHash(encodedHash string) (p *params, salt, hash []byte, err error) {
+func decodeHash(encodedHash string) (out *params, salt, hash []byte, err error) {
vals := strings.Split(encodedHash, "$")
if len(vals) != 6 {
- return nil, nil, nil, fmt.Errorf("invalid hash format")
+ return nil, nil, nil, fmt.Errorf("invalid hash format: expected 6 segments, got %d", len(vals))
}
var version int
_, err = fmt.Sscanf(vals[2], "v=%d", &version)
if err != nil {
- return nil, nil, nil, err
+ return nil, nil, nil, fmt.Errorf("invalid version segment %q: %w", vals[2], err)
}
if version != argon2.Version {
- return nil, nil, nil, fmt.Errorf("unsupported argon2 version: %d", version)
+ return nil, nil, nil, fmt.Errorf("unsupported argon2 version: got %d, want %d", version, argon2.Version)
}
- p = &params{}
- _, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism)
+ out = &params{}
+ _, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &out.memory, &out.iterations, &out.parallelism)
if err != nil {
- return nil, nil, nil, err
+ return nil, nil, nil, fmt.Errorf("invalid params segment %q: %w", vals[3], err)
}
salt, err = base64.RawStdEncoding.Strict().DecodeString(vals[4])
if err != nil {
- return nil, nil, nil, err
+ return nil, nil, nil, fmt.Errorf("invalid salt: %w", err)
}
- p.saltLength = uint32(len(salt))
+ out.saltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.Strict().DecodeString(vals[5])
if err != nil {
- return nil, nil, nil, err
+ return nil, nil, nil, fmt.Errorf("invalid key: %w", err)
+ }
+ out.keyLength = uint32(len(hash))
+
+ return out, salt, hash, nil
+}
+
+// hashPrefix returns the algorithm prefix of an encoded hash if recognizable, without
+// leaking any of the actual key material. This is safe to attach to spans for diagnosis.
+func hashPrefix(hash string) string {
+ switch {
+ case strings.HasPrefix(hash, "$argon2id$"):
+ return "argon2id"
+ case strings.HasPrefix(hash, "$argon2i$"):
+ return "argon2i"
+ case strings.HasPrefix(hash, "$argon2d$"):
+ return "argon2d"
+ case strings.HasPrefix(hash, "$2a$"), strings.HasPrefix(hash, "$2b$"), strings.HasPrefix(hash, "$2y$"):
+ return "bcrypt"
+ case hash == "":
+ return "empty"
+ default:
+ return "unknown"
}
- p.keyLength = uint32(len(hash))
+}
- return p, salt, hash, nil
+func classifyDecodeError(err error) string {
+ if err == nil {
+ return ""
+ }
+ msg := err.Error()
+ switch {
+ case strings.Contains(msg, "expected 6 segments"):
+ return "format_segment_count"
+ case strings.Contains(msg, "invalid version"):
+ return "version_parse"
+ case strings.Contains(msg, "unsupported argon2 version"):
+ return "version_unsupported"
+ case strings.Contains(msg, "invalid params"):
+ return "params_parse"
+ case strings.Contains(msg, "invalid salt"):
+ return "salt_b64"
+ case strings.Contains(msg, "invalid key"):
+ return "key_b64"
+ default:
+ return "other"
+ }
+}
+
+func bcryptErrorKind(err error) string {
+ switch {
+ case err == nil:
+ return ""
+ case errors.Is(err, bcrypt.ErrMismatchedHashAndPassword):
+ return "mismatch"
+ case errors.Is(err, bcrypt.ErrHashTooShort):
+ return "hash_too_short"
+ default:
+ if _, ok := errors.AsType[bcrypt.HashVersionTooNewError](err); ok {
+ return "version_too_new"
+ }
+ if _, ok := errors.AsType[bcrypt.InvalidHashPrefixError](err); ok {
+ return "invalid_prefix"
+ }
+ return "other"
+ }
+}
+
+func errString(err error) string {
+ if err == nil {
+ return ""
+ }
+ return err.Error()
+}
+
+func outcomeForMatch(match bool, algorithm string) string {
+ if match {
+ return algorithm + "_match"
+ }
+ return algorithm + "_mismatch"
}
diff --git a/backend/pkgs/hasher/token.go b/backend/pkgs/hasher/token.go
index 8d98e106..d8e3d8d9 100644
--- a/backend/pkgs/hasher/token.go
+++ b/backend/pkgs/hasher/token.go
@@ -1,9 +1,12 @@
package hasher
import (
+ "context"
"crypto/rand"
"crypto/sha256"
"encoding/base32"
+
+ "go.opentelemetry.io/otel/attribute"
)
type Token struct {
@@ -11,19 +14,34 @@ type Token struct {
Hash []byte
}
+// GenerateToken generates a cryptographically random token. The non-context variant is
+// kept for callers that don't have a context handy; both go through GenerateTokenCtx.
func GenerateToken() Token {
+ return GenerateTokenCtx(context.Background())
+}
+
+func GenerateTokenCtx(ctx context.Context) Token {
+ _, span := hasherTracer().Start(ctx, "hasher.GenerateToken")
+ defer span.End()
+
randomBytes := make([]byte, 16)
_, _ = rand.Read(randomBytes)
plainText := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(randomBytes)
hash := HashToken(plainText)
+ span.SetAttributes(
+ attribute.Int("token.raw.length", len(plainText)),
+ attribute.Int("token.hash.length", len(hash)),
+ )
return Token{
Raw: plainText,
Hash: hash,
}
}
+// HashToken hashes a token. This is fast (single SHA-256) so we don't trace it by
+// default — adding a span on every middleware request would be more noise than signal.
func HashToken(plainTextToken string) []byte {
hash := sha256.Sum256([]byte(plainTextToken))
return hash[:]