mirror of
https://github.com/SamyRai/tercul-backend.git
synced 2025-12-27 04:01:34 +00:00
This commit marks the completion of a major refactoring effort to stabilize the codebase, improve its structure, and prepare it for production. The key changes include: - **Domain Layer Consolidation:** The `Work` entity and its related types, along with all other domain entities and repository interfaces, have been consolidated into the main `internal/domain` package. This eliminates import cycles and provides a single, coherent source of truth for the domain model. - **Data Access Layer Refactoring:** The repository implementations in `internal/data/sql` have been updated to align with the new domain layer. The `BaseRepositoryImpl` has been corrected to use pointer receivers, and all concrete repositories now correctly embed it, ensuring consistent and correct behavior. - **Application Layer Stabilization:** All application services in `internal/app` have been updated to use the new domain types and repository interfaces. Dependency injection has been corrected throughout the application, ensuring that all services are initialized with the correct dependencies. - **GraphQL Adapter Fixes:** The GraphQL resolver implementation in `internal/adapters/graphql` has been updated to correctly handle the new domain types and service methods. The auto-generated GraphQL code has been regenerated to ensure it is in sync with the schema and runtime. - **Test Suite Overhaul:** All test suites have been fixed to correctly implement their respective interfaces and use the updated domain model. Mock repositories and test suites have been corrected to properly embed the `testify` base types, resolving numerous build and linter errors. - **Dependency Management:** The Go modules have been tidied, and the module cache has been cleaned to ensure a consistent and correct dependency graph. - **Code Quality and Verification:** The entire codebase now passes all builds, tests, and linter checks, ensuring a high level of quality and stability. This comprehensive effort has resulted in a more robust, maintainable, and production-ready application.
197 lines
5.8 KiB
Go
197 lines
5.8 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
"tercul/internal/adapters/graphql"
|
|
"tercul/internal/app"
|
|
"tercul/internal/app/analytics"
|
|
"tercul/internal/app/localization"
|
|
appsearch "tercul/internal/app/search"
|
|
dbsql "tercul/internal/data/sql"
|
|
"tercul/internal/jobs/linguistics"
|
|
"tercul/internal/observability"
|
|
"tercul/internal/platform/auth"
|
|
"tercul/internal/platform/config"
|
|
"tercul/internal/platform/db"
|
|
app_log "tercul/internal/platform/log"
|
|
"tercul/internal/platform/search"
|
|
"time"
|
|
|
|
"github.com/99designs/gqlgen/graphql/playground"
|
|
"github.com/pressly/goose/v3"
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
"github.com/weaviate/weaviate-go-client/v5/weaviate"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// runMigrations applies database migrations using goose.
|
|
func runMigrations(gormDB *gorm.DB, migrationPath string) error {
|
|
sqlDB, err := gormDB.DB()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if err := goose.SetDialect("postgres"); err != nil {
|
|
return err
|
|
}
|
|
|
|
app_log.Info(fmt.Sprintf("Applying database migrations from %s", migrationPath))
|
|
if err := goose.Up(sqlDB, migrationPath); err != nil {
|
|
return err
|
|
}
|
|
app_log.Info("Database migrations applied successfully")
|
|
return nil
|
|
}
|
|
|
|
// main is the entry point for the Tercul application.
|
|
func main() {
|
|
// Load configuration from environment variables
|
|
cfg, err := config.LoadConfig()
|
|
if err != nil {
|
|
log.Fatalf("cannot load config: %v", err)
|
|
}
|
|
|
|
// Initialize logger
|
|
app_log.Init("tercul-api", cfg.Environment)
|
|
obsLogger := observability.NewLogger("tercul-api", cfg.Environment)
|
|
|
|
// Initialize OpenTelemetry Tracer Provider
|
|
tp, err := observability.TracerProvider("tercul-api", cfg.Environment)
|
|
if err != nil {
|
|
app_log.Fatal(err, "Failed to initialize OpenTelemetry tracer")
|
|
}
|
|
defer func() {
|
|
if err := tp.Shutdown(context.Background()); err != nil {
|
|
app_log.Error(err, "Error shutting down tracer provider")
|
|
}
|
|
}()
|
|
|
|
// Initialize Prometheus metrics
|
|
reg := prometheus.NewRegistry()
|
|
metrics := observability.NewMetrics(reg) // Metrics are registered automatically
|
|
|
|
app_log.Info(fmt.Sprintf("Starting Tercul application in %s environment, version 1.0.0", cfg.Environment))
|
|
|
|
// Initialize database connection
|
|
database, err := db.InitDB(cfg, metrics)
|
|
if err != nil {
|
|
app_log.Fatal(err, "Failed to initialize database")
|
|
}
|
|
defer db.Close(database)
|
|
|
|
if err := runMigrations(database, cfg.MigrationPath); err != nil {
|
|
app_log.Fatal(err, "Failed to apply database migrations")
|
|
}
|
|
|
|
// Initialize Weaviate client
|
|
weaviateCfg := weaviate.Config{
|
|
Host: cfg.WeaviateHost,
|
|
Scheme: cfg.WeaviateScheme,
|
|
}
|
|
weaviateClient, err := weaviate.NewClient(weaviateCfg)
|
|
if err != nil {
|
|
app_log.Fatal(err, "Failed to create weaviate client")
|
|
}
|
|
|
|
// Create search client
|
|
searchClient := search.NewWeaviateWrapper(weaviateClient)
|
|
|
|
// Create repositories
|
|
repos := dbsql.NewRepositories(database, cfg)
|
|
|
|
// Create linguistics dependencies
|
|
analysisRepo := linguistics.NewGORMAnalysisRepository(database)
|
|
sentimentProvider, err := linguistics.NewGoVADERSentimentProvider()
|
|
if err != nil {
|
|
app_log.Fatal(err, "Failed to create sentiment provider")
|
|
}
|
|
|
|
// Create platform components
|
|
jwtManager := auth.NewJWTManager(cfg)
|
|
|
|
// Create application services
|
|
analyticsService := analytics.NewService(repos.Analytics, analysisRepo, repos.Translation, repos.Work, sentimentProvider)
|
|
localizationService := localization.NewService(repos.Localization)
|
|
searchService := appsearch.NewService(searchClient, localizationService)
|
|
|
|
// Create application dependencies
|
|
deps := app.Dependencies{
|
|
WorkRepo: repos.Work,
|
|
UserRepo: repos.User,
|
|
UserProfileRepo: repos.UserProfile,
|
|
AuthorRepo: repos.Author,
|
|
TranslationRepo: repos.Translation,
|
|
CommentRepo: repos.Comment,
|
|
LikeRepo: repos.Like,
|
|
BookmarkRepo: repos.Bookmark,
|
|
CollectionRepo: repos.Collection,
|
|
TagRepo: repos.Tag,
|
|
CategoryRepo: repos.Category,
|
|
BookRepo: repos.Book,
|
|
PublisherRepo: repos.Publisher,
|
|
SourceRepo: repos.Source,
|
|
CopyrightRepo: repos.Copyright,
|
|
MonetizationRepo: repos.Monetization,
|
|
ContributionRepo: repos.Contribution,
|
|
AnalyticsRepo: repos.Analytics,
|
|
AuthRepo: repos.Auth,
|
|
LocalizationRepo: repos.Localization,
|
|
SearchClient: searchClient,
|
|
AnalyticsService: analyticsService,
|
|
JWTManager: jwtManager,
|
|
}
|
|
|
|
// Create application
|
|
application := app.NewApplication(deps)
|
|
application.Search = searchService // Manually set the search service
|
|
|
|
// Create GraphQL server
|
|
resolver := &graphql.Resolver{
|
|
App: application,
|
|
}
|
|
|
|
// Create the main API handler with all middleware.
|
|
apiHandler := NewServerWithAuth(resolver, jwtManager, metrics, obsLogger)
|
|
|
|
// Create the main ServeMux and register all handlers.
|
|
mux := http.NewServeMux()
|
|
mux.Handle("/query", apiHandler)
|
|
mux.Handle("/playground", playground.Handler("GraphQL Playground", "/query"))
|
|
mux.Handle("/metrics", observability.PrometheusHandler(reg))
|
|
|
|
// Create a single HTTP server with the main mux.
|
|
mainServer := &http.Server{
|
|
Addr: cfg.ServerPort,
|
|
Handler: mux,
|
|
}
|
|
app_log.Info(fmt.Sprintf("API server listening on port %s", cfg.ServerPort))
|
|
|
|
// Start the main server in a goroutine
|
|
go func() {
|
|
if err := mainServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
app_log.Fatal(err, "Failed to start server")
|
|
}
|
|
}()
|
|
|
|
// Wait for interrupt signal to gracefully shutdown the server
|
|
quit := make(chan os.Signal, 1)
|
|
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
|
<-quit
|
|
app_log.Info("Shutting down server...")
|
|
|
|
// Graceful shutdown
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
|
|
if err := mainServer.Shutdown(ctx); err != nil {
|
|
app_log.Error(err, "Server forced to shutdown")
|
|
}
|
|
|
|
app_log.Info("Server shut down successfully")
|
|
} |