Skip to content

Commit

Permalink
Refactoring and bug fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
sesposito committed Mar 7, 2023
1 parent e1d5d98 commit b063315
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 55 deletions.
27 changes: 13 additions & 14 deletions internal/satori/satori.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func (s *SatoriClient) Authenticate(ctx context.Context, id string) error {
case 200:
return nil
default:
return fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand All @@ -155,19 +155,19 @@ func (s *SatoriClient) PropertiesList(ctx context.Context, id string) (*runtime.

switch res.StatusCode {
case 200:
var props runtime.Properties
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

var props runtime.Properties
if err = json.Unmarshal(resBody, &props); err != nil {
return nil, err
}

return &props, nil
default:
return nil, fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return nil, fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand Down Expand Up @@ -200,7 +200,7 @@ func (s *SatoriClient) PropertiesUpdate(ctx context.Context, id string, properti
case 200:
return nil
default:
return fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand Down Expand Up @@ -238,7 +238,7 @@ func (s *SatoriClient) EventsPublish(ctx context.Context, id string, events []*r
return err
}

req, err := http.NewRequestWithContext(ctx, "PUT", url, bytes.NewReader(json))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(json))
if err != nil {
return err
}
Expand All @@ -254,7 +254,7 @@ func (s *SatoriClient) EventsPublish(ctx context.Context, id string, events []*r
case 200:
return nil
default:
return fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand Down Expand Up @@ -287,19 +287,19 @@ func (s *SatoriClient) ExperimentsList(ctx context.Context, id string, names ...

switch res.StatusCode {
case 200:
var experiments runtime.ExperimentList
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

var experiments runtime.ExperimentList
if err = json.Unmarshal(resBody, &experiments); err != nil {
return nil, err
}

return &experiments, nil
default:
return nil, fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return nil, fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand All @@ -320,7 +320,7 @@ func (s *SatoriClient) FlagsList(ctx context.Context, id string, names ...string
if len(names) > 0 {
q := req.URL.Query()
for _, n := range names {
q.Set("names", n)
q.Add("names", n)
}
req.URL.RawQuery = q.Encode()
}
Expand All @@ -332,19 +332,19 @@ func (s *SatoriClient) FlagsList(ctx context.Context, id string, names ...string

switch res.StatusCode {
case 200:
var flags runtime.FlagList
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

var flags runtime.FlagList
if err = json.Unmarshal(resBody, &flags); err != nil {
return nil, err
}

return &flags, nil
default:
return nil, fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return nil, fmt.Errorf("%d status code", res.StatusCode)
}
}

Expand Down Expand Up @@ -377,18 +377,17 @@ func (s *SatoriClient) LiveEventsList(ctx context.Context, id string, names ...s

switch res.StatusCode {
case 200:
var liveEvents runtime.LiveEventList
resBody, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}

var liveEvents runtime.LiveEventList
if err = json.Unmarshal(resBody, &liveEvents); err != nil {
return nil, err
}

return &liveEvents, nil
default:
return nil, fmt.Errorf("Non-200 status code: %d", res.StatusCode)
return nil, fmt.Errorf("%d status code", res.StatusCode)
}
}
13 changes: 5 additions & 8 deletions server/runtime_javascript.go
Original file line number Diff line number Diff line change
Expand Up @@ -1667,16 +1667,15 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, protojs
}

nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, statusRegistry, matchRegistry, tracker, metrics, streamManager, router, eventFn, matchProvider.CreateMatch)
nk := runtime.ToValue(nakamaModule.Constructor(runtime))
nkInst, err := runtime.New(nk)
nk, err := nakamaModule.Constructor(runtime)
if err != nil {
logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err))
}

return &RuntimeJS{
logger: logger,
jsLoggerInst: jsLoggerInst,
nkInst: nkInst,
nkInst: nk,
node: config.GetName(),
version: version,
vm: runtime,
Expand Down Expand Up @@ -2260,8 +2259,7 @@ func evalRuntimeModules(rp *RuntimeProviderJS, modCache *RuntimeJSModuleCache, m
modName := modCache.Names[0]

initializer := NewRuntimeJavascriptInitModule(logger, modCache.Modules[modName].Ast, callbacks, matchHandlers, announceCallbackFn)
initializerValue := r.ToValue(initializer.Constructor(r))
initializerInst, err := r.New(initializerValue)
init, err := initializer.Constructor(r)
if err != nil {
return nil, err
}
Expand All @@ -2272,8 +2270,7 @@ func evalRuntimeModules(rp *RuntimeProviderJS, modCache *RuntimeJSModuleCache, m
}

nakamaModule := NewRuntimeJavascriptNakamaModule(rp.logger, rp.db, rp.protojsonMarshaler, rp.protojsonUnmarshaler, rp.config, rp.socialClient, rp.leaderboardCache, rp.leaderboardRankCache, localCache, leaderboardScheduler, rp.sessionRegistry, rp.sessionCache, rp.statusRegistry, rp.matchRegistry, rp.tracker, rp.metrics, rp.streamManager, rp.router, rp.eventFn, matchProvider.CreateMatch)
nk := r.ToValue(nakamaModule.Constructor(r))
nkInst, err := r.New(nk)
nk, err := nakamaModule.Constructor(r)
if err != nil {
return nil, err
}
Expand All @@ -2297,7 +2294,7 @@ func evalRuntimeModules(rp *RuntimeProviderJS, modCache *RuntimeJSModuleCache, m

// Execute init module function
ctx := NewRuntimeJsInitContext(r, rp.config.GetName(), rp.version, rp.config.GetRuntime().Environment)
_, err = initModFn(goja.Null(), ctx, jsLoggerInst, nkInst, initializerInst)
_, err = initModFn(goja.Null(), ctx, jsLoggerInst, nk, init)
if err != nil {
if exErr, ok := err.(*goja.Exception); ok {
return nil, errors.New(exErr.String())
Expand Down
6 changes: 4 additions & 2 deletions server/runtime_javascript_init.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,16 @@ func (im *RuntimeJavascriptInitModule) mappings(r *goja.Runtime) map[string]func
}
}

func (im *RuntimeJavascriptInitModule) Constructor(r *goja.Runtime) func(goja.ConstructorCall) *goja.Object {
return func(call goja.ConstructorCall) *goja.Object {
func (im *RuntimeJavascriptInitModule) Constructor(r *goja.Runtime) (*goja.Object, error) {
constructor := func(call goja.ConstructorCall) *goja.Object {
for key, fn := range im.mappings(r) {
call.This.Set(key, fn)
}

return nil
}

return r.New(r.ToValue(constructor))
}

func (im *RuntimeJavascriptInitModule) registerRpc(r *goja.Runtime) func(goja.FunctionCall) goja.Value {
Expand Down
8 changes: 5 additions & 3 deletions server/runtime_javascript_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@ type jsLogger struct {

func NewJsLogger(r *goja.Runtime, logger *zap.Logger, fields ...zap.Field) (goja.Value, error) {
l := &jsLogger{logger: logger.With(fields...)}
jsl, err := r.New(r.ToValue(l.Constructor(r)))
jsl, err := l.Constructor(r)
if err != nil {
return nil, err
}
return jsl, nil
}

func (l *jsLogger) Constructor(r *goja.Runtime) func(goja.ConstructorCall) *goja.Object {
func (l *jsLogger) Constructor(r *goja.Runtime) (*goja.Object, error) {
getArgs := func(values []goja.Value) (string, []interface{}, error) {
format, ok := values[0].Export().(string)
if !ok {
Expand All @@ -56,7 +56,7 @@ func (l *jsLogger) Constructor(r *goja.Runtime) func(goja.ConstructorCall) *goja
return zFields
}

return func(call goja.ConstructorCall) *goja.Object {
constructor := func(call goja.ConstructorCall) *goja.Object {
var argFields goja.Value
if len(call.Arguments) > 0 {
argFields = call.Arguments[0]
Expand Down Expand Up @@ -154,6 +154,8 @@ func (l *jsLogger) Constructor(r *goja.Runtime) func(goja.ConstructorCall) *goja

return nil
}

return r.New(r.ToValue(constructor))
}

// Disallows resetting or changing the properties of the object
Expand Down
5 changes: 2 additions & 3 deletions server/runtime_javascript_match_core.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB
}

nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, rankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, statusRegistry, matchRegistry, tracker, metrics, streamManager, router, eventFn, matchCreateFn)
nk := runtime.ToValue(nakamaModule.Constructor(runtime))
nkInst, err := runtime.New(nk)
nk, err := nakamaModule.Constructor(runtime)
if err != nil {
logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err))
}
Expand Down Expand Up @@ -165,7 +164,7 @@ func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB
ctx: ctx,

loggerModule: jsLoggerInst,
nakamaModule: nkInst,
nakamaModule: nk,
ctxCancelFn: ctxCancelFn,
}

Expand Down
50 changes: 26 additions & 24 deletions server/runtime_javascript_nakama.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,8 @@ func NewRuntimeJavascriptNakamaModule(logger *zap.Logger, db *sql.DB, protojsonM
}
}

func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(call goja.ConstructorCall) *goja.Object {
return func(call goja.ConstructorCall) *goja.Object {
func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) (*goja.Object, error) {
constructor := func(call goja.ConstructorCall) *goja.Object {
call.This.Set("authenticate", func(f goja.FunctionCall) goja.Value {
id := getJsString(r, f.Argument(0))

Expand All @@ -128,7 +128,7 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(
return nil
})

call.This.Set("listProperties", func(f goja.FunctionCall) goja.Value {
call.This.Set("propertiesList", func(f goja.FunctionCall) goja.Value {
id := getJsString(r, f.Argument(0))

props, err := n.satori.PropertiesList(n.ctx, id)
Expand All @@ -155,18 +155,12 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(
properties := &runtime.PropertiesUpdate{}
defProps, ok := props["default"]
if ok {
defPropsMap, ok := defProps.(map[string]string)
if !ok {
panic(r.NewTypeError("expects default properties to be an object with string values and keys"))
}
defPropsMap := getJsStringMap(r, r.ToValue(defProps))
properties.Default = defPropsMap
}
customProps, ok := props["custom"]
if ok {
customPropsMap, ok := customProps.(map[string]string)
if !ok {
panic(r.NewTypeError("expects custom properties to be an object with string values and keys"))
}
customPropsMap := getJsStringMap(r, r.ToValue(customProps))
properties.Custom = customPropsMap
}

Expand Down Expand Up @@ -214,15 +208,15 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(

metadata, ok := eMap["metadata"]
if ok {
metadataMap, ok := metadata.(map[string]string)
metadataMap := getJsStringMap(r, r.ToValue(metadata))
if !ok {
panic(r.NewTypeError("expects event metadata to be an object with string keys and values"))
}
evt.Metadata = metadataMap
}

value, ok := eMap["value"]
if !ok {
if ok {
valueStr, ok := value.(string)
if !ok {
panic(r.NewTypeError("expects event value to be a string"))
Expand All @@ -231,13 +225,15 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(
}

ts, ok := eMap["timestamp"]
if !ok {
tsInt, ok := ts.(int)
if ok {
tsInt, ok := ts.(int64)
if !ok {
panic(r.NewTypeError("expects event timestamp to be a number"))
}
evt.Timestamp = int64(tsInt)
evt.Timestamp = tsInt
}

evts = append(evts, evt)
}

if err := n.satori.EventsPublish(n.ctx, identifier, evts); err != nil {
Expand Down Expand Up @@ -370,24 +366,30 @@ func (n *runtimeJavascriptNakamaModule) satoriConstructor(r *goja.Runtime) func(

return nil
}

return r.New(r.ToValue(constructor))
}

func (n *runtimeJavascriptNakamaModule) Constructor(r *goja.Runtime) func(goja.ConstructorCall) *goja.Object {
return func(call goja.ConstructorCall) *goja.Object {
func (n *runtimeJavascriptNakamaModule) Constructor(r *goja.Runtime) (*goja.Object, error) {
satoriJsObj, err := n.satoriConstructor(r)
if err != nil {
return nil, err
}

constructor := func(call goja.ConstructorCall) *goja.Object {
for fnName, fn := range n.mappings(r) {
call.This.Set(fnName, fn)
}

satoriJsObj, _ := r.New(r.ToValue(n.satoriConstructor(r)))
// TODO: refactor to avoid this error voiding

// TODO: Add function docs
call.This.Set("getSatori", satoriJsObj)

freeze(call.This)
call.This.Set("getSatori", func(f goja.FunctionCall) goja.Value {
return satoriJsObj
})

return nil
}

return r.New(r.ToValue(constructor))
}

func (n *runtimeJavascriptNakamaModule) mappings(r *goja.Runtime) map[string]func(goja.FunctionCall) goja.Value {
Expand Down

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

0 comments on commit b063315

Please sign in to comment.