edge/pkg/module/lifecycle.go

63 lines
1.3 KiB
Go

package module
import (
"context"
"time"
"forge.cadoles.com/arcad/edge/pkg/app"
"github.com/dop251/goja"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/logger"
)
type LifecycleModule struct{}
func (m *LifecycleModule) Name() string {
return "lifecycle"
}
func (m *LifecycleModule) Export(export *goja.Object) {
}
func (m *LifecycleModule) OnInit(ctx context.Context, rt *goja.Runtime) (err error) {
call, ok := goja.AssertFunction(rt.Get("onInit"))
if !ok {
logger.Warn(ctx, "could not find onInit() function")
return nil
}
defer func() {
if recovered := recover(); recovered != nil {
revoveredErr, ok := recovered.(error)
if ok {
logger.Error(ctx, "recovered runtime error", logger.CapturedE(errors.WithStack(revoveredErr)))
err = errors.WithStack(app.ErrUnknownError)
return
}
panic(recovered)
}
}()
logger.Debug(ctx, "executing app onInit() function")
start := time.Now()
call(nil)
duration := time.Since(start)
logger.Debug(ctx, "executed app onInit() function", logger.F("duration", duration.String()))
return nil
}
func LifecycleModuleFactory() app.ServerModuleFactory {
return func(server *app.Server) app.ServerModule {
module := &LifecycleModule{}
return module
}
}
var _ app.InitializableModule = &LifecycleModule{}