package module import ( "context" "forge.cadoles.com/arcad/edge/pkg/app" "forge.cadoles.com/arcad/edge/pkg/bus" "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 { ctx = assertContext(firstArg, rt) } 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, } } }