chore: Add comments and improve JSON annotations for better data structuring and clarity across the codebase

This commit is contained in:
SoXX 2024-08-13 10:54:21 +02:00
parent b4e8152cb4
commit cfc7e5362d
10 changed files with 31 additions and 92 deletions

View File

@ -8,7 +8,18 @@ import (
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
func HandleError(ctx context.Context, span trace.Span, logger *log.Entry, error error) error { // HandleError logs the provided error, records it in the given trace span,
// sets the span status to error, and returns the error.
//
// Parameters:
// - ctx: context.Context, the context in which the error occurred.
// - span: trace.Span, the trace span where the error will be recorded.
// - logger: *log.Entry, a log entry used to log the error message.
// - error: error, the error to be handled.
//
// Returns:
// - error: The same error that was passed in.
func HandleError(_ context.Context, span trace.Span, logger *log.Entry, error error) error {
logger.Error(error) logger.Error(error)
span.RecordError(error) span.RecordError(error)
span.SetStatus(codes.Error, error.Error()) span.SetStatus(codes.Error, error.Error())

View File

@ -1,11 +0,0 @@
package utils
func GetOrDefault(data map[string]any, key string, defaultVal any) any {
val, ok := data[key]
if !ok {
return defaultVal
}
return val
}

View File

@ -1,60 +0,0 @@
package utils
import (
"reflect"
"testing"
)
func TestGetOrDefault(t *testing.T) {
type args struct {
data map[string]any
key string
defaultVal any
}
tests := []struct {
name string
args args
want any
}{
{
name: "Test 1: Nil map",
args: args{
data: nil,
key: "key1",
defaultVal: "default",
},
want: "default",
},
{
name: "Test 2: Existing key",
args: args{
data: map[string]interface{}{
"key1": "value1",
"key2": "value2",
},
key: "key1",
defaultVal: "default",
},
want: "value1",
},
{
name: "Test 3: Non-existing key",
args: args{
data: map[string]interface{}{
"key1": "value1",
"key2": "value2",
},
key: "key3",
defaultVal: "default",
},
want: "default",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := GetOrDefault(tt.args.data, tt.args.key, tt.args.defaultVal); !reflect.DeepEqual(got, tt.want) {
t.Errorf("GetOrDefault() = %v, want %v", got, tt.want)
}
})
}
}

View File

@ -7,6 +7,7 @@ import (
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
// SetupTracing initializes a new trace span and logger for the given context and tracer.
func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (context.Context, trace.Span, *log.Entry) { func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (context.Context, trace.Span, *log.Entry) {
ctx, span := tracer.Start(ctx, tracerName) ctx, span := tracer.Start(ctx, tracerName)
localLogger := log.WithContext(ctx) localLogger := log.WithContext(ctx)
@ -14,6 +15,7 @@ func SetupTracing(ctx context.Context, tracer trace.Tracer, tracerName string) (
return ctx, span, localLogger return ctx, span, localLogger
} }
// HandleEvent logs the provided event name and adds it to the given trace span.
func HandleEvent(span trace.Span, logger *log.Entry, eventName string) { func HandleEvent(span trace.Span, logger *log.Entry, eventName string) {
logger.Debug(eventName) logger.Debug(eventName)
span.AddEvent(eventName) span.AddEvent(eventName)

View File

@ -28,9 +28,16 @@ var (
logger = log.New() logger = log.New()
) )
// Connect to the Database
func Connect(ctx context.Context, config models.DatabaseConfig) error { func Connect(ctx context.Context, config models.DatabaseConfig) error {
setupTelemetry()
// Setup open telemetry
tracer = otel.Tracer(tracingName)
hook := otellogrus.NewHook(tracingName)
logger.AddHook(hook)
// Debug enabled?
if config.Debug { if config.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
} }
@ -75,6 +82,7 @@ func Connect(ctx context.Context, config models.DatabaseConfig) error {
return nil return nil
} }
// migrateDatabase handels the migration of ann SQL files in the migrations subfolder
func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.DatabaseConfig) error { func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.DatabaseConfig) error {
ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "migrateDatabase") ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "migrateDatabase")
defer span.End() defer span.End()
@ -114,13 +122,7 @@ func migrateDatabase(ctx context.Context, dbPool *gorm.DB, config models.Databas
return nil return nil
} }
func setupTelemetry() { // GetGorm returns a ready to use gorm.DB client
tracer = otel.Tracer(tracingName)
hook := otellogrus.NewHook(tracingName)
logger.AddHook(hook)
}
func GetGorm(ctx context.Context) (*gorm.DB, error) { func GetGorm(ctx context.Context) (*gorm.DB, error) {
ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "GetGorm") ctx, span, localLogger := utils.SetupTracing(ctx, tracer, "GetGorm")
defer span.End() defer span.End()

View File

@ -3,9 +3,6 @@ package error
import "fmt" import "fmt"
const ( const (
UserIDIsEmpty = "postID cannot be empty"
UserIDToShort = "postID needs to be 25 characters long"
SourceListIsEmpty = "sourceList cannot be empty" SourceListIsEmpty = "sourceList cannot be empty"
SourceIDIsEmpty = "SourceID cannot be empty" SourceIDIsEmpty = "SourceID cannot be empty"
SourceIDToShort = "sourceID needs to be 25 characters long" SourceIDToShort = "sourceID needs to be 25 characters long"
@ -15,10 +12,8 @@ const (
UserSourceIDToShort = "userSourceID needs to be 25 characters long" UserSourceIDToShort = "userSourceID needs to be 25 characters long"
TagListIsEmpty = "tagList cannot be empty" TagListIsEmpty = "tagList cannot be empty"
TagNameIsEmpty = "tagName cannot be empty"
TagAliasListIsEmpty = "tagAliasList cannot be empty" TagAliasListIsEmpty = "tagAliasList cannot be empty"
TagAliasNameIsEmpty = "tagAliasName cannot be empty"
TagGroupListIsEmpty = "tagGroupList cannot be empty" TagGroupListIsEmpty = "tagGroupList cannot be empty"
TagGroupNameIsEmpty = "tagGroupName cannot be empty" TagGroupNameIsEmpty = "tagGroupName cannot be empty"

View File

@ -13,8 +13,8 @@ type ID interface {
type BaseModel[T ID] struct { type BaseModel[T ID] struct {
ID T `json:"id" gorm:"primaryKey"` ID T `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"-"` CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"-"` UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"` DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
} }

View File

@ -4,7 +4,7 @@ package models
type Post struct { type Post struct {
BaseModel[PostID] BaseModel[PostID]
Rating Rating `json:"rating" gorm:"type:enum('safe','questionable','explicit')"` Rating Rating `json:"rating" gorm:"type:enum('safe','questionable','explicit')"`
Tags []Tag `json:"-" gorm:"many2many:post_tags;"` Tags []Tag `json:"tags,omitempty" gorm:"many2many:post_tags;"`
Favorites []UserFavorite `json:"-" gorm:"foreignKey:PostID"` Favorites []UserFavorite `json:"-" gorm:"foreignKey:PostID"`
References []PostReference `json:"references" gorm:"foreignKey:PostID"` References []PostReference `json:"references" gorm:"foreignKey:PostID"`
} }

View File

@ -4,9 +4,9 @@ package models
type Tag struct { type Tag struct {
Name TagName `json:"name" gorm:"primaryKey"` Name TagName `json:"name" gorm:"primaryKey"`
Type TagType `json:"type" gorm:"column:tag_type"` Type TagType `json:"type" gorm:"column:tag_type"`
Aliases []TagAlias `json:"aliases" gorm:"foreignKey:TagID"` Aliases []TagAlias `json:"aliases,omitempty" gorm:"foreignKey:TagID"`
Groups []TagGroup `json:"groups" gorm:"foreignKey:TagID"` Groups []TagGroup `json:"groups,omitempty" gorm:"foreignKey:TagID"`
Posts []Post `json:"posts" gorm:"many2many:post_tags;"` Posts []Post `json:"posts,omitempty" gorm:"many2many:post_tags;"`
} }
func (Tag) TableName() string { func (Tag) TableName() string {

View File

@ -13,7 +13,7 @@ type UserSource struct {
AccountID string `json:"account_id"` AccountID string `json:"account_id"`
LastScrapeTime time.Time `json:"last_scrape_time"` LastScrapeTime time.Time `json:"last_scrape_time"`
AccountValidate bool `json:"account_validate"` AccountValidate bool `json:"account_validate"`
AccountValidationKey string `json:"-"` AccountValidationKey string `json:"account_validation_key"`
} }
func (UserSource) TableName() string { func (UserSource) TableName() string {