2023-02-09 12:16:36 +01:00
|
|
|
package module
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"forge.cadoles.com/arcad/edge/pkg/app"
|
|
|
|
"forge.cadoles.com/arcad/edge/pkg/bus"
|
2023-02-21 12:14:29 +01:00
|
|
|
"forge.cadoles.com/arcad/edge/pkg/module/util"
|
2023-02-09 12:16:36 +01:00
|
|
|
"github.com/dop251/goja"
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
)
|
|
|
|
|
|
|
|
type NetModule struct {
|
|
|
|
server *app.Server
|
|
|
|
bus bus.Bus
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *NetModule) Name() string {
|
|
|
|
return "net"
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *NetModule) Export(export *goja.Object) {
|
|
|
|
if err := export.Set("broadcast", m.broadcast); err != nil {
|
|
|
|
panic(errors.Wrap(err, "could not set 'broadcast' function"))
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := export.Set("send", m.send); err != nil {
|
|
|
|
panic(errors.Wrap(err, "could not set 'send' function"))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *NetModule) broadcast(call goja.FunctionCall) goja.Value {
|
|
|
|
if len(call.Arguments) < 1 {
|
|
|
|
panic(m.server.ToValue("invalid number of argument"))
|
|
|
|
}
|
|
|
|
|
|
|
|
data := call.Argument(0).Export()
|
|
|
|
|
|
|
|
msg := NewServerMessage(nil, data)
|
|
|
|
if err := m.bus.Publish(context.Background(), msg); err != nil {
|
|
|
|
panic(errors.WithStack(err))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *NetModule) send(call goja.FunctionCall, rt *goja.Runtime) goja.Value {
|
|
|
|
if len(call.Arguments) < 2 {
|
|
|
|
panic(m.server.ToValue("invalid number of argument"))
|
|
|
|
}
|
|
|
|
|
|
|
|
var ctx context.Context
|
|
|
|
|
|
|
|
firstArg := call.Argument(0)
|
|
|
|
|
|
|
|
sessionID, ok := firstArg.Export().(string)
|
|
|
|
if ok {
|
|
|
|
ctx = WithContext(context.Background(), map[ContextKey]any{
|
|
|
|
ContextKeySessionID: sessionID,
|
|
|
|
})
|
|
|
|
} else {
|
2023-02-21 12:14:29 +01:00
|
|
|
ctx = util.AssertContext(firstArg, rt)
|
2023-02-09 12:16:36 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
data := call.Argument(1).Export()
|
|
|
|
|
|
|
|
msg := NewServerMessage(ctx, data)
|
|
|
|
if err := m.bus.Publish(ctx, msg); err != nil {
|
|
|
|
panic(errors.WithStack(err))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func NetModuleFactory(bus bus.Bus) app.ServerModuleFactory {
|
|
|
|
return func(server *app.Server) app.ServerModule {
|
|
|
|
return &NetModule{
|
|
|
|
server: server,
|
|
|
|
bus: bus,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|