From 67fedd7153362edef3f4c77eb97e18e64a4a2606 Mon Sep 17 00:00:00 2001 From: WoodenMaiden Date: Wed, 20 Mar 2024 16:43:58 +0100 Subject: [PATCH] feat: Run function route --- database/functionState.go | 14 ++++++--- routes/runFunction.go | 60 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 4 deletions(-) create mode 100644 routes/runFunction.go diff --git a/database/functionState.go b/database/functionState.go index a446f73..d1e322b 100644 --- a/database/functionState.go +++ b/database/functionState.go @@ -1,14 +1,20 @@ package database import ( - "gorm.io/gorm" "github.com/google/uuid" + "gorm.io/gorm" ) type FunctionState struct { gorm.Model - ID uuid.UUID `gorm:"primarykey;type:uuid;default:gen_random_uuid()"` - Code string - Status string + ID uuid.UUID `json:"id", gorm:"primarykey;type:uuid;default:gen_random_uuid()"` + Code string `json:"code"` + Status string `json:"status"` + Address string `json:"address"` + Port uint16 `json:"port"` // OwnerID } + +func (FunctionState) TableName() string { + return "function_state" +} diff --git a/routes/runFunction.go b/routes/runFunction.go new file mode 100644 index 0000000..81a0ed8 --- /dev/null +++ b/routes/runFunction.go @@ -0,0 +1,60 @@ +package routes + +import ( + "errors" + "log" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/do4-2022/grobuzin/database" +) + +func (c *Controller) RunFunction(ctx *gin.Context) { + fnID, err := uuid.Parse(ctx.Param("id")) + + var fnBody any; // because the body is entirely defined by the user, we just forward it to the function + + if err := ctx.BindJSON(&fnBody); err != nil { + ctx.JSON(400, gin.H{"error": "Could not parse function body"}) + return + } + + if err != nil { + ctx.JSON(400, gin.H{"error": "Invalid function ID"}) + return + } + + var fn database.FunctionState + err = c.DB.Where(&database.FunctionState{ID: fnID}).First(&fn).Error + + if (err != nil && errors.Is(err, gorm.ErrRecordNotFound)) { + log.Println("Waiting for new function to be ready") + + for tries := 0 ; tries < 5; tries++ { + if !errors.Is(err, gorm.ErrRecordNotFound) { + ctx.JSON(500, gin.H{"error": err.Error()}) + return + } else { + log.Println("Function", fn.ID, "is not ready yet... Retrying") + + time.Sleep(100 * time.Millisecond) + err = c.DB.Where(&database.FunctionState{ID: fnID}).First(&fn).Error + } + + if fn.Status == "Ready" { + log.Println("Function", fn.ID, "is ready") + + break + }; + + } + } + + ctx.JSON(200, fn) + // forward the body to fn.Address:fn.Port + // define this + // ctx.JSON(200, gin.H{"stdout": "stdout", "stderr": "stderr", "status": "status"}) +} \ No newline at end of file