63 lines
2.0 KiB
Go
63 lines
2.0 KiB
Go
package invoke
|
|
|
|
import (
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"git.oblat.lv/alex/triggerssmith/internal/config"
|
|
"git.oblat.lv/alex/triggerssmith/internal/worker"
|
|
"github.com/go-chi/chi/v5"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type Function struct {
|
|
ID uint `gorm:"primaryKey;autoIncrement"`
|
|
FunctionName string `gorm:"not null"`
|
|
Version string `gorm:"not null"`
|
|
Path string `gorm:"not null"`
|
|
CreatedAt time.Time `gorm:"autoCreateTime"`
|
|
DeletedAt gorm.DeletedAt `gorm:"index"`
|
|
}
|
|
|
|
func InvokeHandler(cfg *config.Config) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id := chi.URLParam(r, "function_id")
|
|
version := chi.URLParam(r, "function_version")
|
|
slog.Debug("executing a function", slog.String("id", id), slog.String("version", version))
|
|
root := cfg.Functions.FunctionDir
|
|
treeCfg, _ := worker.LoadTreeConfig(root)
|
|
db, err := worker.OpenDB(treeCfg, root)
|
|
if err != nil {
|
|
slog.Error("Failed to open db", slog.String("err", err.Error()))
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
//f, _ := worker.FindFunction(db, "echo", "0.0.1-00130112025")
|
|
f, err := worker.FindFunction(db, id, version)
|
|
if err != nil {
|
|
slog.Error("Failed to find function", slog.String("err", err.Error()))
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
fc, err := worker.LoadFunctionConfig(root, f.FunctionName, f.Path)
|
|
if err != nil {
|
|
slog.Error("Failed to load function config", slog.String("err", err.Error()))
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
input, _ := io.ReadAll(r.Body)
|
|
output, err := worker.RunFunction(filepath.Join(root, f.FunctionName, f.Path, fc.Entry), fc, input)
|
|
if err != nil {
|
|
slog.Error("Failed to run function", slog.String("err", err.Error()))
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
slog.Debug("executing done", slog.Any("in", input), slog.Any("out", output))
|
|
w.Write(output)
|
|
}
|
|
}
|