-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (94 loc) · 2.55 KB
/
main.go
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
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
_ "net/http/pprof"
"github.com/Arinji2/ai-backend/completions"
"github.com/Arinji2/ai-backend/tasks"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/render"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
} else {
if os.Getenv("ENVIRONMENT") == "PRODUCTION" {
fmt.Println("Production Environment")
} else {
fmt.Println("Environment File Found")
}
}
r := chi.NewRouter()
r.Use(SkipLoggingMiddleware)
r.Use(CheckAccessKeyMiddleware)
r.Get("/", healthHandler)
r.Get("/health", healthCheckHandler)
r.Post("/completions", completions.CompletionsHandler)
taskManager := tasks.GetTaskManager()
go func() {
ticker := time.NewTicker(time.Second * 10)
for range ticker.C {
for _, tasks := range taskManager.AllTasks.Tasks {
if len(tasks.QueuedProcesses) == 0 {
continue
}
fmt.Println("Tasks In Queue: ", tasks.DisplayName, len(tasks.QueuedProcesses))
}
if len(taskManager.PendingTasks.PendingQueue) > 0 {
fmt.Println("Pending Tasks: ", len(taskManager.PendingTasks.PendingQueue))
}
}
}()
go func() {
//The task manager breaks apart after 2+ hours, we restart it as a temp fix
ticker := time.NewTicker(time.Hour * 2)
for range ticker.C {
os.Exit(0)
}
}()
http.ListenAndServe(":8080", r)
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Vibeify Backend: Request Received")
w.Write([]byte("Vibeify Backend: Request Received"))
render.Status(r, http.StatusOK)
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Vibeify Backend: Health Check"))
render.Status(r, http.StatusOK)
}
func SkipLoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" {
next.ServeHTTP(w, r)
return
}
middleware.Logger(next).ServeHTTP(w, r)
})
}
func CheckAccessKeyMiddleware(next http.Handler) http.Handler {
isProduction := os.Getenv("ENVIRONMENT") == "PRODUCTION"
if !isProduction {
return next
}
accessKey := os.Getenv("ACCESS_KEY")
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/health" {
next.ServeHTTP(w, r)
return
}
inputAccessKey := r.Header.Get("Authorization")
if inputAccessKey != accessKey {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("Unauthorized"))
return
}
middleware.Logger(next).ServeHTTP(w, r)
})
}