Skip to content

Commit

Permalink
chore: prefix log level consts, minor package updates (#39)
Browse files Browse the repository at this point in the history
While using the SDK, I found it difficult to use the log level consts
and to assign a log level in the plugin configuration struct.

This changes the *LogLevel field to use a non-pointer type, and updates
the code accordingly. I think this is ok, since we've define the `iota`
0 value to a `Off` constant. This will be the default / zero-value of
the type when left unset in a struct.

Also, I have prefixed these log level const names with `LogLevel` -- I
think it makes it more clear when looking at the name, e.g.
`extism.LogLevelInfo` vs. `extism.Info`

Additionally, although unrelated, this PR includes a couple minor
changes to use non-deprecated functions from `io` & `os` packages vs.
`ioutil`.

---------

Co-authored-by: Muhammad Azeez <muhammad@dylibso.com>
  • Loading branch information
nilslice and mhmd-azeez committed Nov 19, 2023
1 parent 05fa848 commit c4e57ce
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 48 deletions.
41 changes: 21 additions & 20 deletions extism.go
Expand Up @@ -7,9 +7,10 @@ import (
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
"os"
"time"

"github.com/tetratelabs/wazero"
Expand All @@ -35,8 +36,7 @@ type PluginConfig struct {
ModuleConfig wazero.ModuleConfig
RuntimeConfig wazero.RuntimeConfig
EnableWasi bool
// TODO: couldn't find a better way for this, but I wonder if there is a better and more idomatic way for Option<T>
LogLevel *LogLevel
LogLevel LogLevel
}

// HttpRequest represents an HTTP request to be made by the plugin.
Expand All @@ -50,26 +50,27 @@ type HttpRequest struct {
type LogLevel uint8

const (
Off LogLevel = iota
Error
Warn
Info
Debug
Trace
logLevelUnset LogLevel = iota // unexporting this intentionally so its only ever the default
LogLevelOff
LogLevelError
LogLevelWarn
LogLevelInfo
LogLevelDebug
LogLevelTrace
)

func (l LogLevel) String() string {
s := ""
switch l {
case Error:
case LogLevelError:
s = "ERROR"
case Warn:
case LogLevelWarn:
s = "WARN"
case Info:
case LogLevelInfo:
s = "INFO"
case Debug:
case LogLevelDebug:
s = "DEBUG"
case Trace:
case LogLevelTrace:
s = "TRACE"
}
return s
Expand Down Expand Up @@ -156,7 +157,7 @@ func (f WasmFile) ToWasmData(ctx context.Context) (WasmData, error) {
case <-ctx.Done():
return WasmData{}, ctx.Err()
default:
data, err := ioutil.ReadFile(f.Path)
data, err := os.ReadFile(f.Path)
if err != nil {
return WasmData{}, err
}
Expand Down Expand Up @@ -191,7 +192,7 @@ func (u WasmUrl) ToWasmData(ctx context.Context) (WasmData, error) {
return WasmData{}, errors.New("failed to fetch Wasm data from URL")
}

data, err := ioutil.ReadAll(resp.Body)
data, err := io.ReadAll(resp.Body)
if err != nil {
return WasmData{}, err
}
Expand Down Expand Up @@ -338,9 +339,9 @@ func NewPlugin(
// - If there is only one module in the manifest then that is the main module by default
// - Otherwise the last module listed is the main module

logLevel := Warn
if config.LogLevel != nil {
logLevel = *config.LogLevel
logLevel := LogLevelWarn
if config.LogLevel != logLevelUnset {
logLevel = config.LogLevel
}

i := 0
Expand Down Expand Up @@ -472,7 +473,7 @@ func (plugin *Plugin) Call(name string, data []byte) (uint32, []byte, error) {
plugin.guestRuntime.initialized = true
}

plugin.Logf(Debug, "Calling function : %v", name)
plugin.Logf(LogLevelDebug, "Calling function : %v", name)

res, err := f.Call(ctx)

Expand Down
20 changes: 9 additions & 11 deletions extism_test.go
Expand Up @@ -263,7 +263,7 @@ func TestHost_memory(t *testing.T) {
}

result := bytes.ToUpper(buffer)
plugin.Logf(Debug, "Result: %s", result)
plugin.Logf(LogLevelDebug, "Result: %s", result)

plugin.Free(offset)

Expand Down Expand Up @@ -467,24 +467,24 @@ func TestLog_custom(t *testing.T) {
plugin.SetLogger(func(level LogLevel, message string) {
actual = append(actual, LogEntry{message: message, level: level})
switch level {
case Info:
case LogLevelInfo:
assert.Equal(t, fmt.Sprintf("%s", level), "INFO")
case Warn:
case LogLevelWarn:
assert.Equal(t, fmt.Sprintf("%s", level), "WARN")
case Error:
case LogLevelError:
assert.Equal(t, fmt.Sprintf("%s", level), "ERROR")
}
})

plugin.SetLogLevel(Info)
plugin.SetLogLevel(LogLevelInfo)

exit, _, err := plugin.Call("run_test", []byte{})

if assertCall(t, err, exit) {
expected := []LogEntry{
{message: "this is an info log", level: Info},
{message: "this is a warning log", level: Warn},
{message: "this is an erorr log", level: Error}}
{message: "this is an info log", level: LogLevelInfo},
{message: "this is a warning log", level: LogLevelWarn},
{message: "this is an erorr log", level: LogLevelError}}

assert.Equal(t, expected, actual)
}
Expand Down Expand Up @@ -649,7 +649,7 @@ func TestHelloHaskell(t *testing.T) {
if plugin, ok := plugin(t, manifest); ok {
defer plugin.Close()

plugin.SetLogLevel(Trace)
plugin.SetLogLevel(LogLevelTrace)
plugin.Config["greeting"] = "Howdy"

exit, output, err := plugin.Call("testing", []byte("John"))
Expand Down Expand Up @@ -791,11 +791,9 @@ func generateRandomString(length int, seed int64) string {
}

func wasiPluginConfig() PluginConfig {
level := Warn
config := PluginConfig{
ModuleConfig: wazero.NewModuleConfig().WithSysWalltime(),
EnableWasi: true,
LogLevel: &level,
}
return config
}
Expand Down
11 changes: 5 additions & 6 deletions host.go
Expand Up @@ -6,7 +6,6 @@ import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"

Expand Down Expand Up @@ -295,10 +294,10 @@ func buildEnvModule(ctx context.Context, rt wazero.Runtime, extism api.Module) (
})
}

logFunc("log_debug", Debug)
logFunc("log_info", Info)
logFunc("log_warn", Warn)
logFunc("log_error", Error)
logFunc("log_debug", LogLevelDebug)
logFunc("log_info", LogLevelInfo)
logFunc("log_warn", LogLevelWarn)
logFunc("log_error", LogLevelError)

return builder.Instantiate(ctx)
}
Expand Down Expand Up @@ -502,7 +501,7 @@ func httpRequest(ctx context.Context, m api.Module, requestOffset uint64, bodyOf
// TODO: make this limit configurable
// TODO: the rust implementation silently truncates the response body, should we keep the behavior here?
limiter := http.MaxBytesReader(nil, resp.Body, 1024*1024*50)
body, err := ioutil.ReadAll(limiter)
body, err := io.ReadAll(limiter)
if err != nil {
panic(err)
}
Expand Down
22 changes: 11 additions & 11 deletions runtime.go
Expand Up @@ -33,7 +33,7 @@ func detectGuestRuntime(p *Plugin) guestRuntime {
return runtime
}

p.Log(Trace, "No runtime detected")
p.Log(LogLevelTrace, "No runtime detected")
return guestRuntime{runtimeType: None, init: func() error { return nil }, initialized: true}
}

Expand All @@ -49,7 +49,7 @@ func haskellRuntime(p *Plugin, m api.Module) (guestRuntime, bool) {
params := initFunc.Definition().ParamTypes()

if len(params) != 2 || params[0] != api.ValueTypeI32 || params[1] != api.ValueTypeI32 {
p.Logf(Trace, "hs_init function found with type %v", params)
p.Logf(LogLevelTrace, "hs_init function found with type %v", params)
}

reactorInit := m.ExportedFunction("_initialize")
Expand All @@ -58,18 +58,18 @@ func haskellRuntime(p *Plugin, m api.Module) (guestRuntime, bool) {
if reactorInit != nil {
_, err := reactorInit.Call(p.Runtime.ctx)
if err != nil {
p.Logf(Error, "Error running reactor _initialize: %s", err.Error())
p.Logf(LogLevelError, "Error running reactor _initialize: %s", err.Error())
}
}
_, err := initFunc.Call(p.Runtime.ctx, 0, 0)
if err == nil {
p.Log(Debug, "Initialized Haskell language runtime.")
p.Log(LogLevelDebug, "Initialized Haskell language runtime.")
}

return err
}

p.Log(Trace, "Haskell runtime detected")
p.Log(LogLevelTrace, "Haskell runtime detected")
return guestRuntime{runtimeType: Haskell, init: init}, true
}

Expand All @@ -96,8 +96,8 @@ func reactorModule(m api.Module, p *Plugin) (guestRuntime, bool) {
return guestRuntime{}, false
}

p.Logf(Trace, "WASI runtime detected")
p.Logf(Trace, "Reactor module detected")
p.Logf(LogLevelTrace, "WASI runtime detected")
p.Logf(LogLevelTrace, "Reactor module detected")

return guestRuntime{runtimeType: Wasi, init: init}, true
}
Expand All @@ -110,8 +110,8 @@ func commandModule(m api.Module, p *Plugin) (guestRuntime, bool) {
return guestRuntime{}, false
}

p.Logf(Trace, "WASI runtime detected")
p.Logf(Trace, "Command module detected")
p.Logf(LogLevelTrace, "WASI runtime detected")
p.Logf(LogLevelTrace, "Command module detected")

return guestRuntime{runtimeType: Wasi, init: init}, true
}
Expand All @@ -124,12 +124,12 @@ func findFunc(m api.Module, p *Plugin, name string) func() error {

params := initFunc.Definition().ParamTypes()
if len(params) != 0 {
p.Logf(Trace, "%v function found with type %v", name, params)
p.Logf(LogLevelTrace, "%v function found with type %v", name, params)
return nil
}

return func() error {
p.Logf(Debug, "Calling %v", name)
p.Logf(LogLevelDebug, "Calling %v", name)
_, err := initFunc.Call(p.Runtime.ctx)
return err
}
Expand Down

0 comments on commit c4e57ce

Please sign in to comment.