Skip to content

Commit

Permalink
Merge pull request #124 from bots-garden/122-create-a-response-structure
Browse files Browse the repository at this point in the history
📝 update start changes with Response, Request
  • Loading branch information
k33g authored Sep 3, 2022
2 parents e833f3d + a522db3 commit dd90b15
Show file tree
Hide file tree
Showing 88 changed files with 470 additions and 377 deletions.
1 change: 1 addition & 0 deletions .idea/webResources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 11 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ What is **Capsule**?

> 🖐 **The functions are developed with GoLang and compiled to wasm with TinyGo**
📦 Before executing or running a function, you need to download the last release of **Capsule**: https://github.com/bots-garden/capsule/releases/tag/0.1.8 (`v0.1.8 🐙[octopus]`)
📦 Before executing or running a function, you need to download the last release of **Capsule**: https://github.com/bots-garden/capsule/releases/tag/0.1.9 (`v0.1.9 🐞[ladybug]`)

> - **Capsule** is developed with GoLang and thanks to the 💜 **[Wazero](https://github.com/tetratelabs/wazero)** project
> - The wasm modules are developed in GoLang and compiled with TinyGo (with the WASI specification)
Expand Down Expand Up @@ -105,13 +105,13 @@ func main() {
hf.SetHandleHttp(Handle)
}

func Handle(bodyReq string, headersReq map[string]string) (bodyResp string, headersResp map[string]string, errResp error) {
hf.Log("📝 body: " + bodyReq)
func Handle(request hf.Request) (response hf.Response, errResp error) {
hf.Log("📝 Body: " + request.Body)

// Read the request headers
hf.Log("Content-Type: " + headersReq["Content-Type"])
hf.Log("Content-Length: " + headersReq["Content-Length"])
hf.Log("User-Agent: " + headersReq["User-Agent"])
hf.Log("Content-Type: " + request.Headers["Content-Type"])
hf.Log("Content-Length: " + request.Headers["Content-Length"])
hf.Log("User-Agent: " + request.Headers["User-Agent"])

// Read the MESSAGE environment variable
envMessage, err := hf.GetEnv("MESSAGE")
Expand All @@ -122,14 +122,14 @@ func Handle(bodyReq string, headersReq map[string]string) (bodyResp string, head
}

// Set the response content type and add a message header
headersResp = map[string]string{
headersResp := map[string]string{
"Content-Type": "application/json; charset=utf-8",
"Message": "👋 hello world 🌍",
}

jsonResponse := `{"message": "hey people!"}`

return jsonResponse, headersResp, err
return hf.Response{Body: jsonResponse, Headers: headersResp}, err
}
```
> - `hf.SetHandleHttp(Handle)` defines the called wasm function
Expand Down Expand Up @@ -224,7 +224,7 @@ func main() {
hf.SetHandleHttp(Handle)
}

func Handle(bodyReq string, headersReq map[string]string) (bodyResp string, headersResp map[string]string, errResp error) {
func Handle(request hf.Request) (response hf.Response, errResp error) {
html := `
<html>
<head>
Expand All @@ -239,11 +239,11 @@ func Handle(bodyReq string, headersReq map[string]string) (bodyResp string, head
</html>
`

headersResp = map[string]string{
headersResp := map[string]string{
"Content-Type": "text/html; charset=utf-8",
}

return html, headersResp, nil
return hf.Response{Body: html, Headers: headersResp}, nil
}
```

Expand Down
4 changes: 2 additions & 2 deletions capsule-launcher/hostfunctions/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ func Http(ctx context.Context, module api.Module,
headersStr := memory.ReadStringFromMemory(ctx, module, headersOffSet, headersByteCount)

//TODO: choose another separator: °
headersSlice := commons.CreateSliceFromString(headersStr, "|")
headersSlice := commons.CreateSliceFromString(headersStr, commons.StrSeparator)

//fmt.Println(headersSlice)

headersMap := commons.CreateMapFromSlice(headersSlice, ":")
headersMap := commons.CreateMapFromSlice(headersSlice, commons.FieldSeparator)

//fmt.Println(headersMap)
//fmt.Println(headersMap["Accept"])
Expand Down
2 changes: 1 addition & 1 deletion capsule-launcher/services/http/headers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
)

func GetHeadersMapFromString(headersStr string) map[string]string {
return commons.CreateMapFromSlice(commons.CreateSliceFromString(headersStr, "|"), ":")
return commons.CreateMapFromSlice(commons.CreateSliceFromString(headersStr, commons.StrSeparator), commons.FieldSeparator)
}

//TODO: add other content types
Expand Down
181 changes: 96 additions & 85 deletions capsule-launcher/services/http/http.go
Original file line number Diff line number Diff line change
@@ -1,122 +1,133 @@
package capsulehttp

import (
"encoding/json"
"fmt"
"github.com/bots-garden/capsule/capsule-launcher/hostfunctions"
"github.com/bots-garden/capsule/capsule-launcher/services/wasmrt"
"github.com/bots-garden/capsule/commons"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/mem"
"net/http"
"encoding/json"
"fmt"
"github.com/bots-garden/capsule/capsule-launcher/hostfunctions"
"github.com/bots-garden/capsule/capsule-launcher/services/wasmrt"
"github.com/bots-garden/capsule/commons"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/mem"
"net/http"
)

func Serve(httpPort string, wasmFile []byte, crt, key string) {
//fmt.Println("👋[checking]capsulehttp.Serve")
//fmt.Println("👋[checking]capsulehttp.Serve")

hostfunctions.HostInformation = `{"httpPort":` + httpPort + `}`
hostfunctions.HostInformation = `{"httpPort":` + httpPort + `}`

v, _ := mem.VirtualMemory()
v, _ := mem.VirtualMemory()

if commons.GetEnv("DEBUG", "false") == "false" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
if commons.GetEnv("DEBUG", "false") == "false" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}

router := gin.New()
router := gin.New()

router.GET("/host-metrics", func(c *gin.Context) {
jsonMap := make(map[string]interface{})
json.Unmarshal([]byte(v.String()), &jsonMap)
c.JSON(http.StatusOK, jsonMap)
})
router.GET("/host-metrics", func(c *gin.Context) {
jsonMap := make(map[string]interface{})
json.Unmarshal([]byte(v.String()), &jsonMap)
c.JSON(http.StatusOK, jsonMap)
})

router.GET("/health", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})
router.GET("/health", func(c *gin.Context) {
c.String(http.StatusOK, "OK")
})

//TODO: be able to get the query string from the wasm module
// we need to be able to return json, html, txt
router.GET("/", func(c *gin.Context) {
wasmRuntime, wasmModule, wasmFunction, ctx := capsule.GetNewWasmRuntimeForHttp(wasmFile)
defer wasmRuntime.Close(ctx)
router.GET("/", func(c *gin.Context) {

query := "empty" //🚧
queryPos, queryLen, free, err := capsule.ReserveMemorySpaceFor(query, wasmModule, ctx)
defer free.Call(ctx, queryPos)
jsonStr, _ := GetJsonStringFromPayloadRequest(c)
headersStr := GetHeadersStringFromHeadersRequest(c)
uri := c.Request.RequestURI
method := c.Request.Method

headersStr := GetHeadersStringFromHeadersRequest(c)
headersStrPos, headersStrLen, free, err := capsule.ReserveMemorySpaceFor(headersStr, wasmModule, ctx)
defer free.Call(ctx, headersStrPos)
wasmRuntime, wasmModule, wasmFunction, ctx := capsule.GetNewWasmRuntimeForHttp(wasmFile)
defer wasmRuntime.Close(ctx)

bytes, err := capsule.ExecHandleFunction(wasmFunction, wasmModule, ctx, queryPos, queryLen, headersStrPos, headersStrLen)
if err != nil {
c.String(500, "out of range of memory size")
}
bodyStr, headers := GetBodyAndHeaders(bytes, c)
uriPos, uriLen, free, err := capsule.ReserveMemorySpaceFor(uri, wasmModule, ctx)
defer free.Call(ctx, uriPos)

// check the return value
if commons.IsErrorString(bodyStr) {
SendErrorMessage(bodyStr, headers, c)
} else if IsBodyString(bodyStr) {
SendBodyMessage(bodyStr, headers, c)
} else {
c.String(http.StatusOK, bodyStr)
}
jsonStrPos, jsonStrLen, free, err := capsule.ReserveMemorySpaceFor(jsonStr, wasmModule, ctx)
defer free.Call(ctx, jsonStrPos)

})
headersStrPos, headersStrLen, free, err := capsule.ReserveMemorySpaceFor(headersStr, wasmModule, ctx)
defer free.Call(ctx, headersStrPos)

router.POST("/", func(c *gin.Context) {
methodPos, methodLen, free, err := capsule.ReserveMemorySpaceFor(method, wasmModule, ctx)
defer free.Call(ctx, methodPos)

// Parameters "setup"
jsonStr, _ := GetJsonStringFromPayloadRequest(c)
headersStr := GetHeadersStringFromHeadersRequest(c)
bytes, err := capsule.ExecHandleFunction(wasmFunction, wasmModule, ctx, jsonStrPos, jsonStrLen, uriPos, uriLen, headersStrPos, headersStrLen, methodPos, methodLen)
if err != nil {
c.String(500, "out of range of memory size")
}
bodyStr, headers := GetBodyAndHeaders(bytes, c)

//time.Sleep(500 * time.Millisecond)
// check the return value
if commons.IsErrorString(bodyStr) {
SendErrorMessage(bodyStr, headers, c)
} else if IsBodyString(bodyStr) {
SendBodyMessage(bodyStr, headers, c)
} else {
c.String(http.StatusOK, bodyStr)
}

wasmRuntime, wasmModule, wasmFunction, ctx := capsule.GetNewWasmRuntimeForHttp(wasmFile)
})

defer wasmRuntime.Close(ctx)
router.POST("/", func(c *gin.Context) {

jsonStrPos, jsonStrLen, free, err := capsule.ReserveMemorySpaceFor(jsonStr, wasmModule, ctx)
// Parameters "setup"
jsonStr, _ := GetJsonStringFromPayloadRequest(c)
headersStr := GetHeadersStringFromHeadersRequest(c)
uri := c.Request.RequestURI
method := c.Request.Method

defer free.Call(ctx, jsonStrPos)
wasmRuntime, wasmModule, wasmFunction, ctx := capsule.GetNewWasmRuntimeForHttp(wasmFile)
defer wasmRuntime.Close(ctx)

headersStrPos, headersStrLen, free, err := capsule.ReserveMemorySpaceFor(headersStr, wasmModule, ctx)
uriPos, uriLen, free, err := capsule.ReserveMemorySpaceFor(uri, wasmModule, ctx)
defer free.Call(ctx, uriPos)

defer free.Call(ctx, headersStrPos)
jsonStrPos, jsonStrLen, free, err := capsule.ReserveMemorySpaceFor(jsonStr, wasmModule, ctx)
defer free.Call(ctx, jsonStrPos)

bytes, err := capsule.ExecHandleFunction(wasmFunction, wasmModule, ctx, jsonStrPos, jsonStrLen, headersStrPos, headersStrLen)
headersStrPos, headersStrLen, free, err := capsule.ReserveMemorySpaceFor(headersStr, wasmModule, ctx)
defer free.Call(ctx, headersStrPos)

if err != nil {
c.String(500, "out of range of memory size")
}
methodPos, methodLen, free, err := capsule.ReserveMemorySpaceFor(method, wasmModule, ctx)
defer free.Call(ctx, methodPos)

bodyStr, headers := GetBodyAndHeaders(bytes, c)
bytes, err := capsule.ExecHandleFunction(wasmFunction, wasmModule, ctx, jsonStrPos, jsonStrLen, uriPos, uriLen, headersStrPos, headersStrLen, methodPos, methodLen)

// check the return value
if commons.IsErrorString(bodyStr) {
SendErrorMessage(bodyStr, headers, c)
} else if IsBodyString(bodyStr) {
SendJsonMessage(bodyStr, headers, c)
} else {
c.String(http.StatusOK, bodyStr)
}
if err != nil {
c.String(500, "out of range of memory size")
}

//c.String(http.StatusOK, bodyStr)
bodyStr, headers := GetBodyAndHeaders(bytes, c)

})
// check the return value
if commons.IsErrorString(bodyStr) {
SendErrorMessage(bodyStr, headers, c)
} else if IsBodyString(bodyStr) {
SendJsonMessage(bodyStr, headers, c)
} else {
c.String(http.StatusOK, bodyStr)
}

if crt != "" {
// certs/procyon-registry.local.crt
// certs/procyon-registry.local.key
fmt.Println("💊 Capsule (", commons.CapsuleVersion(), ") http server is listening on:", httpPort, "🔐🌍")
//c.String(http.StatusOK, bodyStr)

router.RunTLS(":"+httpPort, crt, key)
} else {
fmt.Println("💊 Capsule (", commons.CapsuleVersion(), ") http server is listening on:", httpPort, "🌍")
router.Run(":" + httpPort)
}
})

if crt != "" {
// certs/procyon-registry.local.crt
// certs/procyon-registry.local.key
fmt.Println("💊 Capsule (", commons.CapsuleVersion(), ") http server is listening on:", httpPort, "🔐🌍")

router.RunTLS(":"+httpPort, crt, key)
} else {
fmt.Println("💊 Capsule (", commons.CapsuleVersion(), ") http server is listening on:", httpPort, "🌍")
router.Run(":" + httpPort)
}

}
2 changes: 1 addition & 1 deletion capsule-launcher/services/http/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func GetHeadersStringFromHeadersRequest(c *gin.Context) string {
headersMap[key] = values[0]
}
headersSlice := commons.CreateSliceFromMap(headersMap)
headersParameter := commons.CreateStringFromSlice(headersSlice, "|")
headersParameter := commons.CreateStringFromSlice(headersSlice, commons.StrSeparator)

return headersParameter
}
4 changes: 3 additions & 1 deletion capsulemodule/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ module github.com/bots-garden/capsule/capsulemodule

go 1.18

require github.com/bots-garden/capsule/commons v0.0.0-20220903062354-1c48dd250b77
replace github.com/bots-garden/capsule/commons => ../commons

require github.com/bots-garden/capsule/commons v0.0.0-20220903105536-e833f3d14593
4 changes: 0 additions & 4 deletions capsulemodule/go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +0,0 @@
github.com/bots-garden/capsule/commons v0.0.0-20220821060842-d1dc9f030021 h1:cBeILASaSUdrsImLP6wR6a747SHYBJqIwuADm2BMDO4=
github.com/bots-garden/capsule/commons v0.0.0-20220821060842-d1dc9f030021/go.mod h1:5ctHSZAwy3GEi4tR9YKFTfWtBUXDcOMFHNiJYXbV61c=
github.com/bots-garden/capsule/commons v0.0.0-20220903062354-1c48dd250b77 h1:CyywCzVyAuT7fHf5iHgjx0IqUvEVevtbVMwbSkS2VnA=
github.com/bots-garden/capsule/commons v0.0.0-20220903062354-1c48dd250b77/go.mod h1:5ctHSZAwy3GEi4tR9YKFTfWtBUXDcOMFHNiJYXbV61c=
Loading

0 comments on commit dd90b15

Please sign in to comment.