Simulation Upload Update

This commit is contained in:
2026-02-21 22:21:05 -05:00
parent 4c24b141fe
commit 913f45b51b
20 changed files with 1479 additions and 492 deletions

View File

@@ -38,6 +38,33 @@ func createSimulation(w http.ResponseWriter, r *http.Request) {
return
}
// Pattern validation: must contain a search pattern (spiral, lawnmower, or levy)
hasPattern := false
// Fast regex check or parse to detect patterns
var jsonParsed map[string]interface{}
err = json.Unmarshal(bodyBytes, &jsonParsed)
if err != nil {
http.Error(w, "Invalid configuration format: must be valid JSON", http.StatusBadRequest)
return
}
// Valid JSON, traverse and look for pattern
for k, v := range jsonParsed {
if k == "search.yaml" || k == "search" {
if searchMap, ok := v.(map[string]interface{}); ok {
if _, ok := searchMap["spiral"]; ok { hasPattern = true }
if _, ok := searchMap["lawnmower"]; ok { hasPattern = true }
if _, ok := searchMap["levy"]; ok { hasPattern = true }
}
}
}
if !hasPattern {
http.Error(w, "Simulation configuration must include a search pattern (spiral, lawnmower, or levy)", http.StatusBadRequest)
return
}
// Check if this config already exists
var existingID int
var existingName string
@@ -146,6 +173,11 @@ func getSimulationDetails(w http.ResponseWriter, r *http.Request) {
return
}
if r.Method == "PUT" && len(pathParts) > 1 && pathParts[1] == "rename" {
renameSimulation(w, r, idStr)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
@@ -169,6 +201,9 @@ func getSimulationDetails(w http.ResponseWriter, r *http.Request) {
var fname string
if err := rows.Scan(&fname); err == nil {
s.Resources = append(s.Resources, fname)
if stat, err := os.Stat(filepath.Join("../results", s.Name, fname)); err == nil {
s.TotalSizeBytes += stat.Size()
}
}
}
}
@@ -209,6 +244,63 @@ func updateSimulationTime(w http.ResponseWriter, r *http.Request, idStr string)
json.NewEncoder(w).Encode(map[string]string{"status": "success"})
}
func renameSimulation(w http.ResponseWriter, r *http.Request, idStr string) {
var reqBody struct {
Name string `json:"name"`
}
err := json.NewDecoder(r.Body).Decode(&reqBody)
if err != nil || strings.TrimSpace(reqBody.Name) == "" {
http.Error(w, "Invalid request body or missing name", http.StatusBadRequest)
return
}
defer r.Body.Close()
newName := strings.TrimSpace(reqBody.Name)
var oldName string
err = db.QueryRow("SELECT name FROM simulations WHERE id = ?", idStr).Scan(&oldName)
if err != nil {
http.Error(w, "Simulation not found", http.StatusNotFound)
return
}
// Make sure the new name doesn't already exist
var tempID int
err = db.QueryRow("SELECT id FROM simulations WHERE name = ?", newName).Scan(&tempID)
if err == nil {
http.Error(w, "A simulation with that name already exists", http.StatusConflict)
return
}
// Rename the physical storage folder to maintain link parity
oldDirPath := filepath.Join("../results", oldName)
newDirPath := filepath.Join("../results", newName)
if _, statErr := os.Stat(oldDirPath); statErr == nil {
err = os.Rename(oldDirPath, newDirPath)
if err != nil {
log.Println("Error renaming directory:", err)
http.Error(w, "Failed to rename results directory", http.StatusInternalServerError)
return
}
} else {
// Just ensure target dir exists
os.MkdirAll(newDirPath, 0755)
}
_, err = db.Exec("UPDATE simulations SET name = ? WHERE id = ?", newName, idStr)
if err != nil {
// Attempt revert if DB dies halfway
os.Rename(newDirPath, oldDirPath)
log.Println("Update simulation name error:", err)
http.Error(w, "Failed to update database", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "success", "new_name": newName})
}
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)
@@ -248,10 +340,13 @@ func uploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr stri
return
}
// Route through faststart transcoder if it happens to be an .avi
finalFilename := transcodeIfNeeded(filepath.Join("../results", simName), handler.Filename)
var resID int
err = db.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, handler.Filename).Scan(&resID)
err = db.QueryRow("SELECT id FROM resources WHERE simulation_id = ? AND filename = ?", idStr, finalFilename).Scan(&resID)
if err == sql.ErrNoRows {
_, err = db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, handler.Filename)
_, err = db.Exec("INSERT INTO resources(simulation_id, filename) VALUES(?, ?)", idStr, finalFilename)
if err != nil {
log.Println("Error inserting uploaded resource into db:", err)
}
@@ -260,6 +355,6 @@ func uploadSimulationResource(w http.ResponseWriter, r *http.Request, idStr stri
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"status": "success",
"filename": handler.Filename,
"filename": finalFilename,
})
}

View File

@@ -5,6 +5,7 @@ import (
"log"
"os"
"path/filepath"
"strings"
_ "github.com/mattn/go-sqlite3"
)
@@ -17,6 +18,7 @@ type Simulation struct {
Config *string `json:"config"`
SearchTime *float64 `json:"search_time"`
TotalTime *float64 `json:"total_time"`
TotalSizeBytes int64 `json:"total_size_bytes"`
}
var db *sql.DB
@@ -79,9 +81,20 @@ func syncResults() {
// Clear old resources for this simulation
db.Exec("DELETE FROM resources WHERE simulation_id = ?", simID)
// Check for already inserted to avoid dupes if both exist
seen := make(map[string]bool)
for _, sf := range subFiles {
if !sf.IsDir() {
insertResource(simID, sf.Name())
finalName := sf.Name()
if strings.ToLower(filepath.Ext(finalName)) == ".avi" {
finalName = transcodeIfNeeded(filepath.Join(resultsDir, simName), finalName)
}
if !seen[finalName] {
insertResource(simID, finalName)
seen[finalName] = true
}
}
}
}

View File

@@ -1,5 +1,5 @@
module sim-link-server
go 1.22.2
go 1.23
require github.com/mattn/go-sqlite3 v1.14.34 // indirect

46
server/transcoder.go Normal file
View File

@@ -0,0 +1,46 @@
package main
import (
"log"
"os"
"os/exec"
"path/filepath"
"strings"
)
func transcodeIfNeeded(simDir, filename string) string {
ext := strings.ToLower(filepath.Ext(filename))
if ext != ".avi" {
return filename
}
baseName := strings.TrimSuffix(filename, filepath.Ext(filename))
mp4Filename := baseName + ".mp4"
aviPath := filepath.Join(simDir, filename)
mp4Path := filepath.Join(simDir, mp4Filename)
// If the file was already transcoded prior, just remove the stale .avi and return .mp4
if _, err := os.Stat(mp4Path); err == nil {
os.Remove(aviPath)
return mp4Filename
}
log.Printf("Attempting GPU Transcoding (h264_nvenc) %s to %s...\n", aviPath, mp4Path)
cmdGPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "h264_nvenc", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
if err := cmdGPU.Run(); err == nil {
os.Remove(aviPath)
return mp4Filename
}
log.Printf("GPU transcoding failed/unavailable, falling back to CPU (libx264) for %s...\n", aviPath)
cmdCPU := exec.Command("ffmpeg", "-y", "-i", aviPath, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart", mp4Path)
if err := cmdCPU.Run(); err == nil {
os.Remove(aviPath)
return mp4Filename
} else {
log.Println("Failed to transcode (both GPU and CPU):", err)
return filename
}
}