p2p-llm / main.go
arpinfidel's picture
temp
48511d8
package main
import (
"fmt"
"log"
"net/http"
"time"
"github.com/arpinfidel/p2p-llm/auth"
"github.com/arpinfidel/p2p-llm/config"
"github.com/arpinfidel/p2p-llm/db"
"github.com/arpinfidel/p2p-llm/peers"
"github.com/arpinfidel/p2p-llm/proxy"
_ "modernc.org/sqlite" // SQLite driver
)
type Application struct {
cfg *config.Config
database db.Database
authService *auth.AuthService
jwtMiddleware *auth.JWTMiddleware
proxyHandler *proxy.ProxyHandler
peerHandler *peers.PeerHandler
}
func NewApplication() (*Application, error) {
// Load configuration (ignore secrets since we only need keys)
cfg, _, keys, err := config.Load()
if err != nil {
return nil, fmt.Errorf("failed to load configuration: %w", err)
}
// Initialize database
database, err := db.NewSQLiteDB(cfg)
if err != nil {
return nil, fmt.Errorf("failed to initialize database: %w", err)
}
// Initialize repositories
authRepo := db.NewSQLiteAPIKeyRepository(database)
peerRepo := db.NewSQLitePeerRepository(database)
// Create tables
if err := db.CreateTables(database); err != nil {
return nil, fmt.Errorf("failed to create tables: %w", err)
}
// Initialize auth service
authService := auth.NewAuthService(keys.PrivateKey, authRepo)
// Initialize JWT middleware
jwtMiddleware := auth.NewJWTMiddleware(keys.PublicKey)
proxyHandler := proxy.NewProxyHandler(cfg, peerRepo)
// Initialize peer service and handler
peerService := peers.NewPeerService(cfg, peerRepo)
peerHandler := peers.NewPeerHandler(peerService)
return &Application{
cfg: cfg,
database: database,
authService: authService,
jwtMiddleware: jwtMiddleware,
proxyHandler: proxyHandler,
peerHandler: peerHandler,
}, nil
}
func (app *Application) Close() {
if app.database != nil {
app.database.Close()
}
}
func main() {
app, err := NewApplication()
if err != nil {
log.Fatalf("Failed to initialize application: %v", err)
}
defer app.Close()
// Create auth handler
authHandler := auth.NewAuthHandler(app.authService)
// Register routes
RegisterRoutes(authHandler, app.peerHandler, app.jwtMiddleware, app.proxyHandler)
// Start server
log.Printf("Starting proxy server on %s", app.cfg.Port)
server := &http.Server{
Addr: app.cfg.Port,
ReadTimeout: 10 * time.Minute,
WriteTimeout: 10 * time.Minute,
}
log.Fatal(server.ListenAndServe())
}