File size: 2,398 Bytes
48511d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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())
}