otter-space-sdk/pkg/database/client.go
SoXX 2d9db01d72 feat(telemetry): Implement telemetry setup in database client
Add OpenTelemetry integration to the database client by creating a `setupTelemetry` function. Initialize a tracer and configure logging with the otellogrus hook. Call this function during the connection process to enable tracing and logging for database operations.
2024-08-11 22:17:00 +02:00

97 lines
2.1 KiB
Go

package database
import (
"context"
"embed"
"fmt"
otterError "git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/error"
"git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/models"
migrate "github.com/rubenv/sql-migrate"
log "github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/bridges/otellogrus"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/trace"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
const tracingName = "git.anthrove.art/Anthrove/otter-space-sdk/v2/pkg/database"
var (
//go:embed migrations/*.sql
embedMigrations embed.FS
client *gorm.DB
tracer trace.Tracer
logger *log.Logger
)
func Connect(_ context.Context, config models.DatabaseConfig) error {
var localSSL string
if config.SSL {
localSSL = "require"
} else {
localSSL = "disable"
}
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=%s TimeZone=%s", config.Endpoint, config.Username, config.Password, config.Database, config.Port, localSSL, config.Timezone)
sqlDB, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return err
}
err = migrateDatabase(sqlDB, config)
if err != nil {
return err
}
setupTelemetry()
client = sqlDB
return nil
}
func migrateDatabase(dbPool *gorm.DB, config models.DatabaseConfig) error {
dialect := "postgres"
migrations := &migrate.EmbedFileSystemMigrationSource{FileSystem: embedMigrations, Root: "migrations"}
db, err := dbPool.DB()
if err != nil {
return fmt.Errorf("postgres migration: %v", err)
}
n, err := migrate.Exec(db, dialect, migrations, migrate.Up)
if err != nil {
return fmt.Errorf("postgres migration: %v", err)
}
if config.Debug {
if n != 0 {
log.Infof("postgres migration: applied %d migrations!", n)
} else {
log.Info("postgres migration: nothing to migrate")
}
}
return nil
}
func setupTelemetry() {
tracer = otel.Tracer(tracingName)
hook := otellogrus.NewHook(tracingName)
logger.AddHook(hook)
}
func GetGorm(ctx context.Context) (*gorm.DB, error) {
if client == nil {
return nil, &otterError.Database{Reason: otterError.DatabaseIsNotConnected}
}
return client, nil
}