Inital Commit
This commit is contained in:
265
server/api.go
Normal file
265
server/api.go
Normal file
@@ -0,0 +1,265 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func createSimulation(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "POST")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
bodyBytes, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to read request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
configStr := string(bodyBytes)
|
||||
|
||||
if configStr == "" {
|
||||
http.Error(w, "Config cannot be empty", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this config already exists
|
||||
var existingID int
|
||||
var existingName string
|
||||
err = db.QueryRow("SELECT id, name FROM simulations WHERE config = ?", configStr).Scan(&existingID, &existingName)
|
||||
if err == nil {
|
||||
// Found exact config, return the existing run info
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": existingID,
|
||||
"name": existingName,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
var count int
|
||||
db.QueryRow("SELECT COUNT(*) FROM simulations").Scan(&count)
|
||||
newName := fmt.Sprintf("simulation_%d", count+1)
|
||||
|
||||
// ensure name doesn't exist
|
||||
for {
|
||||
var temp int
|
||||
err := db.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&temp)
|
||||
if err == sql.ErrNoRows {
|
||||
break
|
||||
}
|
||||
count++
|
||||
newName = fmt.Sprintf("simulation_%d", count+1)
|
||||
}
|
||||
|
||||
res, err := db.Exec("INSERT INTO simulations(name, config) VALUES(?, ?)", newName, configStr)
|
||||
if err != nil {
|
||||
log.Println("Insert simulation error:", err)
|
||||
http.Error(w, "Failed to create", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
newID, _ := res.LastInsertId()
|
||||
|
||||
// Ensure the directory exists
|
||||
resultsDir := filepath.Join("../results", newName)
|
||||
os.MkdirAll(resultsDir, 0755)
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"id": newID,
|
||||
"name": newName,
|
||||
})
|
||||
}
|
||||
|
||||
func getSimulations(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT id, name, config, created_at, search_time, total_time FROM simulations")
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var sims []Simulation
|
||||
for rows.Next() {
|
||||
var s Simulation
|
||||
err = rows.Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
|
||||
if err != nil {
|
||||
log.Println("Row scan error:", err)
|
||||
continue
|
||||
}
|
||||
sims = append(sims, s)
|
||||
}
|
||||
|
||||
if sims == nil {
|
||||
sims = []Simulation{}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(sims)
|
||||
}
|
||||
|
||||
func getSimulationDetails(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
if r.Method == "OPTIONS" {
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
return
|
||||
}
|
||||
|
||||
pathParts := strings.Split(strings.Trim(r.URL.Path[len("/api/simulations/"):], "/"), "/")
|
||||
idStr := pathParts[0]
|
||||
|
||||
if idStr == "" || idStr == "create" {
|
||||
http.Error(w, "Not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "PUT" && len(pathParts) > 1 && pathParts[1] == "time" {
|
||||
updateSimulationTime(w, r, idStr)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "POST" && len(pathParts) > 1 && pathParts[1] == "upload" {
|
||||
uploadSimulationResource(w, r, idStr)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method != "GET" {
|
||||
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
var s Simulation
|
||||
err := db.QueryRow("SELECT id, name, config, created_at, search_time, total_time FROM simulations WHERE id = ?", idStr).Scan(&s.ID, &s.Name, &s.Config, &s.CreatedAt, &s.SearchTime, &s.TotalTime)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
http.Error(w, "Simulation not found", http.StatusNotFound)
|
||||
} else {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
rows, err := db.Query("SELECT filename FROM resources WHERE simulation_id = ?", s.ID)
|
||||
if err == nil {
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var fname string
|
||||
if err := rows.Scan(&fname); err == nil {
|
||||
s.Resources = append(s.Resources, fname)
|
||||
}
|
||||
}
|
||||
}
|
||||
if s.Resources == nil {
|
||||
s.Resources = []string{}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(s)
|
||||
}
|
||||
|
||||
func updateSimulationTime(w http.ResponseWriter, r *http.Request, idStr string) {
|
||||
var reqBody struct {
|
||||
SearchTime *float64 `json:"search_time"`
|
||||
TotalTime *float64 `json:"total_time"`
|
||||
}
|
||||
|
||||
err := json.NewDecoder(r.Body).Decode(&reqBody)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer r.Body.Close()
|
||||
|
||||
if reqBody.SearchTime == nil || reqBody.TotalTime == nil {
|
||||
http.Error(w, "Missing search_time or total_time", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
_, err = db.Exec("UPDATE simulations SET search_time = ?, total_time = ? WHERE id = ?", *reqBody.SearchTime, *reqBody.TotalTime, idStr)
|
||||
if err != nil {
|
||||
log.Println("Update simulation error:", err)
|
||||
http.Error(w, "Failed to update", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
|
||||
}
|
||||
|
||||
func uploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr string) {
|
||||
var simName string
|
||||
err := db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&simName)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
http.Error(w, "Simulation not found", http.StatusNotFound)
|
||||
} else {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = r.ParseMultipartForm(500 << 20) // 500 MB max memory/file bounds
|
||||
if err != nil {
|
||||
http.Error(w, "Error parsing form: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
file, handler, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
destPath := filepath.Join("../results", simName, handler.Filename)
|
||||
dst, err := os.Create(destPath)
|
||||
if err != nil {
|
||||
http.Error(w, "Error creating destination file: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer dst.Close()
|
||||
|
||||
_, err = io.Copy(dst, file)
|
||||
if err != nil {
|
||||
http.Error(w, "Error saving file: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var resID int
|
||||
err = db.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, handler.Filename).Scan(&resID)
|
||||
if err == sql.ErrNoRows {
|
||||
_, err = db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, handler.Filename)
|
||||
if err != nil {
|
||||
log.Println("Error inserting uploaded resource into db:", err)
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{
|
||||
"status": "success",
|
||||
"filename": handler.Filename,
|
||||
})
|
||||
}
|
||||
118
server/db.go
Normal file
118
server/db.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
type Simulation struct {
|
||||
ID int `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Resources []string `json:"resources"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
Config *string `json:"config"`
|
||||
SearchTime *float64 `json:"search_time"`
|
||||
TotalTime *float64 `json:"total_time"`
|
||||
}
|
||||
|
||||
var db *sql.DB
|
||||
|
||||
func initDBConnection() {
|
||||
var err error
|
||||
db, err = sql.Open("sqlite3", "./sim-link.db")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
createTableSQL := `CREATE TABLE IF NOT EXISTS simulations (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"name" TEXT UNIQUE,
|
||||
"config" TEXT,
|
||||
"created_at" DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);`
|
||||
_, err = db.Exec(createTableSQL)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
db.Exec("ALTER TABLE simulations ADD COLUMN config TEXT") // Ignore error if exists
|
||||
db.Exec("ALTER TABLE simulations ADD COLUMN search_time REAL") // Ignore error if exists
|
||||
db.Exec("ALTER TABLE simulations ADD COLUMN total_time REAL") // Ignore error if exists
|
||||
|
||||
createResourcesTableSQL := `CREATE TABLE IF NOT EXISTS resources (
|
||||
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
|
||||
"simulation_id" INTEGER,
|
||||
"filename" TEXT,
|
||||
FOREIGN KEY(simulation_id) REFERENCES simulations(id)
|
||||
);`
|
||||
_, err = db.Exec(createResourcesTableSQL)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func syncResults() {
|
||||
resultsDir := "../results"
|
||||
if _, err := os.Stat(resultsDir); os.IsNotExist(err) {
|
||||
log.Println("Results directory does not exist, skipping sync")
|
||||
return
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(resultsDir)
|
||||
if err != nil {
|
||||
log.Println("Error reading results directory:", err)
|
||||
return
|
||||
}
|
||||
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() {
|
||||
simName := entry.Name()
|
||||
simID := insertSimulation(simName)
|
||||
|
||||
// Read subfiles
|
||||
subFiles, err := os.ReadDir(filepath.Join(resultsDir, simName))
|
||||
if err == nil {
|
||||
// Clear old resources for this simulation
|
||||
db.Exec("DELETE FROM resources WHERE simulation_id = ?", simID)
|
||||
|
||||
for _, sf := range subFiles {
|
||||
if !sf.IsDir() {
|
||||
insertResource(simID, sf.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
log.Println("Database synchronized with results directory")
|
||||
}
|
||||
|
||||
func insertSimulation(name string) int64 {
|
||||
var id int64
|
||||
err := db.QueryRow("SELECT id FROM simulations WHERE name = ?", name).Scan(&id)
|
||||
if err == sql.ErrNoRows {
|
||||
res, err := db.Exec("INSERT INTO simulations(name) VALUES(?)", name)
|
||||
if err != nil {
|
||||
log.Println("Error inserting simulation:", err)
|
||||
return 0
|
||||
}
|
||||
id, err = res.LastInsertId()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
} else if err != nil {
|
||||
log.Println("Error selecting simulation:", err)
|
||||
return 0
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func insertResource(simID int64, filename string) {
|
||||
_, err := db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", simID, filename)
|
||||
if err != nil {
|
||||
log.Println("Error inserting resource:", err)
|
||||
}
|
||||
}
|
||||
5
server/go.mod
Normal file
5
server/go.mod
Normal file
@@ -0,0 +1,5 @@
|
||||
module sim-link-server
|
||||
|
||||
go 1.22.2
|
||||
|
||||
require github.com/mattn/go-sqlite3 v1.14.34 // indirect
|
||||
2
server/go.sum
Normal file
2
server/go.sum
Normal file
@@ -0,0 +1,2 @@
|
||||
github.com/mattn/go-sqlite3 v1.14.34 h1:3NtcvcUnFBPsuRcno8pUtupspG/GM+9nZ88zgJcp6Zk=
|
||||
github.com/mattn/go-sqlite3 v1.14.34/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
57
server/main.go
Normal file
57
server/main.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
initDBConnection()
|
||||
defer db.Close()
|
||||
|
||||
syncResults()
|
||||
|
||||
// Handle API routes
|
||||
http.HandleFunc("/api/simulations", getSimulations)
|
||||
http.HandleFunc("/api/simulations/create", createSimulation)
|
||||
http.HandleFunc("/api/simulations/", getSimulationDetails)
|
||||
|
||||
// Serve the static files from results directory
|
||||
resultsDir := "../results"
|
||||
fsResults := http.FileServer(http.Dir(resultsDir))
|
||||
http.Handle("/results/", http.StripPrefix("/results/", fsResults))
|
||||
|
||||
// Serve the static frontend with SPA fallback
|
||||
frontendDir := "../build"
|
||||
fsFrontend := http.FileServer(http.Dir(frontendDir))
|
||||
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
path := filepath.Join(frontendDir, r.URL.Path)
|
||||
_, err := os.Stat(path)
|
||||
if os.IsNotExist(err) {
|
||||
http.ServeFile(w, r, filepath.Join(frontendDir, "index.html"))
|
||||
return
|
||||
}
|
||||
fsFrontend.ServeHTTP(w, r)
|
||||
})
|
||||
|
||||
fmt.Println("Server listening on port 5173")
|
||||
|
||||
// Wrap the default ServeMux with our logging middleware
|
||||
loggedMux := loggingMiddleware(http.DefaultServeMux)
|
||||
log.Fatal(http.ListenAndServe("0.0.0.0:5173", loggedMux))
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasPrefix(r.URL.Path, "/api/") {
|
||||
log.Printf("[%s] %s %s", r.RemoteAddr, r.Method, r.URL.Path)
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user