120 lines
2.1 KiB
Go
120 lines
2.1 KiB
Go
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"
|
|
"gitlab.com/wpetit/goweb/logger"
|
|
)
|
|
|
|
type LifecycleModule struct {
|
|
server *app.Server
|
|
bus bus.Bus
|
|
}
|
|
|
|
func (m *LifecycleModule) Name() string {
|
|
return "lifecycle"
|
|
}
|
|
|
|
func (m *LifecycleModule) Export(export *goja.Object) {
|
|
}
|
|
|
|
func (m *LifecycleModule) OnInit() error {
|
|
if _, err := m.server.ExecFuncByName("onInit"); err != nil {
|
|
if errors.Is(err, app.ErrFuncDoesNotExist) {
|
|
logger.Warn(context.Background(), "could not find onInit() function", logger.E(errors.WithStack(err)))
|
|
|
|
return errors.WithStack(err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (m *LifecycleModule) handleMessages() {
|
|
ctx := context.Background()
|
|
|
|
logger.Debug(
|
|
ctx,
|
|
"subscribing to bus messages",
|
|
)
|
|
|
|
clientMessages, err := m.bus.Subscribe(ctx, MessageNamespaceClient)
|
|
if err != nil {
|
|
panic(errors.WithStack(err))
|
|
}
|
|
|
|
defer func() {
|
|
logger.Debug(
|
|
ctx,
|
|
"unsubscribing from bus messages",
|
|
)
|
|
|
|
m.bus.Unsubscribe(ctx, MessageNamespaceClient, clientMessages)
|
|
}()
|
|
|
|
for {
|
|
logger.Debug(
|
|
ctx,
|
|
"waiting for next message",
|
|
)
|
|
select {
|
|
case <-ctx.Done():
|
|
logger.Debug(
|
|
ctx,
|
|
"context done",
|
|
)
|
|
|
|
return
|
|
|
|
case msg := <-clientMessages:
|
|
clientMessage, ok := msg.(*ClientMessage)
|
|
if !ok {
|
|
logger.Error(
|
|
ctx,
|
|
"unexpected message type",
|
|
logger.F("message", msg),
|
|
)
|
|
|
|
continue
|
|
}
|
|
|
|
logger.Debug(
|
|
ctx,
|
|
"received client message",
|
|
logger.F("message", clientMessage),
|
|
)
|
|
|
|
if _, err := m.server.ExecFuncByName("onClientMessage", clientMessage.Context, clientMessage.Data); err != nil {
|
|
if errors.Is(err, app.ErrFuncDoesNotExist) {
|
|
continue
|
|
}
|
|
|
|
logger.Error(
|
|
ctx,
|
|
"on client message error",
|
|
logger.E(err),
|
|
)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func LifecycleModuleFactory(bus bus.Bus) app.ServerModuleFactory {
|
|
return func(server *app.Server) app.ServerModule {
|
|
module := &LifecycleModule{
|
|
server: server,
|
|
bus: bus,
|
|
}
|
|
|
|
go module.handleMessages()
|
|
|
|
return module
|
|
}
|
|
}
|
|
|
|
var _ app.InitializableModule = &LifecycleModule{}
|