mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-29 06:15:31 +00:00
Compare commits
49 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b6c1c5c600 | ||
|
|
b6ec615e40 | ||
|
|
216775c9c6 | ||
|
|
1bfee2186b | ||
|
|
fa612231fb | ||
|
|
c1161c5aa9 | ||
|
|
b1076ce1e4 | ||
|
|
7f5204aca0 | ||
|
|
f3d87e92f8 | ||
|
|
e50e269697 | ||
|
|
ca6aebadef | ||
|
|
818ddc18f4 | ||
|
|
3e7b245536 | ||
|
|
e996d84234 | ||
|
|
04c8ebbe06 | ||
|
|
0f57e123ce | ||
|
|
82ba1d5d10 | ||
|
|
20c53e4996 | ||
|
|
8132faaba6 | ||
|
|
5a0f21bd64 | ||
|
|
fd0f78733c | ||
|
|
65476d5ecc | ||
|
|
536bc2af4e | ||
|
|
b89d907759 | ||
|
|
a3c48de2ad | ||
|
|
8ca9d9940f | ||
|
|
53d0648774 | ||
|
|
cf2881e5c3 | ||
|
|
f437438dca | ||
|
|
6b3c470534 | ||
|
|
3bdff5309f | ||
|
|
3792d40bb1 | ||
|
|
0cca2e3be9 | ||
|
|
5447781232 | ||
|
|
c760b220c0 | ||
|
|
cb71b5c5b8 | ||
|
|
84fd7c1028 | ||
|
|
7bdf6e01b3 | ||
|
|
1b607f64cd | ||
|
|
28e9141cbc | ||
|
|
3b38110ffb | ||
|
|
25e8563cd1 | ||
|
|
80969ac1ff | ||
|
|
beb3664e3b | ||
|
|
6e53cbe8fd | ||
|
|
4ebaa48f93 | ||
|
|
79d535c283 | ||
|
|
85349f8540 | ||
|
|
e49900a3a7 |
6
.github/dependabot.yml
vendored
6
.github/dependabot.yml
vendored
@@ -1,9 +1,9 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
interval: "weekly"
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
|
||||
14
.github/labeler.yml
vendored
14
.github/labeler.yml
vendored
@@ -1,27 +1,27 @@
|
||||
config:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/config/**'
|
||||
- any-glob-to-any-file: "internal/config/**"
|
||||
|
||||
framer:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/framer/**'
|
||||
- any-glob-to-any-file: "internal/framer/**"
|
||||
|
||||
module:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/module/**'
|
||||
- any-glob-to-any-file: "internal/module/**"
|
||||
|
||||
processor:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/processor/**'
|
||||
- any-glob-to-any-file: "internal/processor/**"
|
||||
|
||||
router:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'router*'
|
||||
- any-glob-to-any-file: "router*"
|
||||
|
||||
route:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/route/**'
|
||||
- any-glob-to-any-file: "internal/route/**"
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cmd/showbridge/**'
|
||||
- any-glob-to-any-file: "cmd/showbridge/**"
|
||||
|
||||
2
.github/release.yml
vendored
2
.github/release.yml
vendored
@@ -26,4 +26,4 @@ changelog:
|
||||
- cli
|
||||
- title: Other Changes
|
||||
labels:
|
||||
- '*'
|
||||
- "*"
|
||||
|
||||
12
.github/workflows/release-showbridge.yaml
vendored
12
.github/workflows/release-showbridge.yaml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: release
|
||||
uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
@@ -37,26 +37,26 @@ jobs:
|
||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Setup Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0
|
||||
with:
|
||||
images: |
|
||||
jwetzell/showbridge
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
|
||||
14
.github/workflows/test-showbridge.yaml
vendored
14
.github/workflows/test-showbridge.yaml
vendored
@@ -5,16 +5,16 @@ on:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- "**/*.go"
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- 'go.mod'
|
||||
- 'go.sum'
|
||||
- "**/*.go"
|
||||
- "go.mod"
|
||||
- "go.sum"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
|
||||
31
.vscode/launch.json
vendored
31
.vscode/launch.json
vendored
@@ -1,18 +1,17 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
|
||||
{
|
||||
"name": "Launch showbridge",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "cmd/showbridge",
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch showbridge",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "cmd/showbridge",
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
# showbridge (go edition)
|
||||
|
||||
[](https://raw.githack.com/wiki/jwetzell/showbridge-go/coverage.html)
|
||||
|
||||
Simple protocol router _/s_
|
||||
|
||||
</div>
|
||||
@@ -14,6 +13,7 @@ Simple protocol router _/s_
|
||||
</p>
|
||||
|
||||
### Supported Protocols
|
||||
|
||||
- HTTP
|
||||
- UDP
|
||||
- TCP
|
||||
|
||||
146
api.go
Normal file
146
api.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
func (r *Router) startAPIServer(config config.ApiConfig) {
|
||||
r.logger.Debug("starting API server", "port", config.Port)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/ws", r.handleWebsocket)
|
||||
mux.HandleFunc("/health", r.handleHealthHTTP)
|
||||
mux.HandleFunc("/schema/{schema}", r.handleSchemaHTTP)
|
||||
mux.HandleFunc("/api/v1/config", r.handleConfigHTTP)
|
||||
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
r.apiServer = &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", config.Port),
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
r.apiServer.ListenAndServe()
|
||||
r.apiServerShutdown()
|
||||
}()
|
||||
}
|
||||
|
||||
func (r *Router) stopAPIServer() {
|
||||
r.logger.Debug("stopping API server")
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
if r.apiServer != nil {
|
||||
apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
r.apiServerShutdown = apiShutdownCancel
|
||||
r.apiServer.Shutdown(apiShutdownCtx)
|
||||
<-apiShutdownCtx.Done()
|
||||
r.apiServer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleHealthHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleConfigHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
configJSON, err := json.Marshal(r.runningConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(configJSON)
|
||||
case http.MethodPut:
|
||||
var newConfig config.Config
|
||||
err := json.NewDecoder(req.Body).Decode(&newConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
moduleErrors, routeErrors := r.UpdateConfig(newConfig)
|
||||
if len(moduleErrors) > 0 || len(routeErrors) > 0 {
|
||||
errorResponse := struct {
|
||||
ModuleErrors []module.ModuleError `json:"moduleErrors,omitempty"`
|
||||
RouteErrors []route.RouteError `json:"routeErrors,omitempty"`
|
||||
}{
|
||||
ModuleErrors: moduleErrors,
|
||||
RouteErrors: routeErrors,
|
||||
}
|
||||
errorResponseJSON, err := json.Marshal(errorResponse)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write(errorResponseJSON)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
r.ConfigChange <- newConfig
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//go:embed schema
|
||||
var schema embed.FS
|
||||
|
||||
func (r *Router) handleSchemaHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaName := req.PathValue("schema")
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
configSchema, err := schema.ReadFile(fmt.Sprintf("schema/%s.schema.json", schemaName))
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(configSchema)
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ builds:
|
||||
- "amd64"
|
||||
- "arm64"
|
||||
ldflags:
|
||||
- '-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}'
|
||||
- "-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
- formats: [tar.gz]
|
||||
|
||||
@@ -13,12 +13,14 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/urfave/cli/v3"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp"
|
||||
"go.opentelemetry.io/otel/sdk/resource"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.39.0"
|
||||
semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
@@ -109,6 +111,20 @@ func readConfig(configPath string) (config.Config, error) {
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func writeConfig(configPath string, newConfig config.Config) error {
|
||||
configBytes, err := yaml.Marshal(newConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(configPath, configBytes, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
@@ -173,7 +189,19 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
routerRunner: &sync.WaitGroup{},
|
||||
}
|
||||
|
||||
router, err := showbridgeApp.getNewRouter()
|
||||
config, err := readConfig(showbridgeApp.configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
showbridgeApp.logConfigErrors(moduleErrors, routeErrors)
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize router: %w", err)
|
||||
}
|
||||
@@ -185,7 +213,7 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
})
|
||||
showbridgeApp.routerMutex.Unlock()
|
||||
|
||||
go showbridgeApp.handleHangup()
|
||||
go showbridgeApp.handleChannels()
|
||||
|
||||
<-showbridgeApp.ctx.Done()
|
||||
showbridgeApp.logger.Debug("shutting down router")
|
||||
@@ -195,40 +223,37 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) handleHangup() {
|
||||
func (app *showbridgeApp) handleChannels() {
|
||||
for {
|
||||
select {
|
||||
case <-sigHangup:
|
||||
app.logger.Info("received SIGHUP, reloading configuration")
|
||||
newRouter, err := app.getNewRouter()
|
||||
app.routerMutex.Lock()
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to reload configuration", "error", err)
|
||||
app.logger.Error("failed to read config file", "error", err)
|
||||
app.routerMutex.Unlock()
|
||||
continue
|
||||
}
|
||||
app.routerMutex.Lock()
|
||||
app.router.Stop()
|
||||
app.routerRunner.Wait()
|
||||
app.router = newRouter
|
||||
app.routerRunner.Go(func() {
|
||||
app.router.Start(context.Background())
|
||||
})
|
||||
moduleErrors, routeErrors := app.router.UpdateConfig(config)
|
||||
app.logConfigErrors(moduleErrors, routeErrors)
|
||||
app.logger.Info("configuration reloaded successfully")
|
||||
app.routerMutex.Unlock()
|
||||
case config := <-app.router.ConfigChange:
|
||||
app.logger.Info("router config changed updating config file")
|
||||
err := writeConfig(app.configPath, config)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to write config file", "error", err)
|
||||
continue
|
||||
}
|
||||
app.logger.Info("config file updated successfully")
|
||||
case <-app.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) getNewRouter() (*showbridge.Router, error) {
|
||||
// TODO(jwetzell): what should happen when the config file is unchanged?
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
func (app *showbridgeApp) logConfigErrors(moduleErrors []module.ModuleError, routeErrors []route.RouteError) {
|
||||
for _, moduleError := range moduleErrors {
|
||||
app.logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
@@ -236,12 +261,6 @@ func (app *showbridgeApp) getNewRouter() (*showbridge.Router, error) {
|
||||
for _, routeError := range routeErrors {
|
||||
app.logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return nil, fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
return router, nil
|
||||
}
|
||||
|
||||
func newTracerProvider(exp sdktrace.SpanExporter) *sdktrace.TracerProvider {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
api:
|
||||
port: 8080
|
||||
modules:
|
||||
- id: http
|
||||
type: http.server
|
||||
|
||||
64
events.go
Normal file
64
events.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (e Event) toJSON() ([]byte, error) {
|
||||
return json.Marshal(e)
|
||||
}
|
||||
|
||||
func (r *Router) handleEvent(event Event, sender *websocket.Conn) {
|
||||
switch event.Type {
|
||||
case "ping":
|
||||
r.unicastEvent(Event{Type: "pong"}, sender)
|
||||
default:
|
||||
r.logger.Warn("unknown event type", "eventType", event.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) unicastEvent(event Event, conn *websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
err = conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) broadcastEvent(event Event, excluded ...*websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
r.wsConnsMu.Lock()
|
||||
defer r.wsConnsMu.Unlock()
|
||||
for _, conn := range r.wsConns {
|
||||
exclude := false
|
||||
for _, excludedConn := range excluded {
|
||||
if conn == excludedConn {
|
||||
exclude = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if exclude {
|
||||
continue
|
||||
}
|
||||
err := conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
32
go.mod
32
go.mod
@@ -5,28 +5,29 @@ go 1.26.0
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/emiago/diago v0.27.0
|
||||
github.com/emiago/sipgo v1.2.0
|
||||
github.com/emiago/sipgo v1.2.1
|
||||
github.com/expr-lang/expr v1.17.8
|
||||
github.com/extism/go-sdk v1.7.1
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jwetzell/artnet-go v0.2.1
|
||||
github.com/jwetzell/free-d-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.2.0
|
||||
github.com/jwetzell/psn-go v0.3.0
|
||||
github.com/nats-io/nats-server/v2 v2.12.4
|
||||
github.com/nats-io/nats-server/v2 v2.12.5
|
||||
github.com/nats-io/nats.go v1.49.0
|
||||
github.com/urfave/cli/v3 v3.7.0
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23
|
||||
go.bug.st/serial v1.6.4
|
||||
go.opentelemetry.io/otel v1.41.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0
|
||||
go.opentelemetry.io/otel/sdk v1.41.0
|
||||
go.opentelemetry.io/otel/trace v1.41.0
|
||||
go.opentelemetry.io/otel v1.42.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0
|
||||
go.opentelemetry.io/otel/sdk v1.42.0
|
||||
go.opentelemetry.io/otel/trace v1.42.0
|
||||
modernc.org/quickjs v0.17.1
|
||||
sigs.k8s.io/yaml v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/creack/goselect v0.1.2 // indirect
|
||||
@@ -42,15 +43,14 @@ require (
|
||||
github.com/gobwas/ws v1.4.0 // indirect
|
||||
github.com/google/go-tpm v0.9.8 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
|
||||
github.com/icholy/digest v1.1.0 // indirect
|
||||
github.com/klauspost/compress v1.18.3 // indirect
|
||||
github.com/klauspost/compress v1.18.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.0 // indirect
|
||||
github.com/nats-io/nkeys v0.4.12 // indirect
|
||||
github.com/nats-io/nkeys v0.4.15 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
@@ -65,20 +65,20 @@ require (
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/zaf/g711 v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.41.0 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
|
||||
golang.org/x/net v0.50.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/time v0.14.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/grpc v1.79.1 // indirect
|
||||
google.golang.org/grpc v1.79.2 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 // indirect
|
||||
modernc.org/libc v1.67.1 // indirect
|
||||
|
||||
64
go.sum
64
go.sum
@@ -1,5 +1,5 @@
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op h1:Ucf+QxEKMbPogRO5guBNe5cgd9uZgfoJLOYs8WWhtjM=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0mDD1gk7o9BhI16b9p5yYAXRlidpqJE=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
|
||||
github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
@@ -18,8 +18,8 @@ github.com/emiago/diago v0.27.0 h1:5SQBbcLR9ooxhSMlTkU9QSuDv/2nhMO9lxuWJTd/7rE=
|
||||
github.com/emiago/diago v0.27.0/go.mod h1:8hUxCDPJY2p32hh+4ed7vHW/3yTMmEa3BjNctUPeGD0=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 h1:o4LxpUnZ1zxiQ+Qjc9kLwXcjz31NGAHmnZ7xoJto3VM=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0/go.mod h1:ydcZ977eS1I6uOWodzMuw30BwvNAzT9su/xcNYSJqjA=
|
||||
github.com/emiago/sipgo v1.2.0 h1:rmHFdCu9zu2Cabfd8+/eC9HQWyooqk8x+ti550z5lBw=
|
||||
github.com/emiago/sipgo v1.2.0/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/emiago/sipgo v1.2.1 h1:5JTwogbe3yQFA3sjBVueN2Q4WTU350tGeBwPYT8HMv0=
|
||||
github.com/emiago/sipgo v1.2.1/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM=
|
||||
github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
@@ -65,8 +65,8 @@ github.com/jwetzell/osc-go v0.2.0 h1:4as+BYCeZhEddFczGveP5yZZxvY728Uavz+ZSLZfOII
|
||||
github.com/jwetzell/osc-go v0.2.0/go.mod h1:D3ZIXYB12bt4S35lKFUqgCFbF1Y+9Ld0sOhHA9mGZZM=
|
||||
github.com/jwetzell/psn-go v0.3.0 h1:WVpCEmExYE8a+I5hQak5jNJJp2x35VdGX/VuMUKPmhY=
|
||||
github.com/jwetzell/psn-go v0.3.0/go.mod h1:bcEAeti4sQM375buujb3mIfmUstD4Aby18gq3ENb6+o=
|
||||
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
|
||||
github.com/klauspost/compress v1.18.3/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
@@ -77,12 +77,12 @@ github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 h1:KGuD/pM2JpL
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.0 h1:K7uzyz50+yGZDO5o772eRE7atlcSEENpL7P+b74JV1g=
|
||||
github.com/nats-io/jwt/v2 v2.8.0/go.mod h1:me11pOkwObtcBNR8AiMrUbtVOUGkqYjMQZ6jnSdVUIA=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4 h1:ZnT10v2LU2Xcoiy8ek9X6Se4YG8EuMfIfvAEuFVx1Ts=
|
||||
github.com/nats-io/nats-server/v2 v2.12.4/go.mod h1:5MCp/pqm5SEfsvVZ31ll1088ZTwEUdvRX1Hmh/mTTDg=
|
||||
github.com/nats-io/nats-server/v2 v2.12.5 h1:EOHLbsLJgUHUwzkj9gBTOlubkX+dmSs0EYWMdBiHivU=
|
||||
github.com/nats-io/nats-server/v2 v2.12.5/go.mod h1:JQDAKcwdXs0NRhvYO31dzsXkzCyDkOBS7SKU3Nozu14=
|
||||
github.com/nats-io/nats.go v1.49.0 h1:yh/WvY59gXqYpgl33ZI+XoVPKyut/IcEaqtsiuTJpoE=
|
||||
github.com/nats-io/nats.go v1.49.0/go.mod h1:fDCn3mN5cY8HooHwE2ukiLb4p4G4ImmzvXyJt+tGwdw=
|
||||
github.com/nats-io/nkeys v0.4.12 h1:nssm7JKOG9/x4J8II47VWCL1Ds29avyiQDRn0ckMvDc=
|
||||
github.com/nats-io/nkeys v0.4.12/go.mod h1:MT59A1HYcjIcyQDJStTfaOY6vhy9XTUjOFo+SVsvpBg=
|
||||
github.com/nats-io/nkeys v0.4.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
|
||||
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
@@ -123,20 +123,20 @@ go.bug.st/serial v1.6.4 h1:7FmqNPgVp3pu2Jz5PoPtbZ9jJO5gnEnZIvnI1lzve8A=
|
||||
go.bug.st/serial v1.6.4/go.mod h1:nofMJxTeNVny/m6+KaafC6vJGj3miwQZ6vW4BZUGJPI=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/otel v1.41.0 h1:YlEwVsGAlCvczDILpUXpIpPSL/VPugt7zHThEMLce1c=
|
||||
go.opentelemetry.io/otel v1.41.0/go.mod h1:Yt4UwgEKeT05QbLwbyHXEwhnjxNO6D8L5PQP51/46dE=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0 h1:ao6Oe+wSebTlQ1OEht7jlYTzQKE+pnx/iNywFvTbuuI=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.41.0/go.mod h1:u3T6vz0gh/NVzgDgiwkgLxpsSF6PaPmo2il0apGJbls=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0 h1:inYW9ZhgqiDqh6BioM7DVHHzEGVq76Db5897WLGZ5Go=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.41.0/go.mod h1:Izur+Wt8gClgMJqO/cZ8wdeeMryJ/xxiOVgFSSfpDTY=
|
||||
go.opentelemetry.io/otel/metric v1.41.0 h1:rFnDcs4gRzBcsO9tS8LCpgR0dxg4aaxWlJxCno7JlTQ=
|
||||
go.opentelemetry.io/otel/metric v1.41.0/go.mod h1:xPvCwd9pU0VN8tPZYzDZV/BMj9CM9vs00GuBjeKhJps=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0 h1:YPIEXKmiAwkGl3Gu1huk1aYWwtpRLeskpV+wPisxBp8=
|
||||
go.opentelemetry.io/otel/sdk v1.41.0/go.mod h1:ahFdU0G5y8IxglBf0QBJXgSe7agzjE4GiTJ6HT9ud90=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0 h1:siZQIYBAUd1rlIWQT2uCxWJxcCO7q3TriaMlf08rXw8=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.41.0/go.mod h1:HNBuSvT7ROaGtGI50ArdRLUnvRTRGniSUZbxiWxSO8Y=
|
||||
go.opentelemetry.io/otel/trace v1.41.0 h1:Vbk2co6bhj8L59ZJ6/xFTskY+tGAbOnCtQGVVa9TIN0=
|
||||
go.opentelemetry.io/otel/trace v1.41.0/go.mod h1:U1NU4ULCoxeDKc09yCWdWe+3QoyweJcISEVa1RBzOis=
|
||||
go.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
@@ -151,18 +151,18 @@ golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:j/pmGrbnkbPtQfxEe5D0VQhZC6qKbfKifgD0oM7sR70=
|
||||
golang.org/x/mod v0.32.0 h1:9F4d3PHLljb6x//jOyokMv3eX+YDeepZSEo3mFJy93c=
|
||||
golang.org/x/mod v0.32.0/go.mod h1:SgipZ/3h2Ci89DlEtEXWUk/HteuRin+HHhN+WbNhguU=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=
|
||||
golang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
golang.org/x/tools v0.41.0 h1:a9b8iMweWG+S0OBnlU36rzLp20z1Rp10w+IY2czHTQc=
|
||||
golang.org/x/tools v0.41.0/go.mod h1:XSY6eDqxVNiYgezAVqqCeihT4j1U2CCsqvH3WhQpnlg=
|
||||
gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
|
||||
@@ -171,8 +171,8 @@ google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:kSJwQxqmFXeo79zOmbrALdflXQeAYcUbgS7PbpMknCY=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 h1:mWPCjDEyshlQYzBpMNHaEof6UX1PmHcaUODUywQ0uac=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
|
||||
google.golang.org/grpc v1.79.1 h1:zGhSi45ODB9/p3VAawt9a+O/MULLl9dpizzNNpq7flY=
|
||||
google.golang.org/grpc v1.79.1/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/grpc v1.79.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
|
||||
google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -1,22 +1,179 @@
|
||||
package common
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
const SenderContextKey contextKey = contextKey("sender")
|
||||
|
||||
type RouteIO interface {
|
||||
HandleInput(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||
func GetAnyAs[T any](value any) (T, bool) {
|
||||
typed, ok := value.(T)
|
||||
return typed, ok
|
||||
}
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int
|
||||
OutputError error
|
||||
ProcessError error
|
||||
InputError error
|
||||
func GetAnyAsInt(value any) (int, bool) {
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return intValue, true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return int(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return int(byteValue), true
|
||||
}
|
||||
|
||||
floatValue, ok := value.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return 0, false
|
||||
}
|
||||
return int(floatValue), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsByteSlice(value any) ([]byte, bool) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = byteValue
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
if uintValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
if intValue < 0 || intValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, false
|
||||
}
|
||||
if floatValue < 0 || floatValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsIntSlice(value any) ([]int, bool) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = int(byteValue)
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
result[i] = int(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
result[i] = int(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = int(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsFloat32(value any) (float32, bool) {
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float32Value, true
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float32(float64Value), true
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float32(intValue), true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float32(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float32(byteValue), true
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsFloat64(value any) (float64, bool) {
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float64Value, true
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float64(float32Value), true
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float64(intValue), true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float64(uintValue), true
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float64(byteValue), true
|
||||
}
|
||||
|
||||
return 0, false
|
||||
}
|
||||
|
||||
8
internal/common/context.go
Normal file
8
internal/common/context.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package common
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
const SenderContextKey contextKey = contextKey("sender")
|
||||
15
internal/common/routing.go
Normal file
15
internal/common/routing.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package common
|
||||
|
||||
import "context"
|
||||
|
||||
type RouteIO interface {
|
||||
HandleInput(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||
}
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError error `json:"outputError"`
|
||||
ProcessError error `json:"processError"`
|
||||
InputError error `json:"inputError"`
|
||||
}
|
||||
@@ -1,273 +1,18 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Api ApiConfig `json:"api"`
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
|
||||
type Params map[string]any
|
||||
|
||||
var (
|
||||
ErrParamNotFound = errors.New("not found")
|
||||
ErrParamNotString = errors.New("not a string")
|
||||
ErrParamNotNumber = errors.New("not a number")
|
||||
ErrParamNotInteger = errors.New("not an integer")
|
||||
ErrParamNotBool = errors.New("not a boolean")
|
||||
ErrParamNotSlice = errors.New("not a slice")
|
||||
)
|
||||
|
||||
func (p Params) GetString(key string) (string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return "", ErrParamNotFound
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok {
|
||||
return "", ErrParamNotString
|
||||
}
|
||||
return stringValue, nil
|
||||
type ApiConfig struct {
|
||||
Port int `json:"port"`
|
||||
}
|
||||
|
||||
func (p Params) GetInt(key string) (int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return int(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return int(byteValue), nil
|
||||
}
|
||||
|
||||
floatValue, ok := value.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return 0, ErrParamNotInteger
|
||||
}
|
||||
return int(floatValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat32(key string) (float32, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float32Value, nil
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float32(float64Value), nil
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float32(intValue), nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float32(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float32(byteValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat64(key string) (float64, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
return float64Value, nil
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
return float64(float32Value), nil
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return float64(intValue), nil
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return float64(uintValue), nil
|
||||
}
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return float64(byteValue), nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetBool(key string) (bool, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return false, ErrParamNotFound
|
||||
}
|
||||
|
||||
boolValue, ok := value.(bool)
|
||||
if !ok {
|
||||
return false, ErrParamNotBool
|
||||
}
|
||||
return boolValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetStringSlice(key string) ([]string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
interfaceSlice, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
stringSlice := make([]string, len(interfaceSlice))
|
||||
for i, v := range interfaceSlice {
|
||||
str, ok := v.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("element at index %d is not a string", i)
|
||||
}
|
||||
stringSlice[i] = str
|
||||
}
|
||||
return stringSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetIntSlice(key string) ([]int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = int(byteValue)
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
result[i] = int(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
result[i] = int(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, fmt.Errorf("element at index %d is not an integer", i)
|
||||
}
|
||||
result[i] = int(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("element at index %d is not a number", i)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (p Params) GetByteSlice(key string) ([]byte, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = byteValue
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
if uintValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
if intValue < 0 || intValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, fmt.Errorf("element at index %d is not an integer", i)
|
||||
}
|
||||
if floatValue < 0 || floatValue > 255 {
|
||||
return nil, fmt.Errorf("element at index %d is out of byte range", i)
|
||||
}
|
||||
result[i] = byte(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, fmt.Errorf("element at index %d is not a number", i)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type RouteConfig struct {
|
||||
@@ -277,5 +22,5 @@ type RouteConfig struct {
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
140
internal/config/params.go
Normal file
140
internal/config/params.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
type Params map[string]any
|
||||
|
||||
var (
|
||||
ErrParamNotFound = errors.New("not found")
|
||||
ErrParamNotString = errors.New("not a string")
|
||||
ErrParamNotNumber = errors.New("not a number")
|
||||
ErrParamNotInteger = errors.New("not an integer")
|
||||
ErrParamNotBool = errors.New("not a boolean")
|
||||
ErrParamNotSlice = errors.New("not a slice")
|
||||
ErrParamNotByteSlice = errors.New("not a byte slice")
|
||||
ErrParamNotIntSlice = errors.New("not an int slice")
|
||||
)
|
||||
|
||||
func (p Params) GetString(key string) (string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return "", ErrParamNotFound
|
||||
}
|
||||
|
||||
stringValue, ok := value.(string)
|
||||
if !ok {
|
||||
return "", ErrParamNotString
|
||||
}
|
||||
return stringValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetInt(key string) (int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
intValue, ok := common.GetAnyAsInt(value)
|
||||
if ok {
|
||||
return intValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat32(key string) (float32, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
floatValue, ok := common.GetAnyAsFloat32(value)
|
||||
if ok {
|
||||
return floatValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetFloat64(key string) (float64, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return 0, ErrParamNotFound
|
||||
}
|
||||
|
||||
floatValue, ok := common.GetAnyAsFloat64(value)
|
||||
if ok {
|
||||
return floatValue, nil
|
||||
}
|
||||
|
||||
return 0, ErrParamNotNumber
|
||||
}
|
||||
|
||||
func (p Params) GetBool(key string) (bool, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return false, ErrParamNotFound
|
||||
}
|
||||
|
||||
boolValue, ok := value.(bool)
|
||||
if !ok {
|
||||
return false, ErrParamNotBool
|
||||
}
|
||||
return boolValue, nil
|
||||
}
|
||||
|
||||
func (p Params) GetStringSlice(key string) ([]string, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
interfaceSlice, ok := value.([]any)
|
||||
if !ok {
|
||||
return nil, ErrParamNotSlice
|
||||
}
|
||||
|
||||
stringSlice := make([]string, len(interfaceSlice))
|
||||
for i, v := range interfaceSlice {
|
||||
str, ok := v.(string)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("element at index %d is not a string", i)
|
||||
}
|
||||
stringSlice[i] = str
|
||||
}
|
||||
return stringSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetIntSlice(key string) ([]int, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
intSlice, ok := common.GetAnyAsIntSlice(value)
|
||||
if !ok {
|
||||
return nil, ErrParamNotIntSlice
|
||||
}
|
||||
|
||||
return intSlice, nil
|
||||
}
|
||||
|
||||
func (p Params) GetByteSlice(key string) ([]byte, error) {
|
||||
value, ok := p[key]
|
||||
if !ok {
|
||||
return nil, ErrParamNotFound
|
||||
}
|
||||
|
||||
byteSlice, ok := common.GetAnyAsByteSlice(value)
|
||||
|
||||
if !ok {
|
||||
return nil, ErrParamNotByteSlice
|
||||
}
|
||||
|
||||
return byteSlice, nil
|
||||
}
|
||||
@@ -187,7 +187,7 @@ func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("http.server output must originate from an http.server input")
|
||||
}
|
||||
|
||||
payloadResponse, ok := processor.GetAnyAs[processor.HTTPResponse](payload)
|
||||
payloadResponse, ok := common.GetAnyAs[processor.HTTPResponse](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server is only able to output HTTPResponse")
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
@@ -85,7 +84,7 @@ func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := processor.GetAnyAs[midi.Message](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only ouptut midi.Message")
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
)
|
||||
|
||||
type ModuleError struct {
|
||||
Index int
|
||||
Config config.ModuleConfig
|
||||
Error error
|
||||
Index int `json:"index"`
|
||||
Config config.ModuleConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type Module interface {
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
@@ -102,7 +101,7 @@ func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
payloadMessage, ok := processor.GetAnyAs[mqtt.Message](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||
|
||||
@@ -94,7 +94,7 @@ func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
|
||||
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadMessage, ok := processor.GetAnyAs[processor.NATSMessage](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[processor.NATSMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client is only able to output NATSMessage")
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
@@ -157,7 +156,7 @@ func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
|
||||
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client can only ouptut bytes")
|
||||
|
||||
@@ -173,7 +173,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.call.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
@@ -189,7 +189,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
|
||||
@@ -199,7 +199,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.dtmf.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
@@ -216,7 +216,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type TCPClient struct {
|
||||
@@ -153,7 +152,7 @@ func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client is only able to output bytes")
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type TCPServer struct {
|
||||
@@ -207,7 +206,7 @@ AcceptLoop:
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server is only able to output bytes")
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type UDPClient struct {
|
||||
@@ -88,7 +87,7 @@ func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
|
||||
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.client is only able to output bytes")
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type UDPMulticast struct {
|
||||
@@ -109,7 +108,7 @@ func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
|
||||
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast can only output bytes")
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type ArtNetPacketDecode struct {
|
||||
}
|
||||
|
||||
func (apd *ArtNetPacketDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type ArtNetPacketEncode struct {
|
||||
}
|
||||
|
||||
func (ape *ArtNetPacketEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPacket, ok := GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
payloadPacket, ok := common.GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||
|
||||
@@ -6,41 +6,42 @@ import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type StringFilter struct {
|
||||
type FilterRegex struct {
|
||||
config config.ProcessorConfig
|
||||
Pattern *regexp.Regexp
|
||||
}
|
||||
|
||||
func (sf *StringFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
func (fr *FilterRegex) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.filter processor only accepts a string")
|
||||
return nil, errors.New("filter.regex processor only accepts a string")
|
||||
}
|
||||
|
||||
if !sf.Pattern.MatchString(payloadString) {
|
||||
if !fr.Pattern.MatchString(payloadString) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadString, nil
|
||||
}
|
||||
|
||||
func (sf *StringFilter) Type() string {
|
||||
return sf.config.Type
|
||||
func (fr *FilterRegex) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "string.filter",
|
||||
Type: "filter.regex",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
patternString, err := params.GetString("pattern")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("string.filter pattern error: %w", err)
|
||||
return nil, fmt.Errorf("filter.regex pattern error: %w", err)
|
||||
}
|
||||
|
||||
patternRegexp, err := regexp.Compile(patternString)
|
||||
@@ -49,7 +50,7 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &StringFilter{config: config, Pattern: patternRegexp}, nil
|
||||
return &FilterRegex{config: config, Pattern: patternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -15,7 +16,7 @@ type FloatParse struct {
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse processor only accepts a string")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type FreeDDecode struct {
|
||||
}
|
||||
|
||||
func (fd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a []byte")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type FreeDEncode struct {
|
||||
}
|
||||
|
||||
func (fe *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := GetAnyAs[freeD.FreeDPosition](payload)
|
||||
payloadPosition, ok := common.GetAnyAs[freeD.FreeDPosition](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a FreeDEncode")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -16,7 +17,7 @@ type IntParse struct {
|
||||
}
|
||||
|
||||
func (ip *IntParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("int.parse processor only accepts a string")
|
||||
|
||||
71
internal/processor/int-scale.go
Normal file
71
internal/processor/int-scale.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type IntScale struct {
|
||||
OutMin int
|
||||
OutMax int
|
||||
InMin int
|
||||
InMax int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (ir *IntScale) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadInt, ok := common.GetAnyAs[int](payload)
|
||||
if !ok {
|
||||
return nil, errors.New("int.scale can only process an int")
|
||||
}
|
||||
|
||||
payloadInt = (payloadInt-ir.InMin)*(ir.OutMax-ir.OutMin)/(ir.InMax-ir.InMin) + ir.OutMin
|
||||
return payloadInt, nil
|
||||
}
|
||||
|
||||
func (ir *IntScale) Type() string {
|
||||
return ir.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "int.scale",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
inMinInt, err := params.GetInt("inMin")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale inMin error: %w", err)
|
||||
}
|
||||
|
||||
inMaxInt, err := params.GetInt("inMax")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale inMax error: %w", err)
|
||||
}
|
||||
|
||||
if inMaxInt < inMinInt {
|
||||
return nil, errors.New("int.scale inMax must be greater than inMin")
|
||||
}
|
||||
|
||||
outMinInt, err := params.GetInt("outMin")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale outMin error: %w", err)
|
||||
}
|
||||
|
||||
outMaxInt, err := params.GetInt("outMax")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("int.scale outMax error: %w", err)
|
||||
}
|
||||
|
||||
if outMaxInt < outMinInt {
|
||||
return nil, errors.New("int.scale outMax must be greater than outMin")
|
||||
}
|
||||
|
||||
return &IntScale{config: config, InMin: inMinInt, InMax: inMaxInt, OutMin: outMinInt, OutMax: outMaxInt}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -14,10 +15,10 @@ type JsonDecode struct {
|
||||
|
||||
func (jd *JsonDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadBytes, ok := GetAnyAsByteSlice(payload)
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
if !ok {
|
||||
return nil, errors.New("json.decode can only process a string or []byte")
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -15,7 +16,7 @@ type MIDIMessageDecode struct {
|
||||
}
|
||||
|
||||
func (mmd *MIDIMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.decode processor only accepts a []byte")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -15,7 +16,7 @@ type MIDIMessageEncode struct {
|
||||
}
|
||||
|
||||
func (mme *MIDIMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := GetAnyAs[midi.Message](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.encode processor only accepts a midi.Message")
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
)
|
||||
@@ -45,7 +46,7 @@ type MIDIPitchBend struct {
|
||||
}
|
||||
|
||||
func (mmu *MIDIMessageUnpack) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMidi, ok := GetAnyAs[midi.Message](payload)
|
||||
payloadMidi, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.message.unpack processor only accepts a midi.Message")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type MQTTMessageEncode struct {
|
||||
}
|
||||
|
||||
func (mme *MQTTMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := GetAnyAs[mqtt.Message](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.message.encode processor only accepts an mqtt.Message")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -14,7 +15,7 @@ type OSCMessageDecode struct {
|
||||
}
|
||||
|
||||
func (omd *OSCMessageDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.decode processor only accepts a []byte payload")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
osc "github.com/jwetzell/osc-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,7 +14,7 @@ type OSCMessageEncode struct {
|
||||
}
|
||||
|
||||
func (ome *OSCMessageEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadMessage, ok := GetAnyAs[*osc.OSCMessage](payload)
|
||||
payloadMessage, ok := common.GetAnyAs[*osc.OSCMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("osc.message.encode processor only accepts an *OSCMessage")
|
||||
|
||||
@@ -3,8 +3,6 @@ package processor
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
@@ -44,57 +42,6 @@ var (
|
||||
ProcessorRegistry = make(map[string]ProcessorRegistration)
|
||||
)
|
||||
|
||||
func GetAnyAs[T any](p any) (T, bool) {
|
||||
typed, ok := p.(T)
|
||||
return typed, ok
|
||||
}
|
||||
|
||||
func GetAnyAsByteSlice(p any) ([]byte, bool) {
|
||||
v := reflect.ValueOf(p)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
byteValue, ok := elem.(byte)
|
||||
if ok {
|
||||
result[i] = byteValue
|
||||
continue
|
||||
}
|
||||
uintValue, ok := elem.(uint)
|
||||
if ok {
|
||||
if uintValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(uintValue)
|
||||
continue
|
||||
}
|
||||
intValue, ok := elem.(int)
|
||||
if ok {
|
||||
if intValue < 0 || intValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(intValue)
|
||||
continue
|
||||
}
|
||||
floatValue, ok := elem.(float64)
|
||||
if ok {
|
||||
if floatValue != math.Floor(floatValue) {
|
||||
return nil, false
|
||||
}
|
||||
if floatValue < 0 || floatValue > 255 {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = byte(floatValue)
|
||||
continue
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
type TemplateData struct {
|
||||
Payload any
|
||||
Modules any
|
||||
|
||||
55
internal/processor/router-input.go
Normal file
55
internal/processor/router-input.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type RouterInput struct {
|
||||
config config.ProcessorConfig
|
||||
SourceId string
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (ro *RouterInput) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
if !ok {
|
||||
return nil, errors.New("router.input no router found")
|
||||
}
|
||||
|
||||
_, err := router.HandleInput(ctx, ro.SourceId, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.New("router.input failed to send input")
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (ro *RouterInput) Type() string {
|
||||
return ro.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "router.input",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
sourceId, err := params.GetString("source")
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("router.input source error: %w", err)
|
||||
}
|
||||
|
||||
return &RouterInput{config: config, SourceId: sourceId, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -11,43 +11,39 @@ import (
|
||||
)
|
||||
|
||||
type ScriptJS struct {
|
||||
config config.ProcessorConfig
|
||||
Program string
|
||||
config config.ProcessorConfig
|
||||
vm *quickjs.VM
|
||||
payloadAtom quickjs.Atom
|
||||
senderAtom quickjs.Atom
|
||||
Program string
|
||||
}
|
||||
|
||||
func (sj *ScriptJS) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
vm, err := quickjs.NewVM()
|
||||
//NOTE(jwetzell): some weird conversion going on with these types
|
||||
_, isUint8Slice := common.GetAnyAs[[]uint8](payload)
|
||||
_, isbyteSlice := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer vm.Close()
|
||||
payloadAtom, err := vm.NewAtom("payload")
|
||||
if isUint8Slice || isbyteSlice {
|
||||
intSlice, ok := common.GetAnyAsIntSlice(payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
if ok {
|
||||
payload = intSlice
|
||||
}
|
||||
}
|
||||
|
||||
vm.SetProperty(vm.GlobalObject(), payloadAtom, payload)
|
||||
sj.vm.SetProperty(sj.vm.GlobalObject(), sj.payloadAtom, payload)
|
||||
|
||||
sender := ctx.Value(common.SenderContextKey)
|
||||
if sender != nil {
|
||||
senderAtom, err := vm.NewAtom("sender")
|
||||
sj.vm.SetProperty(sj.vm.GlobalObject(), sj.senderAtom, sender)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
vm.SetProperty(vm.GlobalObject(), senderAtom, sender)
|
||||
}
|
||||
|
||||
_, err = vm.Eval(sj.Program, quickjs.EvalGlobal)
|
||||
_, err := sj.vm.Eval(sj.Program, quickjs.EvalGlobal)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
output, err := vm.GetProperty(vm.GlobalObject(), payloadAtom)
|
||||
output, err := sj.vm.GetProperty(sj.vm.GlobalObject(), sj.payloadAtom)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -65,6 +61,7 @@ func (sj *ScriptJS) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
if ok {
|
||||
var outputMap map[string]interface{}
|
||||
fmt.Println(outputObject.String())
|
||||
err := json.Unmarshal([]byte(outputObject.String()), &outputMap)
|
||||
return outputMap, err
|
||||
}
|
||||
@@ -87,7 +84,23 @@ func init() {
|
||||
return nil, fmt.Errorf("script.js program error: %w", err)
|
||||
}
|
||||
|
||||
return &ScriptJS{config: config, Program: programString}, nil
|
||||
vm, err := quickjs.NewVM()
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payloadAtom, err := vm.NewAtom("payload")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
senderAtom, err := vm.NewAtom("sender")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &ScriptJS{config: config, Program: programString, vm: vm, payloadAtom: payloadAtom, senderAtom: senderAtom}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
extism "github.com/extism/go-sdk"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -17,7 +18,7 @@ type ScriptWASM struct {
|
||||
|
||||
func (sw *ScriptWASM) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("script.wasm can only process a byte array")
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,7 +13,7 @@ type StringDecode struct {
|
||||
}
|
||||
|
||||
func (sd *StringDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.decode processor only accepts a []byte")
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,7 +13,7 @@ type StringEncode struct {
|
||||
}
|
||||
|
||||
func (se *StringEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.encode processor only accepts a string")
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -15,7 +16,7 @@ type StringSplit struct {
|
||||
}
|
||||
|
||||
func (ss *StringSplit) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("string.split only accepts a string")
|
||||
|
||||
@@ -9,23 +9,23 @@ import (
|
||||
)
|
||||
|
||||
func TestStringFilterFromRegistry(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["string.filter"]
|
||||
registration, ok := processor.ProcessorRegistry["filter.regex"]
|
||||
if !ok {
|
||||
t.Fatalf("string.filter processor not registered")
|
||||
t.Fatalf("filter.regex processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "string.filter",
|
||||
Type: "filter.regex",
|
||||
Params: map[string]any{
|
||||
"pattern": "hello",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create string.filter processor: %s", err)
|
||||
t.Fatalf("failed to create filter.regex processor: %s", err)
|
||||
}
|
||||
|
||||
if processorInstance.Type() != "string.filter" {
|
||||
t.Fatalf("string.filter processor has wrong type: %s", processorInstance.Type())
|
||||
if processorInstance.Type() != "filter.regex" {
|
||||
t.Fatalf("filter.regex processor has wrong type: %s", processorInstance.Type())
|
||||
}
|
||||
|
||||
payload := "hello"
|
||||
@@ -33,17 +33,17 @@ func TestStringFilterFromRegistry(t *testing.T) {
|
||||
|
||||
got, err := processorInstance.Process(t.Context(), payload)
|
||||
if err != nil {
|
||||
t.Fatalf("string.filter processing failed: %s", err)
|
||||
t.Fatalf("filter.regex processing failed: %s", err)
|
||||
}
|
||||
|
||||
gotString, ok := got.(string)
|
||||
|
||||
if !ok {
|
||||
t.Fatalf("string.filter should return byte slice")
|
||||
t.Fatalf("filter.regex should return byte slice")
|
||||
}
|
||||
|
||||
if gotString != expected {
|
||||
t.Fatalf("string.filter got %+v, expected %+v", got, expected)
|
||||
t.Fatalf("filter.regex got %+v, expected %+v", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,40 +76,40 @@ func TestGoodStringFilter(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["string.filter"]
|
||||
registration, ok := processor.ProcessorRegistry["filter.regex"]
|
||||
if !ok {
|
||||
t.Fatalf("string.filter processor not registered")
|
||||
t.Fatalf("filter.regex processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "string.filter",
|
||||
Type: "filter.regex",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("string.filter failed to create processor: %s", err)
|
||||
t.Fatalf("filter.regex failed to create processor: %s", err)
|
||||
}
|
||||
|
||||
got, err := processorInstance.Process(t.Context(), test.payload)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("string.filter processing failed: %s", err)
|
||||
t.Fatalf("filter.regex processing failed: %s", err)
|
||||
}
|
||||
|
||||
if test.expected == nil {
|
||||
if got != nil {
|
||||
t.Fatalf("string.filter got %+v, expected nil", got)
|
||||
t.Fatalf("filter.regex got %+v, expected nil", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
gotString, ok := got.(string)
|
||||
if !ok {
|
||||
t.Fatalf("string.filter returned a %T payload: %s", got, got)
|
||||
t.Fatalf("filter.regex returned a %T payload: %s", got, got)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(gotString, test.expected) {
|
||||
t.Fatalf("string.filter got %+v, expected %+v", gotString, test.expected)
|
||||
t.Fatalf("filter.regex got %+v, expected %+v", gotString, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -126,7 +126,7 @@ func TestBadStringFilter(t *testing.T) {
|
||||
name: "no pattern param",
|
||||
payload: "hello",
|
||||
params: map[string]any{},
|
||||
errorString: "string.filter pattern error: not found",
|
||||
errorString: "filter.regex pattern error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string input",
|
||||
@@ -134,7 +134,7 @@ func TestBadStringFilter(t *testing.T) {
|
||||
params: map[string]any{
|
||||
"pattern": "hello",
|
||||
},
|
||||
errorString: "string.filter processor only accepts a string",
|
||||
errorString: "filter.regex processor only accepts a string",
|
||||
},
|
||||
{
|
||||
name: "non-string pattern param",
|
||||
@@ -142,7 +142,7 @@ func TestBadStringFilter(t *testing.T) {
|
||||
params: map[string]any{
|
||||
"pattern": 123,
|
||||
},
|
||||
errorString: "string.filter pattern error: not a string",
|
||||
errorString: "filter.regex pattern error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid regex pattern",
|
||||
@@ -156,19 +156,19 @@ func TestBadStringFilter(t *testing.T) {
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["string.filter"]
|
||||
registration, ok := processor.ProcessorRegistry["filter.regex"]
|
||||
if !ok {
|
||||
t.Fatalf("string.filter processor not registered")
|
||||
t.Fatalf("filter.regex processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "string.filter",
|
||||
Type: "filter.regex",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("string.filter got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
t.Fatalf("filter.regex got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -176,11 +176,11 @@ func TestBadStringFilter(t *testing.T) {
|
||||
got, err := processorInstance.Process(t.Context(), test.payload)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("string.filter expected to fail but got payload: %s", got)
|
||||
t.Fatalf("filter.regex expected to fail but got payload: %s", got)
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("string.filter got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
t.Fatalf("filter.regex got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
170
internal/processor/test/int-scale_test.go
Normal file
170
internal/processor/test/int-scale_test.go
Normal file
@@ -0,0 +1,170 @@
|
||||
package processor_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
func TestIntScaleFromRegistry(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["int.scale"]
|
||||
if !ok {
|
||||
t.Fatalf("int.scale processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "int.scale",
|
||||
Params: map[string]any{
|
||||
"inMin": 0,
|
||||
"inMax": 10,
|
||||
"outMin": 0,
|
||||
"outMax": 127,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create int.scale processor: %s", err)
|
||||
}
|
||||
|
||||
if processorInstance.Type() != "int.scale" {
|
||||
t.Fatalf("int.scale processor has wrong type: %s", processorInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntScale(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
payload any
|
||||
params map[string]any
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "0-10 -> 0-127",
|
||||
params: map[string]any{
|
||||
"inMin": 0,
|
||||
"inMax": 10,
|
||||
"outMin": 0,
|
||||
"outMax": 127,
|
||||
},
|
||||
payload: 5,
|
||||
expected: 63,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
registration, ok := processor.ProcessorRegistry["int.scale"]
|
||||
if !ok {
|
||||
t.Fatalf("int.scale processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "int.scale",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("int.scale failed to create processor: %s", err)
|
||||
}
|
||||
|
||||
got, err := processorInstance.Process(t.Context(), test.payload)
|
||||
if err != nil {
|
||||
t.Fatalf("int.scale processing failed: %s", err)
|
||||
}
|
||||
|
||||
gotInt, ok := got.(int)
|
||||
if !ok {
|
||||
t.Fatalf("int.scale returned a %T payload: %s", got, got)
|
||||
}
|
||||
|
||||
if gotInt != test.expected {
|
||||
t.Fatalf("int.scale got %d, expected %d", gotInt, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadIntScale(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
payload any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no inMin param",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMax": 10, "outMin": 0, "outMax": 127},
|
||||
errorString: "int.scale inMin error: not found",
|
||||
},
|
||||
{
|
||||
name: "no inMax param",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": 0, "outMin": 0, "outMax": 127},
|
||||
errorString: "int.scale inMax error: not found",
|
||||
},
|
||||
{
|
||||
name: "no outMin param",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": 0, "inMax": 10, "outMax": 127},
|
||||
errorString: "int.scale outMin error: not found",
|
||||
},
|
||||
{
|
||||
name: "no outMax param",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": 0, "inMax": 10, "outMin": 0},
|
||||
errorString: "int.scale outMax error: not found",
|
||||
},
|
||||
{
|
||||
name: "inMin param not a number",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": "0", "max": 10, "outMin": 0, "outMax": 127},
|
||||
errorString: "int.scale inMin error: not a number",
|
||||
},
|
||||
{
|
||||
name: "inMax param not a number",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": 0, "inMax": "10", "outMin": 0, "outMax": 127},
|
||||
errorString: "int.scale inMax error: not a number",
|
||||
},
|
||||
{
|
||||
name: "inMax less than inMin",
|
||||
payload: "hello",
|
||||
params: map[string]any{"inMin": 10, "inMax": 0, "outMin": 0, "outMax": 127},
|
||||
errorString: "int.scale inMax must be greater than inMin",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := processor.ProcessorRegistry["int.scale"]
|
||||
if !ok {
|
||||
t.Fatalf("int.scale processor not registered")
|
||||
}
|
||||
|
||||
processorInstance, err := registration.New(config.ProcessorConfig{
|
||||
Type: "int.scale",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("int.scale got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
got, err := processorInstance.Process(t.Context(), test.payload)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("int.scale expected to fail but got payload: %s", got)
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("int.scale got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -204,7 +204,7 @@ func TestBadMQTTMessageCreate(t *testing.T) {
|
||||
"payload": 123,
|
||||
},
|
||||
payload: 1,
|
||||
errorString: "mqtt.message.create payload error: not a slice",
|
||||
errorString: "mqtt.message.create payload error: not a byte slice",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
)
|
||||
|
||||
type RouteError struct {
|
||||
Index int
|
||||
Config config.RouteConfig
|
||||
Error error
|
||||
Index int `json:"index"`
|
||||
Config config.RouteConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
type Route struct {
|
||||
input string
|
||||
@@ -49,7 +49,7 @@ func (r *Route) Input() string {
|
||||
|
||||
func (r *Route) ProcessPayload(ctx context.Context, payload any) (any, error) {
|
||||
tracer := otel.Tracer("route")
|
||||
processCtx, processSpan := tracer.Start(ctx, "ProcessPayload")
|
||||
processCtx, processSpan := tracer.Start(ctx, "ProcessPayload", trace.WithAttributes(attribute.String("payload.type", fmt.Sprintf("%T", payload))))
|
||||
defer processSpan.End()
|
||||
for processorIndex, processor := range r.processors {
|
||||
processorCtx, processorSpan := otel.Tracer("processor").Start(processCtx, "process", trace.WithAttributes(attribute.Int("processor.index", processorIndex), attribute.String("processor.type", processor.Type())))
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
@@ -61,7 +60,7 @@ func TestGoodRouteHandleInput(t *testing.T) {
|
||||
t.Fatalf("route ProcessPayload returned error: %v", err)
|
||||
}
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
payloadBytes, ok := common.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
t.Fatalf("payload should be []byte got %T", payload)
|
||||
}
|
||||
|
||||
162
router.go
162
router.go
@@ -4,8 +4,11 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
@@ -17,15 +20,24 @@ import (
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
)
|
||||
|
||||
// TODO(jwetzell): can/should this be split into different components?
|
||||
type Router struct {
|
||||
contextCancel context.CancelFunc
|
||||
Context context.Context
|
||||
contextCancel context.CancelFunc
|
||||
Context context.Context
|
||||
// TODO(jwetzell): do these need to be guarded against concurrency?
|
||||
ModuleInstances map[string]module.Module
|
||||
// TODO(jwetzell): change to something easier to lookup
|
||||
RouteInstances []*route.Route
|
||||
moduleWait sync.WaitGroup
|
||||
logger *slog.Logger
|
||||
runningConfig config.Config
|
||||
RouteInstances []*route.Route
|
||||
ConfigChange chan config.Config
|
||||
moduleWait sync.WaitGroup
|
||||
logger *slog.Logger
|
||||
runningConfig config.Config
|
||||
runningConfigMu sync.RWMutex
|
||||
wsConns []*websocket.Conn
|
||||
wsConnsMu sync.Mutex
|
||||
apiServer *http.Server
|
||||
apiServerMu sync.Mutex
|
||||
apiServerShutdown context.CancelFunc
|
||||
}
|
||||
|
||||
func (r *Router) addModule(moduleDecl config.ModuleConfig) error {
|
||||
@@ -102,19 +114,20 @@ func (r *Router) getModule(moduleId string) module.Module {
|
||||
return moduleInstance
|
||||
}
|
||||
|
||||
func NewRouter(config config.Config) (*Router, []module.ModuleError, []route.RouteError) {
|
||||
func NewRouter(routerConfig config.Config) (*Router, []module.ModuleError, []route.RouteError) {
|
||||
|
||||
router := Router{
|
||||
ModuleInstances: make(map[string]module.Module),
|
||||
RouteInstances: []*route.Route{},
|
||||
ConfigChange: make(chan config.Config, 1),
|
||||
logger: slog.Default().With("component", "router"),
|
||||
runningConfig: config,
|
||||
runningConfig: routerConfig,
|
||||
}
|
||||
router.logger.Debug("creating")
|
||||
|
||||
var moduleErrors []module.ModuleError
|
||||
|
||||
for moduleIndex, moduleDecl := range config.Modules {
|
||||
for moduleIndex, moduleDecl := range routerConfig.Modules {
|
||||
|
||||
err := router.addModule(moduleDecl)
|
||||
if err != nil {
|
||||
@@ -124,7 +137,7 @@ func NewRouter(config config.Config) (*Router, []module.ModuleError, []route.Rou
|
||||
moduleErrors = append(moduleErrors, module.ModuleError{
|
||||
Index: moduleIndex,
|
||||
Config: moduleDecl,
|
||||
Error: err,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -132,7 +145,7 @@ func NewRouter(config config.Config) (*Router, []module.ModuleError, []route.Rou
|
||||
}
|
||||
|
||||
var routeErrors []route.RouteError
|
||||
for routeIndex, routeDecl := range config.Routes {
|
||||
for routeIndex, routeDecl := range routerConfig.Routes {
|
||||
err := router.addRoute(routeDecl)
|
||||
if err != nil {
|
||||
if routeErrors == nil {
|
||||
@@ -141,7 +154,7 @@ func NewRouter(config config.Config) (*Router, []module.ModuleError, []route.Rou
|
||||
routeErrors = append(routeErrors, route.RouteError{
|
||||
Index: routeIndex,
|
||||
Config: routeDecl,
|
||||
Error: err,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
@@ -155,13 +168,11 @@ func (r *Router) Start(ctx context.Context) {
|
||||
routerContext, cancel := context.WithCancel(ctx)
|
||||
r.Context = routerContext
|
||||
r.contextCancel = cancel
|
||||
contextWithRouter := context.WithValue(routerContext, common.RouterContextKey, r)
|
||||
|
||||
for moduleId := range r.ModuleInstances {
|
||||
// TODO(jwetzell): handle module run errors
|
||||
r.startModule(contextWithRouter, moduleId)
|
||||
}
|
||||
r.startModules()
|
||||
r.startAPIServer(r.runningConfig.Api)
|
||||
<-r.Context.Done()
|
||||
r.logger.Debug("shutting down api server")
|
||||
r.stopAPIServer()
|
||||
r.logger.Debug("waiting for modules to exit")
|
||||
r.moduleWait.Wait()
|
||||
r.logger.Info("done")
|
||||
@@ -173,11 +184,21 @@ func (r *Router) Stop() {
|
||||
}
|
||||
|
||||
func (r *Router) HandleInput(ctx context.Context, sourceId string, payload any) (bool, []common.RouteIOError) {
|
||||
spanCtx, span := otel.Tracer("router").Start(ctx, "input", trace.WithAttributes(attribute.String("source.id", sourceId)), trace.WithNewRoot())
|
||||
r.runningConfigMu.RLock()
|
||||
defer r.runningConfigMu.RUnlock()
|
||||
|
||||
spanCtx, span := otel.Tracer("router").Start(ctx, "input", trace.WithAttributes(attribute.String("source.id", sourceId)))
|
||||
defer span.End()
|
||||
var routeIOErrors []common.RouteIOError
|
||||
routeFound := false
|
||||
|
||||
r.broadcastEvent(Event{
|
||||
Type: "input",
|
||||
Data: map[string]any{
|
||||
"source": sourceId,
|
||||
},
|
||||
})
|
||||
|
||||
var routeWaitGroup sync.WaitGroup
|
||||
|
||||
for routeIndex, routeInstance := range r.RouteInstances {
|
||||
@@ -204,8 +225,21 @@ func (r *Router) HandleInput(ctx context.Context, sourceId string, payload any)
|
||||
Index: routeIndex,
|
||||
ProcessError: err,
|
||||
})
|
||||
r.broadcastEvent(Event{
|
||||
Type: "route",
|
||||
Data: map[string]any{
|
||||
"index": routeIndex,
|
||||
},
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
r.broadcastEvent(Event{
|
||||
Type: "route",
|
||||
Data: map[string]any{
|
||||
"index": routeIndex,
|
||||
},
|
||||
})
|
||||
routeSpan.End()
|
||||
})
|
||||
}
|
||||
@@ -217,7 +251,12 @@ func (r *Router) HandleInput(ctx context.Context, sourceId string, payload any)
|
||||
func (r *Router) HandleOutput(ctx context.Context, destinationId string, payload any) error {
|
||||
spanCtx, span := otel.Tracer("router").Start(ctx, "output", trace.WithAttributes(attribute.String("destination.id", destinationId)))
|
||||
defer span.End()
|
||||
|
||||
outputEvent := Event{
|
||||
Type: "output",
|
||||
Data: map[string]any{
|
||||
"destination": destinationId,
|
||||
},
|
||||
}
|
||||
destinationModule := r.getModule(destinationId)
|
||||
|
||||
if destinationModule == nil {
|
||||
@@ -225,6 +264,8 @@ func (r *Router) HandleOutput(ctx context.Context, destinationId string, payload
|
||||
span.SetStatus(codes.Error, err.Error())
|
||||
span.RecordError(err)
|
||||
r.logger.Error("no module found for destination id", "destinationId", destinationId)
|
||||
outputEvent.Error = err.Error()
|
||||
r.broadcastEvent(outputEvent)
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -235,14 +276,93 @@ func (r *Router) HandleOutput(ctx context.Context, destinationId string, payload
|
||||
moduleOutputSpan.SetStatus(codes.Error, err.Error())
|
||||
moduleOutputSpan.RecordError(err)
|
||||
r.logger.ErrorContext(moduleOutputCtx, "module output encountered error", "module", destinationModule.Id(), "error", err)
|
||||
outputEvent.Error = err.Error()
|
||||
r.broadcastEvent(outputEvent)
|
||||
return err
|
||||
} else {
|
||||
moduleOutputSpan.SetStatus(codes.Ok, "module output successful")
|
||||
}
|
||||
|
||||
r.broadcastEvent(outputEvent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Router) startModules() {
|
||||
contextWithRouter := context.WithValue(r.Context, common.RouterContextKey, r)
|
||||
|
||||
for moduleId := range r.ModuleInstances {
|
||||
// TODO(jwetzell): handle module run errors
|
||||
err := r.startModule(contextWithRouter, moduleId)
|
||||
if err != nil {
|
||||
r.logger.Error("error starting module", "moduleId", moduleId, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) RunningConfig() config.Config {
|
||||
r.runningConfigMu.RLock()
|
||||
defer r.runningConfigMu.RLock()
|
||||
return r.runningConfig
|
||||
}
|
||||
|
||||
func (r *Router) UpdateConfig(newConfig config.Config) ([]module.ModuleError, []route.RouteError) {
|
||||
r.runningConfigMu.Lock()
|
||||
defer r.runningConfigMu.Unlock()
|
||||
oldConfig := r.runningConfig
|
||||
r.logger.Debug("received config update", "oldConfig", oldConfig, "newConfig", newConfig)
|
||||
|
||||
if !reflect.DeepEqual(oldConfig.Api, newConfig.Api) {
|
||||
r.logger.Info("applying new API config")
|
||||
r.stopAPIServer()
|
||||
r.startAPIServer(newConfig.Api)
|
||||
r.runningConfig.Api = newConfig.Api
|
||||
}
|
||||
|
||||
// TODO(jwetzell): handle config update errors better
|
||||
for _, moduleInstance := range r.ModuleInstances {
|
||||
moduleInstance.Stop()
|
||||
}
|
||||
r.logger.Debug("waiting for modules to exit")
|
||||
r.moduleWait.Wait()
|
||||
|
||||
r.ModuleInstances = make(map[string]module.Module)
|
||||
r.RouteInstances = []*route.Route{}
|
||||
|
||||
var moduleErrors []module.ModuleError
|
||||
|
||||
for moduleIndex, moduleDecl := range newConfig.Modules {
|
||||
|
||||
err := r.addModule(moduleDecl)
|
||||
if err != nil {
|
||||
if moduleErrors == nil {
|
||||
moduleErrors = []module.ModuleError{}
|
||||
}
|
||||
moduleErrors = append(moduleErrors, module.ModuleError{
|
||||
Index: moduleIndex,
|
||||
Config: moduleDecl,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var routeErrors []route.RouteError
|
||||
for routeIndex, routeDecl := range newConfig.Routes {
|
||||
err := r.addRoute(routeDecl)
|
||||
if err != nil {
|
||||
if routeErrors == nil {
|
||||
routeErrors = []route.RouteError{}
|
||||
}
|
||||
routeErrors = append(routeErrors, route.RouteError{
|
||||
Index: routeIndex,
|
||||
Config: routeDecl,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
r.runningConfig = newConfig
|
||||
r.startModules()
|
||||
|
||||
return moduleErrors, routeErrors
|
||||
}
|
||||
|
||||
@@ -149,8 +149,8 @@ func TestNewRouterDuplicateModuleId(t *testing.T) {
|
||||
t.Fatalf("router should have returned exactly 1 module error, got: %d", len(moduleErrors))
|
||||
}
|
||||
|
||||
if moduleErrors[0].Error.Error() != "module id already exists" {
|
||||
t.Fatalf("module error did not match expected, got: %s", moduleErrors[0].Error.Error())
|
||||
if moduleErrors[0].Error != "module id already exists" {
|
||||
t.Fatalf("module error did not match expected, got: %s", moduleErrors[0].Error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -184,8 +184,8 @@ func TestNewRouterRouteWithUnknwonProcessor(t *testing.T) {
|
||||
t.Fatalf("router should have returned exactly 1 route error, got: %d", len(routeErrors))
|
||||
}
|
||||
|
||||
if routeErrors[0].Error.Error() != "problem loading processor registration for processor type: asdfasdf" {
|
||||
t.Fatalf("route error did not match expected, got: %s", routeErrors[0].Error.Error())
|
||||
if routeErrors[0].Error != "problem loading processor registration for processor type: asdfasdf" {
|
||||
t.Fatalf("route error did not match expected, got: %s", routeErrors[0].Error)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,16 @@
|
||||
"description": "showbridge configuration",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"api": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"port": {
|
||||
"type": "integer",
|
||||
"description": "Port for the API server to listen on"
|
||||
}
|
||||
},
|
||||
"required": ["port"]
|
||||
},
|
||||
"modules": {
|
||||
"$ref": "https://showbridge.io/modules.schema.json"
|
||||
},
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535
|
||||
}
|
||||
},
|
||||
@@ -226,7 +226,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535,
|
||||
"default": 4222
|
||||
}
|
||||
@@ -305,7 +305,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535,
|
||||
"default": 5060
|
||||
},
|
||||
@@ -350,7 +350,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535,
|
||||
"default": 5060
|
||||
},
|
||||
@@ -436,9 +436,9 @@
|
||||
"default": "0.0.0.0"
|
||||
},
|
||||
"port": {
|
||||
"title" : "Port",
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535
|
||||
},
|
||||
"framing": {
|
||||
@@ -507,7 +507,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535
|
||||
}
|
||||
},
|
||||
@@ -540,7 +540,7 @@
|
||||
"port": {
|
||||
"title": "Port",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"minimum": 1024,
|
||||
"maximum": 65535
|
||||
}
|
||||
},
|
||||
|
||||
@@ -65,6 +65,29 @@
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Filter by Regex",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "filter.regex"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"title": "Pattern",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["pattern"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Parse Float",
|
||||
@@ -117,7 +140,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
"posX": {
|
||||
"title": "Position X",
|
||||
"title": "Position X",
|
||||
"type": "string"
|
||||
},
|
||||
"posY": {
|
||||
@@ -190,7 +213,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"method": {
|
||||
"title": "HTTP Method",
|
||||
"title": "HTTP Method",
|
||||
"type": "string",
|
||||
"enum": ["GET", "POST"]
|
||||
},
|
||||
@@ -245,9 +268,9 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base": {
|
||||
"title": "Base",
|
||||
"title": "Base",
|
||||
"type": "integer",
|
||||
"enum": [0,2, 8, 10, 16],
|
||||
"enum": [0, 2, 8, 10, 16],
|
||||
"default": 10
|
||||
},
|
||||
"bitSize": {
|
||||
@@ -255,7 +278,7 @@
|
||||
"type": "integer",
|
||||
"enum": [0, 8, 16, 32, 64],
|
||||
"default": 64
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -275,11 +298,11 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"min": {
|
||||
"title": "Minimum",
|
||||
"title": "Minimum",
|
||||
"type": "integer"
|
||||
},
|
||||
"max": {
|
||||
"title": "Maximum",
|
||||
"title": "Maximum",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
@@ -290,6 +313,41 @@
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Scale Int",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "int.scale"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"inMin": {
|
||||
"title": "Input Minimum",
|
||||
"type": "integer"
|
||||
},
|
||||
"inMax": {
|
||||
"title": "Input Maximum",
|
||||
"type": "integer"
|
||||
},
|
||||
"outMin": {
|
||||
"title": "Output Minimum",
|
||||
"type": "integer"
|
||||
},
|
||||
"outMax": {
|
||||
"title": "Output Maximum",
|
||||
"type": "integer"
|
||||
}
|
||||
},
|
||||
"required": ["inMin", "inMax", "outMin", "outMax"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Decode JSON",
|
||||
@@ -334,7 +392,7 @@
|
||||
"enum": ["NoteOn", "noteon", "note_on"]
|
||||
},
|
||||
"channel": {
|
||||
"title": "Channel",
|
||||
"title": "Channel",
|
||||
"type": "string"
|
||||
},
|
||||
"note": {
|
||||
@@ -471,7 +529,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"topic": {
|
||||
"title": "Topic",
|
||||
"title": "Topic",
|
||||
"type": "string"
|
||||
},
|
||||
"qos": {
|
||||
@@ -518,7 +576,7 @@
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"subject": {
|
||||
"title": "Subject",
|
||||
"title": "Subject",
|
||||
"type": "string"
|
||||
},
|
||||
"payload": {
|
||||
@@ -549,7 +607,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
"args": {
|
||||
"title": "Arguments",
|
||||
"title": "Arguments",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
@@ -591,6 +649,29 @@
|
||||
"required": ["type"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Router Input",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "router.input"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"source": {
|
||||
"title": "Source",
|
||||
"type": "string",
|
||||
"description": "source to report as to the router"
|
||||
}
|
||||
},
|
||||
"required": ["source"]
|
||||
}
|
||||
},
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Router Output",
|
||||
@@ -739,29 +820,6 @@
|
||||
"required": ["type"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Filter String",
|
||||
"properties": {
|
||||
"type": {
|
||||
"type": "string",
|
||||
"const": "string.filter"
|
||||
},
|
||||
"params": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"pattern": {
|
||||
"title": "Pattern",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": ["pattern"],
|
||||
"additionalProperties": false
|
||||
}
|
||||
},
|
||||
"required": ["type", "params"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"title": "Split String",
|
||||
|
||||
68
websocket.go
Normal file
68
websocket.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
func (r *Router) handleWebsocket(w http.ResponseWriter, req *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
r.logger.Error("websocket upgrade error", "error", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
r.wsConnsMu.Lock()
|
||||
r.wsConns = append(r.wsConns, conn)
|
||||
r.wsConnsMu.Unlock()
|
||||
READ_LOOP:
|
||||
for {
|
||||
messageType, message, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
_, ok := err.(*websocket.CloseError)
|
||||
if ok {
|
||||
break READ_LOOP
|
||||
}
|
||||
}
|
||||
|
||||
switch messageType {
|
||||
case websocket.TextMessage, websocket.BinaryMessage:
|
||||
event := Event{}
|
||||
err = json.Unmarshal(message, &event)
|
||||
if err != nil {
|
||||
r.logger.Error("websocket message unmarshal error", "error", err)
|
||||
continue
|
||||
}
|
||||
r.handleEvent(event, conn)
|
||||
case websocket.CloseMessage:
|
||||
break READ_LOOP
|
||||
case websocket.PingMessage:
|
||||
err = conn.WriteMessage(websocket.PongMessage, nil)
|
||||
if err != nil {
|
||||
r.logger.Error("websocket pong error", "error", err)
|
||||
}
|
||||
default:
|
||||
r.logger.Warn("unsupported websocket message type", "type", messageType)
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
//NOTE(jwetzell): remove ws connection
|
||||
r.wsConnsMu.Lock()
|
||||
for i, c := range r.wsConns {
|
||||
if c == conn {
|
||||
r.wsConns = append(r.wsConns[:i], r.wsConns[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
r.wsConnsMu.Unlock()
|
||||
}
|
||||
Reference in New Issue
Block a user