websocket actions: Refactor registration

This commit is contained in:
Tom Wiesing 2023-11-09 14:58:19 +01:00
parent 08ab7b4383
commit 7b5f8a9882
No known key found for this signature in database
4 changed files with 102 additions and 87 deletions

View file

@ -2,7 +2,6 @@ package socket
import (
"context"
"io"
"net/http"
"github.com/FAU-CDI/wisski-distillery/internal/dis/component"
@ -13,7 +12,7 @@ import (
"github.com/FAU-CDI/wisski-distillery/internal/dis/component/instances/purger"
"github.com/FAU-CDI/wisski-distillery/internal/dis/component/provision"
"github.com/FAU-CDI/wisski-distillery/internal/dis/component/server/admin/socket/actions"
"github.com/FAU-CDI/wisski-distillery/internal/wisski"
"github.com/FAU-CDI/wisski-distillery/internal/dis/component/server/admin/socket/proto"
"github.com/rs/zerolog"
"github.com/tkw1536/pkglib/httpx"
"github.com/tkw1536/pkglib/lazy"
@ -22,7 +21,7 @@ import (
type Sockets struct {
component.Base
actions lazy.Lazy[ActionMap]
actions lazy.Lazy[proto.ActionMap]
dependencies struct {
Actions []actions.WebsocketAction
@ -58,37 +57,8 @@ func (sockets *Sockets) HandleRoute(ctx context.Context, path string) (http.Hand
// Serve handles a connection to the websocket api
func (socket *Sockets) Serve(conn httpx.WebSocketConnection) {
// handle the websocket connection!
name, err := socket.actions.Get(socket.Actions).Handle(socket.dependencies.Auth, conn)
name, err := socket.actions.Get(func() proto.ActionMap { return socket.Actions(conn.Context()) }).Handle(socket.dependencies.Auth, conn)
if err != nil {
zerolog.Ctx(conn.Context()).Err(err).Str("name", name).Msg("Error handling websocket")
}
}
// Generic returns a new action that calls handler with the provided number of parameters
func (sockets *Sockets) Generic(scope component.Scope, scopeParam string, numParams int, handler func(ctx context.Context, socket *Sockets, in io.Reader, out io.Writer, params ...string) error) Action {
return Action{
Scope: scope,
ScopeParam: scopeParam,
NumParams: numParams,
Handle: func(ctx context.Context, in io.Reader, out io.Writer, params ...string) error {
return handler(ctx, sockets, in, out, params...)
},
}
}
// Insstance returns a new action that calls handler with a specific WissKI instance
func (sockets *Sockets) Instance(scope component.Scope, scopeParam string, numParams int, handler func(ctx context.Context, sockets *Sockets, instance *wisski.WissKI, in io.Reader, out io.Writer, params ...string) error) Action {
return Action{
Scope: scope,
ScopeParam: scopeParam,
NumParams: numParams + 1,
Handle: func(ctx context.Context, in io.Reader, out io.Writer, params ...string) error {
instance, err := sockets.dependencies.Instances.WissKI(ctx, params[0])
if err != nil {
return err
}
return handler(ctx, sockets, instance, in, out, params[1:]...)
},
}
}