Skip to content

Commit

Permalink
feat: Run function route
Browse files Browse the repository at this point in the history
  • Loading branch information
WoodenMaiden committed Apr 8, 2024
1 parent 7ff5650 commit 67fedd7
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 4 deletions.
14 changes: 10 additions & 4 deletions database/functionState.go
Original file line number Diff line number Diff line change
@@ -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"
}
60 changes: 60 additions & 0 deletions routes/runFunction.go
Original file line number Diff line number Diff line change
@@ -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"})
}

0 comments on commit 67fedd7

Please sign in to comment.