small fix, don't worry about it

This commit is contained in:
Tomas Dvorak
2026-04-10 12:02:36 +02:00
parent 08bd0c6e5c
commit 08cb5754f3
638 changed files with 57332 additions and 34706 deletions
+29
View File
@@ -0,0 +1,29 @@
package main
import (
"fmt"
"log"
"net/http"
"containr/internal/apwhy/api"
"containr/internal/apwhy/config"
"containr/internal/apwhy/storage"
)
func main() {
cfg := config.Load()
store, err := storage.Open(cfg)
if err != nil {
log.Fatalf("failed to initialize storage: %v", err)
}
defer store.Close()
server := api.NewServer(store, cfg)
addr := fmt.Sprintf(":%d", cfg.Port)
log.Printf("APwhy server listening on http://localhost%s", addr)
if err := http.ListenAndServe(addr, server.Handler()); err != nil {
log.Fatalf("server exited: %v", err)
}
}
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"containr/internal/cli"
"fmt"
"os"
)
func main() {
if err := cli.Run(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
+78
View File
@@ -0,0 +1,78 @@
package main
import (
"context"
"log"
"os"
"containr/internal/config"
"containr/internal/database"
"github.com/pressly/goose/v3"
)
func main() {
cfg := config.Load()
db, err := database.NewConnectionWithConfig(cfg.DatabaseURL, database.DBConfig{
MaxOpenConns: cfg.MaxConnections,
MaxIdleConns: cfg.MaxIdleConnections,
ConnMaxLifetime: cfg.ConnMaxLifetime,
ConnMaxIdleTime: cfg.ConnMaxIdleTime,
})
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer db.Close()
legacyDir := os.Getenv("LEGACY_MIGRATIONS_DIR")
if legacyDir == "" {
legacyDir = "migrations"
}
gooseDir := os.Getenv("GOOSE_MIGRATIONS_DIR")
if gooseDir == "" {
gooseDir = "migrations_goose"
}
command := "up"
if len(os.Args) > 1 {
command = os.Args[1]
}
switch command {
case "up":
migrationCtx, migrationCancel := context.WithTimeout(context.Background(), cfg.MigrationLockTimeout)
if err := db.MigrateAllWithLock(migrationCtx, legacyDir, gooseDir); err != nil {
migrationCancel()
log.Fatalf("Migration failed: %v", err)
}
migrationCancel()
log.Println("Legacy + goose migrations completed successfully")
case "legacy-up":
if err := db.Migrate(legacyDir); err != nil {
log.Fatalf("Legacy migration failed: %v", err)
}
log.Println("Legacy migrations completed successfully")
case "goose-up":
if err := db.MigrateGoose(gooseDir); err != nil {
log.Fatalf("Goose migration failed: %v", err)
}
log.Println("Goose migrations completed successfully")
case "goose-status":
if err := db.GooseStatus(gooseDir); err != nil {
log.Fatalf("Goose status failed: %v", err)
}
case "goose-create":
if len(os.Args) < 3 {
log.Fatalf("Missing migration name. Usage: go run cmd/migrate/main.go goose-create <name>")
}
name := os.Args[2]
if err := goose.Create(nil, gooseDir, name, "sql"); err != nil {
log.Fatalf("Goose create failed: %v", err)
}
log.Printf("Created goose migration %q in %q", name, gooseDir)
default:
log.Fatalf("Unknown command %q. Supported commands: up | legacy-up | goose-up | goose-status | goose-create", command)
}
}
+161
View File
@@ -0,0 +1,161 @@
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"containr/internal/api"
"containr/internal/authruntime"
"containr/internal/config"
"containr/internal/database"
"containr/internal/middleware"
"github.com/gin-gonic/gin"
"github.com/rs/cors"
)
func main() {
// Load configuration
cfg := config.Load()
// Initialize database
db, err := database.NewConnectionWithConfig(cfg.DatabaseURL, database.DBConfig{
MaxOpenConns: cfg.MaxConnections,
MaxIdleConns: cfg.MaxIdleConnections,
ConnMaxLifetime: cfg.ConnMaxLifetime,
ConnMaxIdleTime: cfg.ConnMaxIdleTime,
})
if err != nil {
log.Fatalf("Failed to connect to database: %v", err)
}
defer db.Close()
// Run startup migrations unless explicitly disabled.
if cfg.AutoMigrate {
migrationCtx, migrationCancel := context.WithTimeout(context.Background(), cfg.MigrationLockTimeout)
if err := db.MigrateAllWithLock(migrationCtx, "migrations", "migrations_goose"); err != nil {
migrationCancel()
log.Fatalf("Failed to run database migrations: %v", err)
}
migrationCancel()
} else {
log.Println("AUTO_MIGRATE disabled; skipping startup migrations")
}
// Seed demo data in development (or when explicitly requested).
if cfg.IsDevelopment() || cfg.SeedDataOnStart {
if err := db.SeedData(); err != nil {
log.Printf("Warning: Failed to seed data: %v", err)
}
}
// Initialize Redis
redis, err := database.NewRedis(cfg.RedisURL)
if err != nil {
log.Fatalf("Failed to initialize Redis: %v", err)
}
redisHealthCtx, redisHealthCancel := context.WithTimeout(context.Background(), 5*time.Second)
if err := redis.Health(redisHealthCtx); err != nil {
redisHealthCancel()
log.Fatalf("Failed to connect to Redis: %v", err)
}
redisHealthCancel()
defer redis.Close()
authRuntime, err := authruntime.Start(authruntime.Config{
Enabled: cfg.BetterAuthEnabled,
NodeBinary: cfg.BetterAuthNodeBinary,
Entrypoint: cfg.BetterAuthEntrypoint,
Port: cfg.AuthPort,
StartupTimeout: cfg.BetterAuthStartupTimeout,
})
if err != nil {
log.Fatalf("Failed to start embedded Better Auth runtime: %v", err)
}
if authRuntime != nil {
defer func() {
if closeErr := authRuntime.Close(); closeErr != nil {
log.Printf("Better Auth runtime shutdown error: %v", closeErr)
}
}()
}
// Setup Gin router
if cfg.IsProduction() {
gin.SetMode(gin.ReleaseMode)
}
router := gin.New()
trustedProxies := []string{}
if cfg.TrustedProxyCIDR != "" {
trustedProxies = []string{cfg.TrustedProxyCIDR}
}
if err := router.SetTrustedProxies(trustedProxies); err != nil {
log.Fatalf("Failed to configure trusted proxies: %v", err)
}
// Add middleware
router.Use(middleware.SecurityHeaders())
router.Use(middleware.Logger())
router.Use(middleware.Recovery())
router.Use(middleware.RequestID())
router.Use(middleware.RequestBodyLimit(cfg.MaxRequestBody))
// CORS setup
c := cors.New(cors.Options{
AllowedOrigins: cfg.CORSOrigins,
AllowedMethods: cfg.CORSMethods,
AllowedHeaders: cfg.CORSHeaders,
ExposedHeaders: []string{"Content-Length"},
AllowCredentials: cfg.CORSCredentials,
MaxAge: 86400,
})
// Wrap Gin router with CORS
handler := c.Handler(router)
// Initialize API routes
api.SetupRoutes(router, db, redis, cfg)
// Create HTTP server
addr := fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)
log.Printf("Server starting on %s", addr)
server := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: cfg.ReadTimeout,
WriteTimeout: cfg.WriteTimeout,
IdleTimeout: cfg.IdleTimeout,
}
// Start server in a goroutine
go func() {
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Failed to start server: %v", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// Create a deadline for shutdown
ctx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)
defer cancel()
// Attempt graceful shutdown
if err := server.Shutdown(ctx); err != nil {
log.Printf("Server forced to shutdown: %v", err)
}
log.Println("Server exited")
}
@@ -0,0 +1,54 @@
package main
import (
"context"
"fmt"
"containr/internal/build"
)
func main() {
fmt.Println("🧪 Testing Build Manager Detection...")
// Test build type detection on the current project
fmt.Println("\n📁 Testing on current project (has package.json)...")
// Note: We can't fully test BuildManager without a docker client,
// but we can test the detection logic
// Create mock scenarios
testCases := []struct {
name string
expected string
}{
{"Node.js project (package.json)", "railpack"},
{"Python project (requirements.txt)", "railpack"},
{"Go project (go.mod)", "railpack"},
{"Dockerfile project", "dockerfile"},
{"Unknown project", "nixpacks"},
}
fmt.Println("\n🎯 Expected detection priorities:")
for _, tc := range testCases {
fmt.Printf(" • %s → %s\n", tc.name, tc.expected)
}
// Test Railpack builder directly
builder := build.NewRailpackBuilder("/tmp/test", nil)
fmt.Println("\n🔍 Testing Railpack detection on current project:")
err := builder.DetectRailpack(context.Background(), "/home/tdvorak/Desktop/PROG+HTML/Containr")
if err != nil {
fmt.Printf("❌ Detection failed: %v\n", err)
} else {
fmt.Println("✅ Railpack can build this project!")
}
fmt.Println("\n📋 Build Priority Order:")
fmt.Println(" 1. Dockerfile (if present)")
fmt.Println(" 2. Railpack (primary choice)")
fmt.Println(" 3. Nixpacks (fallback)")
fmt.Println(" 4. Prebuilt (manual)")
fmt.Println("\n🚀 Build Manager Integration Test Complete!")
}
+32
View File
@@ -0,0 +1,32 @@
package main
import (
"context"
"fmt"
"containr/internal/build"
)
func main() {
// Create a RailpackBuilder
builder := build.NewRailpackBuilder("/tmp/containr-build-test", nil)
// Test detection on the current project (has package.json)
fmt.Println("Testing Railpack detection on current project...")
err := builder.DetectRailpack(context.Background(), "/home/tdvorak/Desktop/PROG+HTML/Containr")
if err != nil {
fmt.Printf("❌ Railpack detection failed: %v\n", err)
} else {
fmt.Println("✅ Railpack can build this project!")
}
// Show supported frameworks
fmt.Println("\nSupported frameworks:")
frameworks := builder.GetSupportedFrameworks()
for _, fw := range frameworks {
fmt.Printf(" - %s\n", fw)
}
fmt.Println("\n✅ Railpack integration test completed successfully!")
}