mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-08-10 17:03:38 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 68a943e141 |
@@ -1,10 +1,10 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
interval: 'weekly'
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
interval: "weekly"
|
||||
@@ -0,0 +1,27 @@
|
||||
config:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/config/**'
|
||||
|
||||
framer:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/framer/**'
|
||||
|
||||
module:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/module/**'
|
||||
|
||||
processor:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/processor/**'
|
||||
|
||||
router:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'router*'
|
||||
|
||||
route:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/route/**'
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cmd/showbridge/**'
|
||||
+1
-1
@@ -26,4 +26,4 @@ changelog:
|
||||
- cli
|
||||
- title: Other Changes
|
||||
labels:
|
||||
- "*"
|
||||
- '*'
|
||||
@@ -0,0 +1,18 @@
|
||||
# Taken from https://github.com/go-gitea/gitea
|
||||
name: Add labels to PR
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
jobs:
|
||||
labeler:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/labeler@634933edcd8ababfe52f92936142cc22ac488b1b # v6.0.1
|
||||
with:
|
||||
sync-labels: true
|
||||
@@ -4,296 +4,59 @@ on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
setup_release:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.set_version.outputs.version }}
|
||||
short_commit: ${{ steps.set_commit.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: set environment variables
|
||||
run: echo "SHOWBRIDGE_VERSION=${GITHUB_SHA::7}" >> $GITHUB_ENV
|
||||
- name: clean tag
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: echo "SHOWBRIDGE_VERSION=${SHOWBRIDGE_VERSION#v}" >> $GITHUB_ENV
|
||||
- name: set version
|
||||
id: set_version
|
||||
run: echo "version=${SHOWBRIDGE_VERSION}" >> $GITHUB_OUTPUT
|
||||
- name: set commit
|
||||
id: set_commit
|
||||
run: echo "short_commit=${GITHUB_SHA::7}" >> $GITHUB_OUTPUT
|
||||
- name: create release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
generate_release_notes: true
|
||||
build_webui:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup_release
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
repository: jwetzell/showbridge-webui
|
||||
ref: main
|
||||
|
||||
- name: Set up Node.js
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
cache: "npm"
|
||||
cache-dependency-path: "package-lock.json"
|
||||
|
||||
- name: Install Node.js dependencies
|
||||
run: npm ci
|
||||
|
||||
- run: npm run build -- --base-href=/ui/
|
||||
|
||||
- name: upload webui artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: dist/webui/
|
||||
|
||||
linux_amd64:
|
||||
runs-on: ubuntu-24.04
|
||||
needs: setup_release
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v7
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- name: install alsa lib
|
||||
run: sudo apt-get install -y libasound2-dev
|
||||
- name: get webui artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
go-version-file: 'go.mod'
|
||||
- name: release
|
||||
uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: internal/api/webui/
|
||||
- name: build
|
||||
run: |
|
||||
CGO_ENABLED=1 go build -o showbridge -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" ./cmd/showbridge
|
||||
tar -czf showbridge_${SHOWBRIDGE_VERSION}_linux-amd64.tar.gz showbridge
|
||||
- name: upload linux artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: showbridge-linux-amd64
|
||||
path: |
|
||||
showbridge_*.tar.gz
|
||||
- name: upload artifacts to release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
files: showbridge_*.tar.gz
|
||||
linux_arm64:
|
||||
runs-on: ubuntu-24.04-arm
|
||||
needs: setup_release
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- name: install alsa lib
|
||||
run: sudo apt-get install -y libasound2-dev
|
||||
- name: get webui artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: internal/api/webui/
|
||||
- name: build
|
||||
run: |
|
||||
CGO_ENABLED=1 go build -o showbridge -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" -tags=showbridge_webui ./cmd/showbridge
|
||||
tar -czf showbridge_${SHOWBRIDGE_VERSION}_linux-arm64.tar.gz showbridge
|
||||
- name: upload linux artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: showbridge-linux-arm64
|
||||
path: |
|
||||
showbridge_*.tar.gz
|
||||
- name: upload artifacts to release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
files: showbridge_*.tar.gz
|
||||
windows:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup_release
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- name: setup zig
|
||||
uses: mlugg/setup-zig@v2
|
||||
with:
|
||||
version: 0.16.0
|
||||
- name: get webui artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: internal/api/webui/
|
||||
- name: build amd64
|
||||
run: |
|
||||
CGO_ENABLED=1 GOOS=windows GOARCH=amd64 CC="zig cc -target x86_64-windows-gnu" CXX="zig c++ -target x86_64-windows-gnu" go build -o showbridge.exe -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" -tags=showbridge_webui ./cmd/showbridge
|
||||
zip showbridge_${SHOWBRIDGE_VERSION}_windows-amd64.zip showbridge.exe
|
||||
- name: build arm64
|
||||
run: |
|
||||
CGO_ENABLED=1 GOOS=windows GOARCH=arm64 CC="zig cc -target aarch64-windows-gnu" CXX="zig c++ -target aarch64-windows-gnu" go build -o showbridge.exe -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" -tags=showbridge_webui ./cmd/showbridge
|
||||
zip showbridge_${SHOWBRIDGE_VERSION}_windows-arm64.zip showbridge.exe
|
||||
- name: upload windows artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: showbridge-windows
|
||||
path: |
|
||||
showbridge_*.zip
|
||||
- name: upload artifacts to release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
files: showbridge_*.zip
|
||||
macos_arm64:
|
||||
runs-on: macos-26
|
||||
needs: setup_release
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- name: get webui artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: internal/api/webui/
|
||||
- name: build
|
||||
run: |
|
||||
CGO_ENABLED=1 GOOS=darwin GOARCH=arm64 go build -o showbridge -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" -tags=showbridge_webui ./cmd/showbridge
|
||||
tar -czf showbridge_${SHOWBRIDGE_VERSION}_macOS-arm64.tar.gz showbridge
|
||||
- name: upload macos artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: showbridge-macos-arm64
|
||||
path: |
|
||||
showbridge_*.tar.gz
|
||||
- name: upload artifacts to release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
files: showbridge_*.tar.gz
|
||||
macos_amd64:
|
||||
runs-on: macos-26-intel
|
||||
needs: [setup_release, build_webui]
|
||||
env:
|
||||
SHOWBRIDGE_VERSION: ${{ needs.setup_release.outputs.version }}
|
||||
SHORT_COMMIT: ${{ needs.setup_release.outputs.short_commit }}
|
||||
steps:
|
||||
- name: checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v7
|
||||
with:
|
||||
go-version-file: "go.mod"
|
||||
- name: get webui artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: showbridge-webui
|
||||
path: internal/api/webui/
|
||||
- name: build
|
||||
run: |
|
||||
CGO_ENABLED=1 GOOS=darwin GOARCH=amd64 go build -o showbridge -ldflags="-s -w -X main.version=${SHOWBRIDGE_VERSION}-${SHORT_COMMIT}" -tags=showbridge_webui ./cmd/showbridge
|
||||
tar -czf showbridge_${SHOWBRIDGE_VERSION}_macOS-amd64.tar.gz showbridge
|
||||
- name: upload macos artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: showbridge-macos-amd64
|
||||
path: |
|
||||
showbridge_*.tar.gz
|
||||
- name: upload artifacts to release
|
||||
uses: softprops/action-gh-release@v3
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch' && startsWith(github.ref, 'refs/tags/v')
|
||||
with:
|
||||
draft: true
|
||||
files: showbridge_*.tar.gz
|
||||
workdir: cmd/showbridge
|
||||
distribution: goreleaser
|
||||
version: "v2.13.0"
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
docker:
|
||||
runs-on: ubuntu-latest
|
||||
needs: setup_release
|
||||
if: github.ref_type == 'tag' && github.event_name != 'workflow_dispatch'
|
||||
needs: goreleaser
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
|
||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4.2.0
|
||||
uses: docker/setup-buildx-action@8d2750c68a42422c14e847fe6c8ac0403b4cbd6f # v3.12.0
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
uses: docker/login-action@c94ce9fb468520275223c153574b00df6fe4bcc9 # v3.7.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Setup Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@dc802804100637a589fabce1cb79ff13a1411302 # v6.2.0
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
with:
|
||||
images: |
|
||||
jwetzell/showbridge
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7.3.0
|
||||
uses: docker/build-push-action@10e90e3645eae34f1e60eeb005ba3a3d33f178e8 # v6.19.2
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
|
||||
@@ -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
|
||||
@@ -26,10 +26,10 @@ jobs:
|
||||
- name: Install alsa
|
||||
run: sudo apt-get install -y libasound2-dev
|
||||
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-go@v7
|
||||
- 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
|
||||
|
||||
@@ -37,7 +37,7 @@ jobs:
|
||||
run: go test ./... -count=1 -coverpkg "github.com/jwetzell/showbridge-go/..." -coverprofile coverage.out
|
||||
|
||||
- name: clean up coverage report
|
||||
run: cat coverage.out | grep -v "github.com/jwetzell/showbridge-go/cmd" > coverage.nocmd.out
|
||||
run: cat coverage.out | grep -v "github.com/jwetzell/showbridge-go/cmd" > coverage.nocmd.out
|
||||
- name: Update coverage report
|
||||
uses: ncruces/go-coverage-report@v0.3.2
|
||||
with:
|
||||
@@ -45,5 +45,5 @@ jobs:
|
||||
report: true
|
||||
chart: true
|
||||
amend: true
|
||||
if: github.event_name == 'push'
|
||||
if: github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
|
||||
Vendored
+17
-16
@@ -1,17 +1,18 @@
|
||||
{
|
||||
// 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": "./"
|
||||
}
|
||||
]
|
||||
}
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
ARG GO_VERSION=1.26.3
|
||||
ARG GO_VERSION=1.25.5
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
RUN apk --no-cache add ca-certificates tzdata git
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
WORKDIR /build
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
# showbridge (go edition)
|
||||
|
||||
[](https://raw.githack.com/wiki/jwetzell/showbridge-go/coverage.html)
|
||||
|
||||
Simple protocol router _/s_
|
||||
|
||||
</div>
|
||||
@@ -13,7 +14,6 @@ Simple protocol router _/s_
|
||||
</p>
|
||||
|
||||
### Supported Protocols
|
||||
|
||||
- HTTP
|
||||
- UDP
|
||||
- TCP
|
||||
@@ -25,8 +25,7 @@ Simple protocol router _/s_
|
||||
- [OSC](https://opensoundcontrol.stanford.edu/spec-1_0.html)
|
||||
- [FreeD](https://ptzoptics.com/freed/)
|
||||
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
||||
- [Redis](https://redis.io/)
|
||||
|
||||
|
||||
### CLI Usage
|
||||
|
||||
```
|
||||
@@ -37,9 +36,9 @@ USAGE:
|
||||
showbridge [global options]
|
||||
|
||||
GLOBAL OPTIONS:
|
||||
--config string path to config file (default: "./config.yaml") [$SHOWBRIDGE_CONFIG]
|
||||
--log-level string set log level (default: "info") [$SHOWBRIDGE_LOG_LEVEL]
|
||||
--log-format string log format to use (default: "text") [$SHOWBRIDGE_LOG_FORMAT]
|
||||
--config string path to config file (default: "./config.yaml")
|
||||
--log-level string set log level (default: "info")
|
||||
--log-format string log format to use (default: "text")
|
||||
--help, -h show help
|
||||
--version, -v print the version
|
||||
```
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
# Added by goreleaser init:
|
||||
dist/
|
||||
@@ -0,0 +1,33 @@
|
||||
version: 2
|
||||
project_name: showbridge
|
||||
before:
|
||||
hooks:
|
||||
- go mod tidy
|
||||
|
||||
builds:
|
||||
- env:
|
||||
- CGO_ENABLED=0
|
||||
goos:
|
||||
- linux
|
||||
- windows
|
||||
- darwin
|
||||
goarch:
|
||||
- "amd64"
|
||||
- "arm64"
|
||||
ldflags:
|
||||
- '-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}'
|
||||
|
||||
archives:
|
||||
- formats: [tar.gz]
|
||||
name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}-{{ .Arch }}"
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats: [zip]
|
||||
|
||||
changelog:
|
||||
sort: asc
|
||||
use: github-native
|
||||
|
||||
release:
|
||||
draft: true
|
||||
replace_existing_draft: true
|
||||
+93
-92
@@ -2,7 +2,6 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -14,8 +13,12 @@ import (
|
||||
|
||||
"github.com/jwetzell/showbridge-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/schema"
|
||||
"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"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
@@ -31,10 +34,9 @@ func main() {
|
||||
Version: version,
|
||||
Flags: []cli.Flag{
|
||||
&cli.StringFlag{
|
||||
Name: "config",
|
||||
Value: "./config.yaml",
|
||||
Usage: "path to config file",
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_CONFIG"),
|
||||
Name: "config",
|
||||
Value: "./config.yaml",
|
||||
Usage: "path to config file",
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-level",
|
||||
@@ -47,7 +49,6 @@ func main() {
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_LOG_LEVEL"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-format",
|
||||
@@ -60,7 +61,11 @@ func main() {
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_LOG_FORMAT"),
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "trace",
|
||||
Value: false,
|
||||
Usage: "enable OpenTelemetry tracing",
|
||||
},
|
||||
},
|
||||
Action: run,
|
||||
@@ -79,11 +84,12 @@ func main() {
|
||||
}
|
||||
|
||||
type showbridgeApp struct {
|
||||
ctx context.Context
|
||||
configPath string
|
||||
logger *slog.Logger
|
||||
router *showbridge.Router
|
||||
routerMutex sync.Mutex
|
||||
ctx context.Context
|
||||
configPath string
|
||||
logger *slog.Logger
|
||||
router *showbridge.Router
|
||||
routerRunner *sync.WaitGroup
|
||||
routerMutex sync.Mutex
|
||||
}
|
||||
|
||||
func readConfig(configPath string) (config.Config, error) {
|
||||
@@ -95,31 +101,7 @@ func readConfig(configPath string) (config.Config, error) {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
//TODO(jwetzell): this is an annoying amount of marshaling
|
||||
|
||||
yamlMap := make(map[string]any)
|
||||
|
||||
err = yaml.Unmarshal(configBytes, &yamlMap)
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
err = schema.ApplyDefaults(&yamlMap)
|
||||
if err != nil {
|
||||
return config.Config{}, fmt.Errorf("failed to apply defaults: %w", err)
|
||||
}
|
||||
|
||||
err = schema.ValidateConfig(yamlMap)
|
||||
if err != nil {
|
||||
return config.Config{}, fmt.Errorf("failed to validate config: %w", err)
|
||||
}
|
||||
|
||||
validatedConfigBytes, err := json.Marshal(yamlMap)
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
err = json.Unmarshal(validatedConfigBytes, &cfg)
|
||||
err = yaml.Unmarshal(configBytes, &cfg)
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
@@ -127,27 +109,13 @@ 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, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
return errors.New("config path cannot be empty")
|
||||
}
|
||||
|
||||
var logLevel slog.Level
|
||||
logLevel := slog.LevelInfo
|
||||
|
||||
logLevelFromFlag := c.String("log-level")
|
||||
|
||||
@@ -185,75 +153,82 @@ func run(ctx context.Context, c *cli.Command) error {
|
||||
|
||||
slog.SetDefault(slog.New(logHandler))
|
||||
|
||||
if c.Bool("trace") {
|
||||
exporter, err := otlptracehttp.New(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create trace exporter: %w", err)
|
||||
}
|
||||
|
||||
tracerProvider := newTracerProvider(exporter)
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
defer tracerProvider.Shutdown(ctx)
|
||||
|
||||
otel.SetTracerProvider(tracerProvider)
|
||||
}
|
||||
|
||||
showbridgeApp := &showbridgeApp{
|
||||
ctx: ctx,
|
||||
configPath: configPath,
|
||||
logger: slog.Default().With("component", "cmd"),
|
||||
ctx: ctx,
|
||||
configPath: configPath,
|
||||
logger: slog.Default().With("component", "cmd"),
|
||||
routerRunner: &sync.WaitGroup{},
|
||||
}
|
||||
|
||||
config, err := readConfig(showbridgeApp.configPath)
|
||||
router, err := showbridgeApp.getNewRouter()
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("failed to initialize router: %w", err)
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
showbridgeApp.logConfigErrors(moduleErrors, routeErrors)
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
showbridgeApp.routerMutex.Lock()
|
||||
showbridgeApp.router = router
|
||||
|
||||
router.Start(context.Background())
|
||||
showbridgeApp.routerRunner.Go(func() {
|
||||
router.Start(context.Background())
|
||||
})
|
||||
showbridgeApp.routerMutex.Unlock()
|
||||
|
||||
go showbridgeApp.handleChannels()
|
||||
go showbridgeApp.handleHangup()
|
||||
|
||||
<-showbridgeApp.ctx.Done()
|
||||
showbridgeApp.logger.Debug("shutting down router")
|
||||
showbridgeApp.router.Stop()
|
||||
showbridgeApp.logger.Debug("waiting for router to exit")
|
||||
showbridgeApp.routerRunner.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) handleChannels() {
|
||||
func (app *showbridgeApp) handleHangup() {
|
||||
for {
|
||||
select {
|
||||
case <-sigHangup:
|
||||
app.logger.Info("received SIGHUP, reloading configuration")
|
||||
newRouter, err := app.getNewRouter()
|
||||
if err != nil {
|
||||
app.logger.Error("failed to reload configuration", "error", err)
|
||||
continue
|
||||
}
|
||||
app.routerMutex.Lock()
|
||||
config, err := readConfig(app.configPath)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to read config file", "error", err)
|
||||
app.routerMutex.Unlock()
|
||||
continue
|
||||
}
|
||||
moduleErrors, routeErrors, err := app.router.UpdateConfig(config, false)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to update router config", "error", err)
|
||||
app.routerMutex.Unlock()
|
||||
continue
|
||||
}
|
||||
app.logConfigErrors(moduleErrors, routeErrors)
|
||||
app.router.Stop()
|
||||
app.routerRunner.Wait()
|
||||
app.router = newRouter
|
||||
app.routerRunner.Go(func() {
|
||||
app.router.Start(context.Background())
|
||||
})
|
||||
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) logConfigErrors(moduleErrors []config.ModuleError, routeErrors []config.RouteError) {
|
||||
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)
|
||||
|
||||
for _, moduleError := range moduleErrors {
|
||||
app.logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
@@ -261,4 +236,30 @@ func (app *showbridgeApp) logConfigErrors(moduleErrors []config.ModuleError, rou
|
||||
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 {
|
||||
r, err := resource.Merge(
|
||||
resource.Default(),
|
||||
resource.NewWithAttributes(
|
||||
semconv.SchemaURL,
|
||||
semconv.ServiceName("showbridge"),
|
||||
semconv.ServiceVersion(version),
|
||||
),
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return sdktrace.NewTracerProvider(
|
||||
sdktrace.WithBatcher(exp),
|
||||
sdktrace.WithResource(r),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"reflect"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
func (r *Router) GetRunningConfig() config.Config {
|
||||
r.runningConfigMu.RLock()
|
||||
defer r.runningConfigMu.RUnlock()
|
||||
return r.runningConfig
|
||||
}
|
||||
|
||||
func (r *Router) UpdateConfig(newConfig config.Config, triggerChangeChan bool) ([]config.ModuleError, []config.RouteError, error) {
|
||||
if !r.runningConfigMu.TryLock() {
|
||||
return nil, nil, errors.New("config update in progress")
|
||||
}
|
||||
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.apiServer.Stop()
|
||||
r.apiServer.Start(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]common.Module)
|
||||
r.RouteInstances = []*route.Route{}
|
||||
|
||||
var moduleErrors []config.ModuleError
|
||||
|
||||
for moduleIndex, moduleDecl := range newConfig.Modules {
|
||||
|
||||
err := r.addModule(moduleDecl)
|
||||
if err != nil {
|
||||
if moduleErrors == nil {
|
||||
moduleErrors = []config.ModuleError{}
|
||||
}
|
||||
moduleErrors = append(moduleErrors, config.ModuleError{
|
||||
Index: moduleIndex,
|
||||
Config: moduleDecl,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
var routeErrors []config.RouteError
|
||||
for routeIndex, routeDecl := range newConfig.Routes {
|
||||
err := r.addRoute(routeDecl)
|
||||
if err != nil {
|
||||
if routeErrors == nil {
|
||||
routeErrors = []config.RouteError{}
|
||||
}
|
||||
routeErrors = append(routeErrors, config.RouteError{
|
||||
Index: routeIndex,
|
||||
Config: routeDecl,
|
||||
Error: err.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
}
|
||||
r.runningConfig = newConfig
|
||||
r.startModules()
|
||||
|
||||
if triggerChangeChan {
|
||||
r.ConfigChange <- newConfig
|
||||
}
|
||||
|
||||
return moduleErrors, routeErrors, nil
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
api:
|
||||
enabled: true
|
||||
port: 8080
|
||||
modules:
|
||||
- id: sqlite
|
||||
type: db.sqlite
|
||||
params:
|
||||
dsn: ":memory:"
|
||||
- id: httpin
|
||||
type: http.server
|
||||
params:
|
||||
port: 3000
|
||||
- id: tcpout
|
||||
type: net.tcp.client
|
||||
params:
|
||||
host: "localhost"
|
||||
port: 9000
|
||||
framing: "RAW"
|
||||
- id: tcpin
|
||||
type: net.tcp.server
|
||||
params:
|
||||
port: 9000
|
||||
framing: "RAW"
|
||||
- id: ticker
|
||||
type: time.interval
|
||||
params:
|
||||
duration: 1000
|
||||
- id: udpout
|
||||
type: net.udp.client
|
||||
params:
|
||||
host: "localhost"
|
||||
port: 9001
|
||||
- id: udpin
|
||||
type: net.udp.server
|
||||
params:
|
||||
port: 9001
|
||||
- id: wsecho
|
||||
type: websocket.client
|
||||
params:
|
||||
url: "wss://echo.websocket.org"
|
||||
- id: natsserver
|
||||
type: nats.server
|
||||
params:
|
||||
port: 4222
|
||||
- id: natsout
|
||||
type: nats.client
|
||||
params:
|
||||
url: "nats://localhost:4222"
|
||||
subject: "hello"
|
||||
- id: natsin
|
||||
type: nats.client
|
||||
params:
|
||||
url: "nats://localhost:4222"
|
||||
subject: "test"
|
||||
routes:
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: string.create
|
||||
params:
|
||||
template: "wsecho: {{.Payload.UnixMilli}}"
|
||||
- type: module.output
|
||||
params:
|
||||
module: wsecho
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: string.create
|
||||
params:
|
||||
template: "tcpout: {{.Payload.UnixMilli}}"
|
||||
- type: string.encode
|
||||
- type: module.output
|
||||
params:
|
||||
module: tcpout
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: string.create
|
||||
params:
|
||||
template: "udpout: {{.Payload.UnixMilli}}"
|
||||
- type: string.encode
|
||||
- type: module.output
|
||||
params:
|
||||
module: udpout
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: http.request.do
|
||||
params:
|
||||
url: "http://localhost:3000/echo"
|
||||
method: "GET"
|
||||
- type: struct.field.get
|
||||
params:
|
||||
name: "Body"
|
||||
- type: string.decode
|
||||
- type: debug.log
|
||||
- input: tcpin
|
||||
processors:
|
||||
- type: string.decode
|
||||
- type: debug.log
|
||||
- input: udpin
|
||||
processors:
|
||||
- type: string.decode
|
||||
- type: debug.log
|
||||
- input: wsecho
|
||||
processors:
|
||||
- type: debug.log
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: db.query
|
||||
params:
|
||||
module: "sqlite"
|
||||
query: "SELECT 1;"
|
||||
- type: debug.log
|
||||
- input: natsin
|
||||
processors:
|
||||
- type: struct.field.get
|
||||
params:
|
||||
name: "Data"
|
||||
- type: string.decode
|
||||
- type: debug.log
|
||||
- input: httpin
|
||||
processors:
|
||||
- type: http.response.create
|
||||
params:
|
||||
status: 200
|
||||
bodyTemplate: "Hello, World!"
|
||||
- type: module.output
|
||||
params:
|
||||
module: httpin
|
||||
- input: ticker
|
||||
processors:
|
||||
- type: string.create
|
||||
params:
|
||||
template: "natsout: {{.Payload}}"
|
||||
- type: pubsub.publish
|
||||
params:
|
||||
module: natsout
|
||||
topic: "test"
|
||||
+2
-7
@@ -1,6 +1,3 @@
|
||||
api:
|
||||
enabled: true
|
||||
port: 8080
|
||||
modules:
|
||||
- id: http
|
||||
type: http.server
|
||||
@@ -16,8 +13,6 @@ routes:
|
||||
processors:
|
||||
- type: osc.message.create
|
||||
params:
|
||||
address: "{{.Payload.URL.Path}}"
|
||||
address: "{{.URL.Path}}"
|
||||
- type: osc.message.encode
|
||||
- type: module.output
|
||||
params:
|
||||
module: udp
|
||||
output: udp
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
func (r *Router) HandleEvent(event common.Event, sender common.EventDestination) {
|
||||
switch event.Type {
|
||||
case "ping":
|
||||
r.unicastEvent(common.Event{Type: "pong", Data: map[string]any{
|
||||
"timestamp": time.Now().UnixMilli(),
|
||||
}}, sender)
|
||||
default:
|
||||
r.logger.Warn("unknown event type", "eventType", event.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) AddEventDestination(dest common.EventDestination) {
|
||||
r.eventDestinationsMu.Lock()
|
||||
defer r.eventDestinationsMu.Unlock()
|
||||
r.eventDestinations = append(r.eventDestinations, dest)
|
||||
}
|
||||
|
||||
func (r *Router) RemoveEventDestination(dest common.EventDestination) {
|
||||
r.eventDestinationsMu.Lock()
|
||||
defer r.eventDestinationsMu.Unlock()
|
||||
for i, d := range r.eventDestinations {
|
||||
if d.Is(dest) {
|
||||
r.eventDestinations = append(r.eventDestinations[:i], r.eventDestinations[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) unicastEvent(event common.Event, dest common.EventDestination) {
|
||||
err := dest.Send(event)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to send event", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) broadcastEvent(event common.Event) {
|
||||
r.eventDestinationsMu.Lock()
|
||||
defer r.eventDestinationsMu.Unlock()
|
||||
for _, dest := range r.eventDestinations {
|
||||
err := dest.Send(event)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to send event", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,76 +1,88 @@
|
||||
module github.com/jwetzell/showbridge-go
|
||||
|
||||
go 1.26.3
|
||||
go 1.25.5
|
||||
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/emiago/diago v0.31.0
|
||||
github.com/emiago/sipgo v1.4.3
|
||||
github.com/emiago/diago v0.27.0
|
||||
github.com/emiago/sipgo v1.2.0
|
||||
github.com/expr-lang/expr v1.17.8
|
||||
github.com/extism/go-sdk v1.7.1
|
||||
github.com/google/jsonschema-go v0.4.3
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jwetzell/artnet-go v0.3.0
|
||||
github.com/jwetzell/free-d-go v0.2.0
|
||||
github.com/jwetzell/osc-go v0.3.0
|
||||
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.14.4
|
||||
github.com/nats-io/nats.go v1.52.0
|
||||
github.com/redis/go-redis/v9 v9.21.0
|
||||
github.com/urfave/cli/v3 v3.10.1
|
||||
gitlab.com/gomidi/midi/v2 v2.3.24
|
||||
go.bug.st/serial v1.8.0
|
||||
golang.org/x/time v0.15.0
|
||||
modernc.org/quickjs v0.22.0
|
||||
modernc.org/sqlite v1.55.0
|
||||
github.com/nats-io/nats-server/v2 v2.12.4
|
||||
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
|
||||
modernc.org/quickjs v0.17.1
|
||||
sigs.k8s.io/yaml v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op // indirect
|
||||
github.com/antithesishq/antithesis-sdk-go v0.5.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
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 // indirect
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 // indirect
|
||||
github.com/go-audio/riff v1.0.0 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
github.com/gobwas/glob v0.2.3 // indirect
|
||||
github.com/gobwas/httphead v0.1.0 // indirect
|
||||
github.com/gobwas/pool v0.2.1 // indirect
|
||||
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/ianlancetaylor/demangle v0.0.0-20260505044615-1ff4bf46051f // 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.19.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||
github.com/minio/highwayhash v1.0.4 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.2 // indirect
|
||||
github.com/nats-io/nkeys v0.4.16 // indirect
|
||||
github.com/klauspost/compress v1.18.3 // 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/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.16 // indirect
|
||||
github.com/pion/rtp v1.10.2 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||
github.com/pion/rtp v1.8.26 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.9 // indirect
|
||||
github.com/pion/transport/v3 v3.1.1 // indirect
|
||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/rogpeppe/go-internal v1.14.1 // indirect
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.11.0 // indirect
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/zaf/g711 v1.4.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 // indirect
|
||||
go.uber.org/atomic v1.11.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/proto/otlp v1.9.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/net v0.56.0 // indirect
|
||||
golang.org/x/sync v0.21.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // 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/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/text v0.34.0 // indirect
|
||||
golang.org/x/time v0.14.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/protobuf v1.36.11 // indirect
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 // indirect
|
||||
modernc.org/libc v1.74.3 // indirect
|
||||
modernc.org/libquickjs v0.12.10 // indirect
|
||||
modernc.org/libc v1.67.1 // indirect
|
||||
modernc.org/libquickjs v0.12.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
@@ -1,31 +1,36 @@
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op h1:p2zFsAzvhIpFya8AIOHIbWf7NGvO34QpLGclyf7nXj8=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.7.2-default-no-op/go.mod h1:FQyySiasQQM8735Ddel3MRojmy4dA1IqCeyJ5jmPMbI=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||
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/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=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/creack/goselect v0.1.2 h1:2DNy14+JPjRBgPzAd1thbQp4BSIihxcBf0IXhQXDRa0=
|
||||
github.com/creack/goselect v0.1.2/go.mod h1:a/NhLweNvqIYMuxcMOuWY516Cimucms3DglDzQP3hKY=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1 h1:idfl8M8rPW93NehFw5H1qqH8yG158t5POr+LX9avbJY=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240828172851-9145d8ad07e1/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a h1:UwSIFv5g5lIvbGgtf3tVwC7Ky9rmMFBp0RMs+6f6YqE=
|
||||
github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1 h1:/VSOv3oDLlpqR2Epjn1Q7b2bSTplJIeV2ISgCl2W7nE=
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1/go.mod h1:1/yJCneuyOoCOzKSsOTUc0AJfpsItBGWvYpBLimhArU=
|
||||
github.com/emiago/diago v0.31.0 h1:w/GZQnMS60EBANKXMnf/MjFDlUfcfHLPOlEKiZkaNe0=
|
||||
github.com/emiago/diago v0.31.0/go.mod h1:CP7p9/aBZG/fQEYdtGdQkCblr1jLr1zbxODcu8MryVU=
|
||||
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.4.3 h1:Ju1Ilp0LhTcSHCyp2jBYAQDQ8TAwuxQHzT1IhO6jSIY=
|
||||
github.com/emiago/sipgo v1.4.3/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
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/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=
|
||||
github.com/extism/go-sdk v1.7.1/go.mod h1:IT+Xdg5AZM9hVtpFUA+uZCJMge/hbvshl8bwzLtFyKA=
|
||||
github.com/go-audio/riff v1.0.0 h1:d8iCGbDvox9BfLagY94fBynxSPHO80LmZCaOsmKxokA=
|
||||
github.com/go-audio/riff v1.0.0/go.mod h1:l3cQwc85y79NQFCRB7TiPoNiaijp6q8Z0Uv38rVG498=
|
||||
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
|
||||
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
|
||||
github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
|
||||
github.com/gobwas/httphead v0.1.0 h1:exrUm0f4YX0L7EBwZHuCF4GDp8aJfVeBrlLQrs6NqWU=
|
||||
@@ -34,52 +39,50 @@ github.com/gobwas/pool v0.2.1 h1:xfeeEhW7pwmX8nuLVlqbzVc7udMDrwetjEv+TZIz1og=
|
||||
github.com/gobwas/pool v0.2.1/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw=
|
||||
github.com/gobwas/ws v1.4.0 h1:CTaoG1tojrh4ucGPcoJFiAQUAsEWekEWvLy7GsVNqGs=
|
||||
github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakrc=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=
|
||||
github.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=
|
||||
github.com/google/jsonschema-go v0.4.3 h1:/DBOLZTfDow7pe2GmaJNhltueGTtDKICi8V8p+DQPd0=
|
||||
github.com/google/jsonschema-go v0.4.3/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20260505044615-1ff4bf46051f h1:NW3E2QSchEk63/fjeEvWOa2cE02FSv9ox//VE/N4c8g=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20260505044615-1ff4bf46051f/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca h1:T54Ema1DU8ngI+aef9ZhAhNGQhcRTrWxVeG07F+c/Rw=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca/go.mod h1:gx7rwoVhcfuVKG5uya9Hs3Sxj7EIvldVofAWIUtGouw=
|
||||
github.com/icholy/digest v1.1.0 h1:HfGg9Irj7i+IX1o1QAmPfIBNu/Q5A5Tu3n/MED9k9H4=
|
||||
github.com/icholy/digest v1.1.0/go.mod h1:QNrsSGQ5v7v9cReDI0+eyjsXGUoRSUZQHeQ5C4XLa0Y=
|
||||
github.com/jwetzell/artnet-go v0.3.0 h1:MDHElOSbpgmIbYGHO9SoxsT7ynrYtV5/UHGT82geHk0=
|
||||
github.com/jwetzell/artnet-go v0.3.0/go.mod h1:zqRsSsrd6rPwJacwscPteDqGIqevjZ3Z6dpp092VJ1w=
|
||||
github.com/jwetzell/free-d-go v0.2.0 h1:8WQW4du8Sf3d18aUzk9n5jZtHE6WdDQHDFjkFffvycc=
|
||||
github.com/jwetzell/free-d-go v0.2.0/go.mod h1:yHuRy51NeDfN26eJ6wzZgys8qyQiS7hkYILw8yF+UJ4=
|
||||
github.com/jwetzell/osc-go v0.3.0 h1:z75TxuQSEmdcmZ56OAepkDa3m88SdZh//3m4nBb/XZI=
|
||||
github.com/jwetzell/osc-go v0.3.0/go.mod h1:kCs329JxY6Qjga08tRQ/Gl0PqhgQzLIMpOhm6uszvIc=
|
||||
github.com/jwetzell/artnet-go v0.2.1 h1:iYTKWcwYrF5kBkYfkw2UbWvoueeA23iKEn7fR27mWZE=
|
||||
github.com/jwetzell/artnet-go v0.2.1/go.mod h1:gli97Z32a0kMkZ6taoTiK7/lqHcF/dhiGjGJdx/PxqA=
|
||||
github.com/jwetzell/free-d-go v0.1.0 h1:xHt6dvyit98X+OC3jVzV0aLidxbyzi3vI9QiYkteEtA=
|
||||
github.com/jwetzell/free-d-go v0.1.0/go.mod h1:KmrkooRARRaxJTBSPvwt/6IMAIaHH1R8bSA8cwbbELw=
|
||||
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.19.0 h1:sXLILfc9jV2QYWkzFOPWStmcUVH2RHEB1JCdY2oVvCQ=
|
||||
github.com/klauspost/compress v1.19.0/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
|
||||
github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/compress v1.18.3 h1:9PJRvfbmTabkOX8moIpXPbMMbYN60bWImDDU7L+/6zw=
|
||||
github.com/klauspost/compress v1.18.3/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=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4=
|
||||
github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
|
||||
github.com/minio/highwayhash v1.0.4 h1:asJizugGgchQod2ja9NJlGOWq4s7KsAWr5XUc9Clgl4=
|
||||
github.com/minio/highwayhash v1.0.4/go.mod h1:GGYsuwP/fPD6Y9hMiXuapVvlIUEhFhMTh0rxU3ik1LQ=
|
||||
github.com/nats-io/jwt/v2 v2.8.2 h1:XXRgB60MSTnqsRwejQurVDs/hcv2dkt+86GjI+I/bMc=
|
||||
github.com/nats-io/jwt/v2 v2.8.2/go.mod h1:Ag/56sq9OblL4JgdYufDd16Egb17Kr/8WwwuO/forVc=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4 h1:efgjZ8cdExAKRuqSg8UPJFprb+l7NlBtSDPhDlw3rO4=
|
||||
github.com/nats-io/nats-server/v2 v2.14.4/go.mod h1:BltdpOYestjbtQSnVO2zGHdg5SGBZjt+GYTgB9LZq/I=
|
||||
github.com/nats-io/nats.go v1.52.0 h1:n3avV4VBsCgsdwh71TppsTwtv+QdPs7ntSKM8qJLGsc=
|
||||
github.com/nats-io/nats.go v1.52.0/go.mod h1:26HypzazeOkyO3/mqd1zZd53STJN0EjCYF9Uy2ZOBno=
|
||||
github.com/nats-io/nkeys v0.4.16 h1:rd5oAuLOb8mnAycB0xleuEBNS1pVVnN0fv/FF34Eypg=
|
||||
github.com/nats-io/nkeys v0.4.16/go.mod h1:llLgWoI0o4z/Q57q2R1kHfmocyhGV6VG/U18Glg1Afs=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 h1:KGuD/pM2JpL9FAYvBrnBBeENKZNh6eNtjqytV6TYjnk=
|
||||
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.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/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=
|
||||
@@ -90,16 +93,16 @@ github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
|
||||
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
|
||||
github.com/pion/rtp v1.10.2 h1:l+f6tTDcAH6xwepaAoW791ddhuYsJlqRATOzirO04Mo=
|
||||
github.com/pion/rtp v1.10.2/go.mod h1:Au8fc6cEByy8RLTwKTQTEeQqDB/SJDxwL4mZuxYA5Pk=
|
||||
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
|
||||
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
||||
github.com/pion/rtp v1.8.26 h1:VB+ESQFQhBXFytD+Gk8cxB6dXeVf2WQzg4aORvAvAAc=
|
||||
github.com/pion/rtp v1.8.26/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
|
||||
github.com/pion/srtp/v3 v3.0.9 h1:lRGF4G61xxj+m/YluB3ZnBpiALSri2lTzba0kGZMrQY=
|
||||
github.com/pion/srtp/v3 v3.0.9/go.mod h1:E+AuWd7Ug2Fp5u38MKnhduvpVkveXJX6J4Lq4rxUYt8=
|
||||
github.com/pion/transport/v3 v3.1.1 h1:Tr684+fnnKlhPceU+ICdrw6KKkTms+5qHMgw6bIkYOM=
|
||||
github.com/pion/transport/v3 v3.1.1/go.mod h1:+c2eewC5WJQHiAA46fkMMzoYZSuGzA/7E2FPrOYHctQ=
|
||||
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E=
|
||||
github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
@@ -108,42 +111,68 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZjBaFj3HgFonKXUcwgJ4djLb6i42S3Q=
|
||||
github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk=
|
||||
github.com/tetratelabs/wazero v1.11.0 h1:+gKemEuKCTevU4d7ZTzlsvgd1uaToIDtlQlmNbwqYhA=
|
||||
github.com/tetratelabs/wazero v1.11.0/go.mod h1:eV28rsN8Q+xwjogd7f4/Pp4xFxO7uOGbLcD/LzB1wiU=
|
||||
github.com/urfave/cli/v3 v3.10.1 h1:7Kx9H50hrHbRbyxgO1KP6/BcbiGRz0uYh5YyQ30JEEY=
|
||||
github.com/urfave/cli/v3 v3.10.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/tetratelabs/wazero v1.9.0 h1:IcZ56OuxrtaEz8UYNRHBrUa9bYeX9oVY93KspZZBf/I=
|
||||
github.com/tetratelabs/wazero v1.9.0/go.mod h1:TSbcXCfFP0L2FGkRPxHphadXPjo1T6W+CseNNY7EkjM=
|
||||
github.com/urfave/cli/v3 v3.7.0 h1:AGSnbUyjtLiM+WJUb4dzXKldl/gL+F8OwmRDtVr6g2U=
|
||||
github.com/urfave/cli/v3 v3.7.0/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
github.com/zaf/g711 v1.4.0 h1:XZYkjjiAg9QTBnHqEg37m2I9q3IIDv5JRYXs2N8ma7c=
|
||||
github.com/zaf/g711 v1.4.0/go.mod h1:eCDXt3dSp/kYYAoooba7ukD/Q75jvAaS4WOMr0l1Roo=
|
||||
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.24 h1:afkq5nhlzKvZaj9QK80YbK8tH3lIlKLnPPP9HxxD7Do=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.24/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
go.bug.st/serial v1.8.0 h1:ZtnmN8aYXtPlTghwSvDWPHKBHL9TM6oFDa+KpSn4SQE=
|
||||
go.bug.st/serial v1.8.0/go.mod h1:d0MmS16Qt9b1m06yoYRNUXhRRTJV5Qg2S5EKqQtnayQ=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=
|
||||
go.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23 h1:P8NxV4EzV9c+BjpwTeB+G/qa+Xdq/UTazS2fKxY0O0g=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
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/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=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
|
||||
golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
|
||||
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/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.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
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.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
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/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/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=
|
||||
gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 h1:JLQynH/LBHfCTSbDWl+py8C+Rg/k1OVH3xfcaiANuF0=
|
||||
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/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=
|
||||
@@ -155,34 +184,32 @@ gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=
|
||||
gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=
|
||||
modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI=
|
||||
modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/cc/v4 v4.27.1 h1:9W30zRlYrefrDV2JE2O8VDtJ1yPGownxciz5rrbQZis=
|
||||
modernc.org/cc/v4 v4.27.1/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.30.1 h1:4r4U1J6Fhj98NKfSjnPUN7Ze2c6MnAdL0hWw6+LrJpc=
|
||||
modernc.org/ccgo/v4 v4.30.1/go.mod h1:bIOeI1JL54Utlxn+LwrFyjCx2n2RDiYEaJVSrgdrRfM=
|
||||
modernc.org/fileutil v1.3.40 h1:ZGMswMNc9JOCrcrakF1HrvmergNLAmxOPjizirpfqBA=
|
||||
modernc.org/fileutil v1.3.40/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/gc/v3 v3.1.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
|
||||
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.3 h1:a4J+Z8aVaxPyjyxRAdJzw246PqpcFGvVPnfT/AuM5Ws=
|
||||
modernc.org/libc v1.74.3/go.mod h1:4H7h/MJ8wnjL8RAbp9v3OXgnk22X7MouHIhDbvP3gj4=
|
||||
modernc.org/libquickjs v0.12.10 h1:nhfXth/BywJmx3Flid/r7iQYdPzc/+B4LDigA9YIKtQ=
|
||||
modernc.org/libquickjs v0.12.10/go.mod h1:UedJnNW5BS4PbItZnk0Zg4tUI7m0ImmmtJAI3yqoF30=
|
||||
modernc.org/libc v1.67.1 h1:bFaqOaa5/zbWYJo8aW0tXPX21hXsngG2M7mckCnFSVk=
|
||||
modernc.org/libc v1.67.1/go.mod h1:QvvnnJ5P7aitu0ReNpVIEyesuhmDLQ8kaEoyMjIFZJA=
|
||||
modernc.org/libquickjs v0.12.3 h1:2IU9B6njBmce2PuYttJDkXeoLRV9WnvgP+eU5HAC8YI=
|
||||
modernc.org/libquickjs v0.12.3/go.mod h1:iCsgVxnHTX3i0YPxxHBmJk0GLA5sVUHXWI/090UXgeE=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/quickjs v0.22.0 h1:4YhaspgX4Nc+YN84ZTQdlVMnQCY7M5GloF+D+UvEg7I=
|
||||
modernc.org/quickjs v0.22.0/go.mod h1:kRfDSgneM1WAd/niu2O3tqpTy+HB6+25DmTNKr+DqDA=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/quickjs v0.17.1 h1:CbYnbTf7ksZk9YZ1rRM2Ab1Zfi+X6s50kXiOhpd2NIg=
|
||||
modernc.org/quickjs v0.17.1/go.mod h1:hATT7DIJc33I5Q/Fjffhm0tpUHNSqdKHma/ossibTA0=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
|
||||
modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
webui/
|
||||
@@ -1,280 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/schema"
|
||||
)
|
||||
|
||||
type ApiServer struct {
|
||||
config config.ApiConfig
|
||||
serverMu sync.Mutex
|
||||
server *http.Server
|
||||
logger *slog.Logger
|
||||
configurableRouter config.Configurable
|
||||
eventRouter common.EventRouter
|
||||
}
|
||||
|
||||
func NewApiServer(configurableRouter config.Configurable, eventRouter common.EventRouter) *ApiServer {
|
||||
return &ApiServer{
|
||||
configurableRouter: configurableRouter,
|
||||
eventRouter: eventRouter,
|
||||
logger: slog.Default().With("component", "api"),
|
||||
}
|
||||
}
|
||||
|
||||
func (as *ApiServer) Start(config config.ApiConfig) {
|
||||
as.config = config
|
||||
if !as.config.Enabled {
|
||||
as.logger.Warn("not enabled")
|
||||
return
|
||||
}
|
||||
as.logger.Debug("starting", "port", as.config.Port)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/ws", as.handleWebsocket)
|
||||
mux.HandleFunc("/health", as.handleHealthHTTP)
|
||||
mux.HandleFunc("/api/v1/config", as.handleConfigHTTP)
|
||||
mux.HandleFunc("/schema/config.schema.json", handleConfigSchema)
|
||||
mux.HandleFunc("/schema/routes.schema.json", handleRoutesSchema)
|
||||
mux.HandleFunc("/schema/modules.schema.json", handleModulesSchema)
|
||||
mux.HandleFunc("/schema/processors.schema.json", handleProcessorsSchema)
|
||||
mux.HandleFunc("/ui", handleWebUI)
|
||||
mux.HandleFunc("/ui/", handleWebUI)
|
||||
|
||||
as.serverMu.Lock()
|
||||
defer as.serverMu.Unlock()
|
||||
as.server = &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", as.config.Port),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
err := as.server.ListenAndServe()
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
as.logger.Error("server error", "error", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (as *ApiServer) Stop() {
|
||||
if as.server == nil {
|
||||
return
|
||||
}
|
||||
as.serverMu.Lock()
|
||||
defer as.serverMu.Unlock()
|
||||
if as.server != nil {
|
||||
apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer apiShutdownCancel()
|
||||
err := as.server.Shutdown(apiShutdownCtx)
|
||||
if err != nil {
|
||||
as.logger.Error("error shutting down server", "error", err)
|
||||
}
|
||||
as.server = nil
|
||||
}
|
||||
as.logger.Debug("done")
|
||||
}
|
||||
|
||||
func (as *ApiServer) 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 (as *ApiServer) handleConfigHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
configJSON, err := json.Marshal(as.configurableRouter.GetRunningConfig())
|
||||
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:
|
||||
//TODO(jwetzell): again way too much marshaling
|
||||
cfgBytes, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
cfgMap := make(map[string]any)
|
||||
err = json.Unmarshal(cfgBytes, &cfgMap)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = schema.ApplyDefaults(&cfgMap)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = schema.ValidateConfig(cfgMap)
|
||||
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
validCfgBytes, err := json.Marshal(cfgMap)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var newConfig config.Config
|
||||
err = json.Unmarshal(validCfgBytes, &newConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
moduleErrors, routeErrors, err := as.configurableRouter.UpdateConfig(newConfig, true)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if len(moduleErrors) > 0 || len(routeErrors) > 0 {
|
||||
errorResponse := struct {
|
||||
ModuleErrors []config.ModuleError `json:"moduleErrors,omitempty"`
|
||||
RouteErrors []config.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)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
func handleConfigSchema(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaJSON, err := json.Marshal(schema.ConfigSchema)
|
||||
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(schemaJSON)
|
||||
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 handleRoutesSchema(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaJSON, err := json.Marshal(schema.RoutesConfigSchema)
|
||||
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(schemaJSON)
|
||||
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 handleModulesSchema(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaJSON, err := json.Marshal(schema.GetModulesSchema())
|
||||
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(schemaJSON)
|
||||
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 handleProcessorsSchema(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
schemaJSON, err := json.Marshal(schema.GetProcessorsSchema())
|
||||
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(schemaJSON)
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
//go:build !showbridge_webui
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func handleWebUI(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
http.Error(w, "Web UI is not enabled", http.StatusNotImplemented)
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool {
|
||||
return true
|
||||
},
|
||||
}
|
||||
|
||||
type WebsocketEventDestination struct {
|
||||
conn *websocket.Conn
|
||||
}
|
||||
|
||||
func (d WebsocketEventDestination) Send(event common.Event) error {
|
||||
eventJSON, err := event.ToJSON()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return d.conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
}
|
||||
|
||||
func (d WebsocketEventDestination) Is(dest common.EventDestination) bool {
|
||||
other, ok := dest.(WebsocketEventDestination)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
return d.conn == other.conn
|
||||
}
|
||||
|
||||
func (as *ApiServer) handleWebsocket(w http.ResponseWriter, req *http.Request) {
|
||||
conn, err := upgrader.Upgrade(w, req, nil)
|
||||
if err != nil {
|
||||
as.logger.Error("websocket upgrade error", "error", err)
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
eventDestination := WebsocketEventDestination{conn: conn}
|
||||
|
||||
as.eventRouter.AddEventDestination(eventDestination)
|
||||
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 := common.Event{}
|
||||
err = json.Unmarshal(message, &event)
|
||||
if err != nil {
|
||||
as.logger.Error("websocket message unmarshal error", "error", err)
|
||||
continue
|
||||
}
|
||||
as.eventRouter.HandleEvent(event, WebsocketEventDestination{conn: conn})
|
||||
case websocket.CloseMessage:
|
||||
break READ_LOOP
|
||||
case websocket.PingMessage:
|
||||
err = conn.WriteMessage(websocket.PongMessage, nil)
|
||||
if err != nil {
|
||||
as.logger.Error("websocket pong error", "error", err)
|
||||
}
|
||||
default:
|
||||
as.logger.Warn("unsupported websocket message type", "type", messageType)
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
//NOTE(jwetzell): remove ws connection
|
||||
as.eventRouter.RemoveEventDestination(eventDestination)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
//go:build showbridge_webui
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"path"
|
||||
"strings"
|
||||
|
||||
_ "embed"
|
||||
)
|
||||
|
||||
//go:embed webui
|
||||
var webUIFS embed.FS
|
||||
|
||||
var fsPrefix = "webui/browser"
|
||||
|
||||
var index = path.Join(fsPrefix, "index.html")
|
||||
|
||||
func handleWebUI(w http.ResponseWriter, req *http.Request) {
|
||||
requestedPath := strings.TrimLeft(req.URL.Path, "/ui")
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
var pathToLoad string
|
||||
stat, err := fs.Stat(webUIFS, path.Join(fsPrefix, requestedPath))
|
||||
if err != nil {
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
pathToLoad = index
|
||||
} else {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
if stat != nil {
|
||||
if stat.IsDir() {
|
||||
pathToLoad = index
|
||||
} else {
|
||||
pathToLoad = path.Join(fsPrefix, requestedPath)
|
||||
}
|
||||
}
|
||||
file, err := webUIFS.ReadFile(pathToLoad)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
switch path.Ext(pathToLoad) {
|
||||
case ".js":
|
||||
w.Header().Set("Content-Type", "application/javascript")
|
||||
case ".css":
|
||||
w.Header().Set("Content-Type", "text/css")
|
||||
case ".html":
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
case ".ico":
|
||||
w.Header().Set("Content-Type", "image/x-icon")
|
||||
}
|
||||
w.Write(file)
|
||||
return
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
+4
-188
@@ -1,191 +1,7 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
type contextKey string
|
||||
|
||||
func GetAnyAs[T any](value any) (T, bool) {
|
||||
typed, ok := value.(T)
|
||||
return typed, ok
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
if float64(float32Value) != math.Floor(float64(float32Value)) {
|
||||
return 0, false
|
||||
}
|
||||
return int(float32Value), true
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
if float64Value != math.Floor(float64Value) {
|
||||
return 0, false
|
||||
}
|
||||
return int(float64Value), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsByte(value any) (byte, bool) {
|
||||
|
||||
byteValue, ok := value.(byte)
|
||||
if ok {
|
||||
return byte(byteValue), true
|
||||
}
|
||||
|
||||
intValue, ok := value.(int)
|
||||
if ok {
|
||||
return byte(intValue), true
|
||||
}
|
||||
|
||||
uintValue, ok := value.(uint)
|
||||
if ok {
|
||||
return byte(uintValue), true
|
||||
}
|
||||
|
||||
float32Value, ok := value.(float32)
|
||||
if ok {
|
||||
if float64(float32Value) != math.Floor(float64(float32Value)) {
|
||||
return 0, false
|
||||
}
|
||||
return byte(float32Value), true
|
||||
}
|
||||
|
||||
float64Value, ok := value.(float64)
|
||||
if ok {
|
||||
if float64Value != math.Floor(float64Value) {
|
||||
return 0, false
|
||||
}
|
||||
return byte(float64Value), true
|
||||
}
|
||||
return 0, false
|
||||
}
|
||||
|
||||
func GetAnyAsByteSlice(value any) ([]byte, bool) {
|
||||
// already a []byte
|
||||
byteSlice, ok := value.([]byte)
|
||||
if ok {
|
||||
return byteSlice, true
|
||||
}
|
||||
|
||||
// check for a slice
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// try to convert each element to a byte
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
elemValue, ok := GetAnyAsByte(elem)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = elemValue
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsIntSlice(value any) ([]int, bool) {
|
||||
|
||||
// already a []int
|
||||
intSlice, ok := value.([]int)
|
||||
if ok {
|
||||
return intSlice, true
|
||||
}
|
||||
|
||||
// check for a slice
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice && v.Kind() != reflect.Array {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
elemInt, ok := GetAnyAsInt(elem)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = elemInt
|
||||
}
|
||||
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
|
||||
}
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
package common_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
func TestGoodGetAnyAsInt(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue int
|
||||
}{
|
||||
{
|
||||
name: "int",
|
||||
value: int(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "uint",
|
||||
value: uint(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float32 without decimal",
|
||||
value: float32(42.0),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float64 without decimal",
|
||||
value: float64(42.0),
|
||||
typedValue: 42,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsInt(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsInt expected to succeed but failed")
|
||||
}
|
||||
if value != testCase.typedValue {
|
||||
t.Fatalf("GetAnyAsInt expected got %d, expected %d", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsInt(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "string",
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "float32 with decimal",
|
||||
value: float32(1.5),
|
||||
},
|
||||
{
|
||||
name: "float64 with decimal",
|
||||
value: float64(1.5),
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsInt(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsInt expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodGetAnyAsByte(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue byte
|
||||
}{
|
||||
{
|
||||
name: "int",
|
||||
value: int(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "uint",
|
||||
value: uint(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float32 without decimal",
|
||||
value: float32(42.0),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float64 without decimal",
|
||||
value: float64(42.0),
|
||||
typedValue: 42,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsByte(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsByte expected to succeed but failed")
|
||||
}
|
||||
if value != testCase.typedValue {
|
||||
t.Fatalf("GetAnyAsByte expected got %d, expected %d", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsByte(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "string",
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "float32 with decimal",
|
||||
value: float32(1.5),
|
||||
},
|
||||
{
|
||||
name: "float64 with decimal",
|
||||
value: float64(1.5),
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsByte(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsByte expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodGetAnyAsByteSlice(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue []byte
|
||||
}{
|
||||
{
|
||||
name: "byte slice",
|
||||
value: []byte{1, 2, 3},
|
||||
typedValue: []byte{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "int slice",
|
||||
value: []int{1, 2, 3},
|
||||
typedValue: []byte{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "uint slice",
|
||||
value: []uint{1, 2, 3},
|
||||
typedValue: []byte{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "float32 without decimal slice",
|
||||
value: []float32{1, 2, 3},
|
||||
typedValue: []byte{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "float64 without decimal slice",
|
||||
value: []float64{1, 2, 3},
|
||||
typedValue: []byte{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsByteSlice(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsByteSlice expected to succeed but failed")
|
||||
}
|
||||
if !slices.Equal(value, testCase.typedValue) {
|
||||
t.Fatalf("GetAnyAsByteSlice expected got %d, expected %d", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsByteSlice(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "not a slice",
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "not a int slice",
|
||||
value: []any{"value1", 2},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsByteSlice(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsByteSlice expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodGetAnyAsIntSlice(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue []int
|
||||
}{
|
||||
{
|
||||
name: "int slice",
|
||||
value: []int{1, 2, 3},
|
||||
typedValue: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "byte slice",
|
||||
value: []byte{1, 2, 3},
|
||||
typedValue: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "uint slice",
|
||||
value: []uint{1, 2, 3},
|
||||
typedValue: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "float32 without decimal slice",
|
||||
value: []float32{1, 2, 3},
|
||||
typedValue: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "float64 without decimal slice",
|
||||
value: []float64{1, 2, 3},
|
||||
typedValue: []int{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsIntSlice(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsIntSlice expected to succeed but failed")
|
||||
}
|
||||
if !slices.Equal(value, testCase.typedValue) {
|
||||
t.Fatalf("GetAnyAsIntSlice expected got %d, expected %d", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsIntSlice(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "not a slice",
|
||||
value: "value",
|
||||
},
|
||||
{
|
||||
name: "not a int slice",
|
||||
value: []any{"value1", 2},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsIntSlice(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsIntSlice expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodGetAnyAsFloat32(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue float32
|
||||
}{
|
||||
{
|
||||
name: "int",
|
||||
value: int(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "uint",
|
||||
value: uint(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "byte",
|
||||
value: byte(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float32",
|
||||
value: float32(42.3),
|
||||
typedValue: 42.3,
|
||||
},
|
||||
{
|
||||
name: "float64",
|
||||
value: float64(42.3),
|
||||
typedValue: 42.3,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsFloat32(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsFloat32 expected to succeed but failed")
|
||||
}
|
||||
if value != testCase.typedValue {
|
||||
t.Fatalf("GetAnyAsFloat32 expected got %f, expected %f", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsFloat32(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "string",
|
||||
value: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsFloat32(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsFloat32 expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodGetAnyAsFloat64(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
typedValue float64
|
||||
}{
|
||||
{
|
||||
name: "int",
|
||||
value: int(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "uint",
|
||||
value: uint(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "byte",
|
||||
value: byte(42),
|
||||
typedValue: 42,
|
||||
},
|
||||
{
|
||||
name: "float32",
|
||||
value: float32(42.5),
|
||||
typedValue: 42.5,
|
||||
},
|
||||
{
|
||||
name: "float64",
|
||||
value: float64(42.5),
|
||||
typedValue: 42.5,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsFloat64(testCase.value)
|
||||
if !ok {
|
||||
t.Fatalf("GetAnyAsFloat64 expected to succeed but failed")
|
||||
}
|
||||
if value != testCase.typedValue {
|
||||
t.Fatalf("GetAnyAsFloat64 expected got %f, expected %f", value, testCase.typedValue)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadGetAnyAsFloat64(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
value any
|
||||
}{
|
||||
{
|
||||
name: "string",
|
||||
value: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
value, ok := common.GetAnyAsFloat64(testCase.value)
|
||||
if ok {
|
||||
t.Fatalf("GetAnyAsFloat64 expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
type EventDestination interface {
|
||||
Send(event Event) error
|
||||
Is(dest EventDestination) bool
|
||||
}
|
||||
|
||||
type EventRouter interface {
|
||||
HandleEvent(event Event, source EventDestination)
|
||||
AddEventDestination(dest EventDestination)
|
||||
RemoveEventDestination(dest EventDestination)
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package common_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
)
|
||||
|
||||
func TestEventToJson(t *testing.T) {
|
||||
e := common.Event{
|
||||
Type: "test.event",
|
||||
Data: map[string]any{
|
||||
"key": "value",
|
||||
},
|
||||
}
|
||||
jsonData, err := e.ToJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to convert event to JSON: %v", err)
|
||||
}
|
||||
expectedJson := `{"type":"test.event","data":{"key":"value"}}`
|
||||
if string(jsonData) != expectedJson {
|
||||
t.Errorf("Expected JSON: %s, got: %s", expectedJson, string(jsonData))
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type Module interface {
|
||||
Id() string
|
||||
Type() string
|
||||
Start(context.Context, InputHandler) error
|
||||
Stop()
|
||||
}
|
||||
|
||||
type OutputModule interface {
|
||||
Output(context.Context, any) error
|
||||
}
|
||||
|
||||
type KeyValueModule interface {
|
||||
Get(ctx context.Context, key string) (any, error)
|
||||
Set(ctx context.Context, key string, value any) error
|
||||
}
|
||||
|
||||
type DatabaseModule interface {
|
||||
QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
|
||||
}
|
||||
|
||||
type PubSubModule interface {
|
||||
Publish(ctx context.Context, topic string, payload any) error
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package common
|
||||
|
||||
type WrappedPayload struct {
|
||||
Payload any
|
||||
InputHandler InputHandler
|
||||
Modules map[string]Module
|
||||
Source string
|
||||
End bool
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type InputHandler func(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int `json:"index"`
|
||||
ProcessError error `json:"processError"`
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package config
|
||||
|
||||
type ApiConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Port int `json:"port"`
|
||||
}
|
||||
+274
-4
@@ -1,12 +1,282 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Api ApiConfig `json:"api"`
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
|
||||
type Configurable interface {
|
||||
UpdateConfig(newConfig Config, triggerChangeChannel bool) ([]ModuleError, []RouteError, error)
|
||||
GetRunningConfig() Config
|
||||
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
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type RouteConfig struct {
|
||||
Input string `json:"input"`
|
||||
Processors []ProcessorConfig `json:"processors"`
|
||||
Output string `json:"output"`
|
||||
}
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func TestGoodStringParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "string param",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
expected: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetString(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetString returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetString got %s, expected %s", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "int param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetInt(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetInt returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetInt got %d, expected %d", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat32ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float32
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat32(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat32 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat32 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat64ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat64(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat64 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat64 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodBoolParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "bool param",
|
||||
paramsJSON: `{"key": true}`,
|
||||
key: "key",
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetBool(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBool returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetBool got %t, expected %t", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodStringSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "string array",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "key",
|
||||
expected: []string{"value1", "value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetStringSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetStringSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetStringSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []int
|
||||
}{
|
||||
{
|
||||
name: "int array",
|
||||
paramsJSON: `{"key": [1, 2, 3]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "int array with floats",
|
||||
paramsJSON: `{"key": [1.0, 2.0, 3.0]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetIntSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIntSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetIntSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodByteSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "byte array",
|
||||
paramsJSON: `{"key": [1,2,3,4]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
{
|
||||
name: "byte array with floats",
|
||||
paramsJSON: `{"key": [1.0,2.0,3.0,4.0]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetByteSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByteSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetByteSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
package config
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
|
||||
type ModuleError struct {
|
||||
Index int `json:"index"`
|
||||
Config ModuleConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
@@ -1,140 +0,0 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"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")
|
||||
ErrParamNotStringSlice = errors.New("not a string 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, ErrParamNotStringSlice
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -1,628 +0,0 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func TestGoodStringParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "string param",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
expected: "value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetString(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetString returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetString got %s, expected %s", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadStringParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a string",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotString,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetString(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetString expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetString got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected int
|
||||
}{
|
||||
{
|
||||
name: "int param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetInt(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetInt returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetInt got %d, expected %d", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadIntParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a number",
|
||||
paramsJSON: `{"key": "1"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotNumber,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetInt(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetInt expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetInt got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat32ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float32
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat32(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat32 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat32 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadFloat32ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a number",
|
||||
paramsJSON: `{"key": "1"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotNumber,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat32(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetFloat32 expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetFloat32 got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodFloat64ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "no decimal param",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "key",
|
||||
expected: 1,
|
||||
},
|
||||
{
|
||||
name: "float param",
|
||||
paramsJSON: `{"key": 1.23}`,
|
||||
key: "key",
|
||||
expected: 1.23,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat64(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetFloat64 returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetFloat64 got %f, expected %f", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadFloat64ParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a number",
|
||||
paramsJSON: `{"key": "1"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotNumber,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetFloat64(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetFloat64 expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetFloat64 got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodBoolParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected bool
|
||||
}{
|
||||
{
|
||||
name: "bool param",
|
||||
paramsJSON: `{"key": true}`,
|
||||
key: "key",
|
||||
expected: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetBool(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBool returned error: %v", err)
|
||||
}
|
||||
if value != testCase.expected {
|
||||
t.Fatalf("GetBool got %t, expected %t", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadBoolParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": 1}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a bool",
|
||||
paramsJSON: `{"key": "1"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotBool,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetBool(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetBool expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetBool got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodStringSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []string
|
||||
}{
|
||||
{
|
||||
name: "string array",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "key",
|
||||
expected: []string{"value1", "value2"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetStringSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetStringSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetStringSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadStringSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a slice",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotSlice,
|
||||
},
|
||||
{
|
||||
name: "not a string slice",
|
||||
paramsJSON: `{"key": ["value1", 2]}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotStringSlice,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetStringSlice(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetStringSlice expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetStringSlice got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodIntSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []int
|
||||
}{
|
||||
{
|
||||
name: "int array",
|
||||
paramsJSON: `{"key": [1, 2, 3]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
{
|
||||
name: "int array with floats",
|
||||
paramsJSON: `{"key": [1.0, 2.0, 3.0]}`,
|
||||
key: "key",
|
||||
expected: []int{1, 2, 3},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetIntSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetIntSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetIntSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadIntSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a slice",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotIntSlice,
|
||||
},
|
||||
{
|
||||
name: "not a int slice",
|
||||
paramsJSON: `{"key": ["value1", 2]}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotIntSlice,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetIntSlice(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetIntSlice expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetIntSlice got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodByteSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "byte array",
|
||||
paramsJSON: `{"key": [1,2,3,4]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
{
|
||||
name: "byte array with floats",
|
||||
paramsJSON: `{"key": [1.0,2.0,3.0,4.0]}`,
|
||||
key: "key",
|
||||
expected: []byte{1, 2, 3, 4},
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetByteSlice(testCase.key)
|
||||
if err != nil {
|
||||
t.Fatalf("GetByteSlice returned error: %v", err)
|
||||
}
|
||||
if !slices.Equal(value, testCase.expected) {
|
||||
t.Fatalf("GetByteSlice got %v, expected %v", value, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadByteSliceParamsJSON(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
paramsJSON string
|
||||
key string
|
||||
returnError error
|
||||
}{
|
||||
{
|
||||
name: "key not found",
|
||||
paramsJSON: `{"key": ["value1", "value2"]}`,
|
||||
key: "test",
|
||||
returnError: config.ErrParamNotFound,
|
||||
},
|
||||
{
|
||||
name: "not a slice",
|
||||
paramsJSON: `{"key": "value"}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotByteSlice,
|
||||
},
|
||||
{
|
||||
name: "not a int slice",
|
||||
paramsJSON: `{"key": ["value1", 2]}`,
|
||||
key: "key",
|
||||
returnError: config.ErrParamNotByteSlice,
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
params := config.Params{}
|
||||
err := json.Unmarshal([]byte(testCase.paramsJSON), ¶ms)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to unmarshal params JSON: %v", err)
|
||||
}
|
||||
value, err := params.GetByteSlice(testCase.key)
|
||||
if err == nil {
|
||||
t.Fatalf("GetByteSlice expected to fail but succeeded, got: %v", value)
|
||||
}
|
||||
if !errors.Is(err, testCase.returnError) {
|
||||
t.Fatalf("GetByteSlice got error '%s', expected '%s'", err, testCase.returnError)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package config
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package config
|
||||
|
||||
type RouteConfig struct {
|
||||
Input string `json:"input"`
|
||||
Processors []ProcessorConfig `json:"processors"`
|
||||
}
|
||||
|
||||
type RouteError struct {
|
||||
Index int `json:"index"`
|
||||
Config RouteConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
@@ -10,15 +10,15 @@ type Framer interface {
|
||||
func GetFramer(framingType string) Framer {
|
||||
switch framingType {
|
||||
case "CR":
|
||||
return newByteSeparatorFramer([]byte{'\r'})
|
||||
return NewByteSeparatorFramer([]byte{'\r'})
|
||||
case "LF":
|
||||
return newByteSeparatorFramer([]byte{'\n'})
|
||||
return NewByteSeparatorFramer([]byte{'\n'})
|
||||
case "CRLF":
|
||||
return newByteSeparatorFramer([]byte{'\r', '\n'})
|
||||
return NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||
case "SLIP":
|
||||
return newSlipFramer()
|
||||
return NewSlipFramer()
|
||||
case "RAW":
|
||||
return newRawFramer()
|
||||
return NewRawFramer()
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
package framer
|
||||
|
||||
type rawFramer struct{}
|
||||
type RawFramer struct{}
|
||||
|
||||
func newRawFramer() *rawFramer {
|
||||
return &rawFramer{}
|
||||
func NewRawFramer() *RawFramer {
|
||||
return &RawFramer{}
|
||||
}
|
||||
|
||||
func (rf *rawFramer) Decode(data []byte) [][]byte {
|
||||
func (rf *RawFramer) Decode(data []byte) [][]byte {
|
||||
return [][]byte{data}
|
||||
}
|
||||
|
||||
func (rf *rawFramer) Encode(data []byte) []byte {
|
||||
func (rf *RawFramer) Encode(data []byte) []byte {
|
||||
return data
|
||||
}
|
||||
|
||||
func (rf *rawFramer) Clear() {
|
||||
func (rf *RawFramer) Clear() {
|
||||
// NOTE(jwetzell): no internal state to clear
|
||||
}
|
||||
|
||||
func (rf *rawFramer) Buffer() []byte {
|
||||
func (rf *RawFramer) Buffer() []byte {
|
||||
return []byte{}
|
||||
}
|
||||
|
||||
@@ -4,16 +4,16 @@ import (
|
||||
"bytes"
|
||||
)
|
||||
|
||||
type byteSeparatorFramer struct {
|
||||
type ByteSeparatorFramer struct {
|
||||
buffer []byte
|
||||
separator []byte
|
||||
}
|
||||
|
||||
func newByteSeparatorFramer(separator []byte) *byteSeparatorFramer {
|
||||
return &byteSeparatorFramer{separator: separator, buffer: []byte{}}
|
||||
func NewByteSeparatorFramer(separator []byte) *ByteSeparatorFramer {
|
||||
return &ByteSeparatorFramer{separator: separator, buffer: []byte{}}
|
||||
}
|
||||
|
||||
func (bsf *byteSeparatorFramer) Decode(data []byte) [][]byte {
|
||||
func (bsf *ByteSeparatorFramer) Decode(data []byte) [][]byte {
|
||||
messages := [][]byte{}
|
||||
|
||||
bsf.buffer = append(bsf.buffer, data...)
|
||||
@@ -28,14 +28,14 @@ func (bsf *byteSeparatorFramer) Decode(data []byte) [][]byte {
|
||||
return messages
|
||||
}
|
||||
|
||||
func (bsf *byteSeparatorFramer) Encode(data []byte) []byte {
|
||||
func (bsf *ByteSeparatorFramer) Encode(data []byte) []byte {
|
||||
return append(data, bsf.separator...)
|
||||
}
|
||||
|
||||
func (bsf *byteSeparatorFramer) Clear() {
|
||||
func (bsf *ByteSeparatorFramer) Clear() {
|
||||
bsf.buffer = []byte{}
|
||||
}
|
||||
|
||||
func (bsf *byteSeparatorFramer) Buffer() []byte {
|
||||
func (bsf *ByteSeparatorFramer) Buffer() []byte {
|
||||
return bsf.buffer
|
||||
}
|
||||
|
||||
+9
-10
@@ -1,14 +1,14 @@
|
||||
package framer
|
||||
|
||||
type slipFramer struct {
|
||||
type SlipFramer struct {
|
||||
buffer []byte
|
||||
}
|
||||
|
||||
func newSlipFramer() *slipFramer {
|
||||
return &slipFramer{buffer: []byte{}}
|
||||
func NewSlipFramer() *SlipFramer {
|
||||
return &SlipFramer{buffer: []byte{}}
|
||||
}
|
||||
|
||||
func (sf *slipFramer) Decode(data []byte) [][]byte {
|
||||
func (sf *SlipFramer) Decode(data []byte) [][]byte {
|
||||
messages := [][]byte{}
|
||||
|
||||
END := byte(0xc0)
|
||||
@@ -25,10 +25,9 @@ func (sf *slipFramer) Decode(data []byte) [][]byte {
|
||||
}
|
||||
|
||||
if escapeNext {
|
||||
switch packetByte {
|
||||
case ESC_END:
|
||||
if packetByte == ESC_END {
|
||||
sf.buffer = append(sf.buffer, END)
|
||||
case ESC_ESC:
|
||||
} else if packetByte == ESC_ESC {
|
||||
sf.buffer = append(sf.buffer, ESC)
|
||||
}
|
||||
escapeNext = false
|
||||
@@ -49,7 +48,7 @@ func (sf *slipFramer) Decode(data []byte) [][]byte {
|
||||
return messages
|
||||
}
|
||||
|
||||
func (sf *slipFramer) Encode(data []byte) []byte {
|
||||
func (sf *SlipFramer) Encode(data []byte) []byte {
|
||||
END := byte(0xc0)
|
||||
ESC := byte(0xdb)
|
||||
ESC_END := byte(0xdc)
|
||||
@@ -72,10 +71,10 @@ func (sf *slipFramer) Encode(data []byte) []byte {
|
||||
return encodedBytes
|
||||
}
|
||||
|
||||
func (sf *slipFramer) Clear() {
|
||||
func (sf *SlipFramer) Clear() {
|
||||
sf.buffer = []byte{}
|
||||
}
|
||||
|
||||
func (sf *slipFramer) Buffer() []byte {
|
||||
func (sf *SlipFramer) Buffer() []byte {
|
||||
return sf.buffer
|
||||
}
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "db.sqlite",
|
||||
Title: "SQLite Database",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"dsn": {
|
||||
Title: "Data Source Name",
|
||||
Description: "the data source name (DSN) for the SQLite database",
|
||||
Type: "string",
|
||||
MinLength: new(1),
|
||||
},
|
||||
},
|
||||
Required: []string{"dsn"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
|
||||
dsnString, err := params.GetString("dsn")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db.sqlite dsn error: %w", err)
|
||||
}
|
||||
|
||||
return &DbSqlite{Dsn: dsnString, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type DbSqlite struct {
|
||||
config config.ModuleConfig
|
||||
Dsn string
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
db *sql.DB
|
||||
logger *slog.Logger
|
||||
dbMu sync.Mutex
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (dbs *DbSqlite) Id() string {
|
||||
return dbs.config.Id
|
||||
}
|
||||
|
||||
func (dbs *DbSqlite) Type() string {
|
||||
return dbs.config.Type
|
||||
}
|
||||
|
||||
func (dbs *DbSqlite) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
dbs.logger.Debug("running")
|
||||
dbs.inputHandler = inputHandler
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
dbs.ctx = moduleContext
|
||||
dbs.cancel = cancel
|
||||
|
||||
db, err := sql.Open("sqlite", dbs.Dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("db.sqlite error opening database: %w", err)
|
||||
}
|
||||
dbs.dbMu.Lock()
|
||||
dbs.db = db
|
||||
dbs.dbMu.Unlock()
|
||||
<-dbs.ctx.Done()
|
||||
dbs.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dbs *DbSqlite) Stop() {
|
||||
if dbs.cancel != nil {
|
||||
defer dbs.cancel()
|
||||
}
|
||||
dbs.dbMu.Lock()
|
||||
defer dbs.dbMu.Unlock()
|
||||
if dbs.db != nil {
|
||||
dbs.db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (dbs *DbSqlite) QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
|
||||
dbs.dbMu.Lock()
|
||||
defer dbs.dbMu.Unlock()
|
||||
if dbs.db == nil {
|
||||
return nil, fmt.Errorf("database not initialized")
|
||||
}
|
||||
return dbs.db.QueryContext(ctx, query, args...)
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
type HTTPClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
client *http.Client
|
||||
router route.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
|
||||
return &HTTPClient{config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Id() string {
|
||||
return hc.config.Id
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Type() string {
|
||||
return hc.config.Type
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Start(ctx context.Context) error {
|
||||
hc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.client unable to get router from context")
|
||||
}
|
||||
hc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
hc.ctx = moduleContext
|
||||
hc.cancel = cancel
|
||||
|
||||
hc.client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
<-hc.ctx.Done()
|
||||
hc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadRequest, ok := processor.GetAnyAs[*http.Request](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.client is only able to output an http.Request")
|
||||
}
|
||||
|
||||
if hc.client == nil {
|
||||
return errors.New("http.client client is nil")
|
||||
}
|
||||
|
||||
response, err := hc.client.Do(payloadRequest)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if hc.router != nil {
|
||||
hc.router.HandleInput(hc.ctx, hc.Id(), response)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Stop() {
|
||||
hc.cancel()
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("http.client does not support Get")
|
||||
}
|
||||
@@ -7,58 +7,27 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.server",
|
||||
Title: "HTTP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the HTTP server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.server port error: %w", err)
|
||||
}
|
||||
return &HTTPServer{Port: uint16(portNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type HTTPServer struct {
|
||||
config config.ModuleConfig
|
||||
Port uint16
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
server *http.Server
|
||||
serverMu sync.Mutex
|
||||
config config.ModuleConfig
|
||||
Port uint16
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type ResponseIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError *string `json:"outputError"`
|
||||
ProcessError *string `json:"processError"`
|
||||
InputError *string `json:"inputError"`
|
||||
}
|
||||
|
||||
type IOResponseData struct {
|
||||
@@ -84,6 +53,20 @@ func (hsrw *HTTPServerResponseWriter) Write(data []byte) (int, error) {
|
||||
return hsrw.ResponseWriter.Write(data)
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.server",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.server port error: %w", err)
|
||||
}
|
||||
return &HTTPServer{Port: uint16(portNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Id() string {
|
||||
return hs.config.Id
|
||||
}
|
||||
@@ -99,9 +82,9 @@ func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
Message: "routing successful",
|
||||
Status: "ok",
|
||||
}
|
||||
if hs.inputHandler != nil {
|
||||
if hs.router != nil {
|
||||
inputContext := context.WithValue(hs.ctx, httpServerContextKey("responseWriter"), &responseWriter)
|
||||
aRouteFound, routingErrors := hs.inputHandler(inputContext, hs.Id(), r)
|
||||
aRouteFound, routingErrors := hs.router.HandleInput(inputContext, hs.Id(), r)
|
||||
if !responseWriter.done {
|
||||
if aRouteFound {
|
||||
if routingErrors != nil {
|
||||
@@ -115,11 +98,21 @@ func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
Index: responseIOError.Index,
|
||||
}
|
||||
|
||||
if responseIOError.InputError != nil {
|
||||
errorMsg := responseIOError.InputError.Error()
|
||||
errorToAdd.InputError = &errorMsg
|
||||
}
|
||||
|
||||
if responseIOError.ProcessError != nil {
|
||||
errorMsg := responseIOError.ProcessError.Error()
|
||||
errorToAdd.ProcessError = &errorMsg
|
||||
}
|
||||
|
||||
if responseIOError.OutputError != nil {
|
||||
errorMsg := responseIOError.OutputError.Error()
|
||||
errorToAdd.OutputError = &errorMsg
|
||||
}
|
||||
|
||||
response.IOErrors = append(response.IOErrors, errorToAdd)
|
||||
|
||||
}
|
||||
@@ -148,27 +141,32 @@ func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (hs *HTTPServer) Start(ctx context.Context) error {
|
||||
hs.logger.Debug("running")
|
||||
hs.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server unable to get router from context")
|
||||
}
|
||||
hs.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
hs.ctx = moduleContext
|
||||
hs.cancel = cancel
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", hs.Port),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
Handler: hs,
|
||||
Addr: fmt.Sprintf(":%d", hs.Port),
|
||||
Handler: hs,
|
||||
}
|
||||
|
||||
hs.serverMu.Lock()
|
||||
hs.server = httpServer
|
||||
hs.serverMu.Unlock()
|
||||
go func() {
|
||||
<-hs.ctx.Done()
|
||||
httpServer.Close()
|
||||
}()
|
||||
|
||||
err := httpServer.ListenAndServe()
|
||||
// TODO(jwetzell): handle server closed error differently
|
||||
if err != nil {
|
||||
if !errors.Is(err, http.ErrServerClosed) {
|
||||
if err.Error() != "http: Server closed" {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -185,7 +183,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 := common.GetAnyAs[processor.HTTPResponse](payload)
|
||||
payloadResponse, ok := processor.GetAnyAs[processor.HTTPResponse](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server is only able to output HTTPResponse")
|
||||
@@ -201,15 +199,9 @@ func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Stop() {
|
||||
if hs.cancel != nil {
|
||||
defer hs.cancel()
|
||||
}
|
||||
hs.serverMu.Lock()
|
||||
defer hs.serverMu.Unlock()
|
||||
if hs.server != nil {
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
hs.server.Shutdown(shutdownCtx)
|
||||
shutdownCancel()
|
||||
<-shutdownCtx.Done()
|
||||
}
|
||||
hs.cancel()
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("http.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -4,33 +4,31 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
|
||||
type MIDIInput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.input",
|
||||
Title: "MIDI Input",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the name of the MIDI port to listen to",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "midi.input",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
@@ -42,16 +40,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type MIDIInput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Port string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
stop func()
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Id() string {
|
||||
return mi.config.Id
|
||||
}
|
||||
@@ -60,9 +48,15 @@ func (mi *MIDIInput) Type() string {
|
||||
return mi.config.Type
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (mi *MIDIInput) Start(ctx context.Context) error {
|
||||
mi.logger.Debug("running")
|
||||
mi.inputHandler = inputHandler
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.input unable to get router from context")
|
||||
}
|
||||
mi.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mi.ctx = moduleContext
|
||||
mi.cancel = cancel
|
||||
@@ -73,27 +67,35 @@ func (mi *MIDIInput) Start(ctx context.Context, inputHandler common.InputHandler
|
||||
}
|
||||
|
||||
stop, err := midi.ListenTo(in, func(msg midi.Message, timestampms int32) {
|
||||
if mi.inputHandler != nil {
|
||||
mi.inputHandler(mi.ctx, mi.Id(), msg)
|
||||
if mi.router != nil {
|
||||
mi.router.HandleInput(mi.ctx, mi.Id(), msg)
|
||||
}
|
||||
}, midi.UseSysEx())
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mi.stop = stop
|
||||
|
||||
defer stop()
|
||||
|
||||
<-mi.ctx.Done()
|
||||
mi.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Stop() {
|
||||
if mi.cancel != nil {
|
||||
defer mi.cancel()
|
||||
}
|
||||
if mi.stop != nil {
|
||||
mi.stop()
|
||||
}
|
||||
midi.CloseDriver()
|
||||
func (mi *MIDIInput) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("midi.input output is not implemented")
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Stop() {
|
||||
mi.cancel()
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mi.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.input key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,32 +7,29 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
|
||||
type MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.output",
|
||||
Title: "MIDI Output",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the name of the MIDI port to send messages to",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "midi.output",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
portString, err := params.GetString("port")
|
||||
@@ -45,17 +42,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Port string
|
||||
sendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
sendFuncMu sync.Mutex
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Id() string {
|
||||
return mo.config.Id
|
||||
}
|
||||
@@ -64,9 +50,15 @@ func (mo *MIDIOutput) Type() string {
|
||||
return mo.config.Type
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (mo *MIDIOutput) Start(ctx context.Context) error {
|
||||
mo.logger.Debug("running")
|
||||
mo.inputHandler = inputHandler
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output unable to get router from context")
|
||||
}
|
||||
mo.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mo.ctx = moduleContext
|
||||
mo.cancel = cancel
|
||||
@@ -82,9 +74,7 @@ func (mo *MIDIOutput) Start(ctx context.Context, inputHandler common.InputHandle
|
||||
return err
|
||||
}
|
||||
|
||||
mo.sendFuncMu.Lock()
|
||||
mo.sendFunc = send
|
||||
mo.sendFuncMu.Unlock()
|
||||
mo.SendFunc = send
|
||||
|
||||
<-mo.ctx.Done()
|
||||
mo.logger.Debug("done")
|
||||
@@ -92,24 +82,28 @@ func (mo *MIDIOutput) Start(ctx context.Context, inputHandler common.InputHandle
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
mo.sendFuncMu.Lock()
|
||||
defer mo.sendFuncMu.Unlock()
|
||||
if mo.sendFunc == nil {
|
||||
if mo.SendFunc == nil {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
payloadMessage, ok := processor.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only output midi.Message")
|
||||
return errors.New("midi.output can only ouptut midi.Message")
|
||||
}
|
||||
|
||||
return mo.sendFunc(payloadMessage)
|
||||
return mo.SendFunc(payloadMessage)
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Stop() {
|
||||
if mo.cancel != nil {
|
||||
defer mo.cancel()
|
||||
}
|
||||
midi.CloseDriver()
|
||||
mo.cancel()
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return mo.Port, nil
|
||||
default:
|
||||
return nil, errors.New("midi.output key not found")
|
||||
}
|
||||
}
|
||||
|
||||
+21
-32
@@ -1,21 +1,32 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type ModuleError struct {
|
||||
Index int
|
||||
Config config.ModuleConfig
|
||||
Error error
|
||||
}
|
||||
|
||||
type Module interface {
|
||||
Id() string
|
||||
Type() string
|
||||
Start(context.Context) error
|
||||
Stop()
|
||||
Output(context.Context, any) error
|
||||
Get(key string) (any, error)
|
||||
}
|
||||
|
||||
type ModuleRegistration struct {
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
ParamsSchema *jsonschema.Schema `json:"paramsSchema,omitempty"`
|
||||
New func(config.ModuleConfig) (common.Module, error)
|
||||
Type string `json:"type"`
|
||||
New func(config.ModuleConfig) (Module, error)
|
||||
}
|
||||
|
||||
func RegisterModule(mod ModuleRegistration) {
|
||||
@@ -30,37 +41,15 @@ func RegisterModule(mod ModuleRegistration) {
|
||||
moduleRegistryMu.Lock()
|
||||
defer moduleRegistryMu.Unlock()
|
||||
|
||||
_, exists := moduleRegistry[string(mod.Type)]
|
||||
if exists {
|
||||
if _, ok := ModuleRegistry[string(mod.Type)]; ok {
|
||||
panic(fmt.Sprintf("module already registered: %s", mod.Type))
|
||||
}
|
||||
moduleRegistry[string(mod.Type)] = mod
|
||||
}
|
||||
|
||||
type ModuleRegistry map[string]ModuleRegistration
|
||||
|
||||
func GetModuleRegistration(moduleType string) (ModuleRegistration, bool) {
|
||||
moduleRegistryMu.RLock()
|
||||
defer moduleRegistryMu.RUnlock()
|
||||
|
||||
mod, ok := moduleRegistry[moduleType]
|
||||
return mod, ok
|
||||
}
|
||||
|
||||
func GetModuleRegistrations() []ModuleRegistration {
|
||||
moduleRegistryMu.RLock()
|
||||
defer moduleRegistryMu.RUnlock()
|
||||
|
||||
registrations := make([]ModuleRegistration, 0, len(moduleRegistry))
|
||||
for _, mod := range moduleRegistry {
|
||||
registrations = append(registrations, mod)
|
||||
}
|
||||
return registrations
|
||||
ModuleRegistry[string(mod.Type)] = mod
|
||||
}
|
||||
|
||||
var (
|
||||
moduleRegistryMu sync.RWMutex
|
||||
moduleRegistry = make(ModuleRegistry)
|
||||
ModuleRegistry = make(map[string]ModuleRegistration)
|
||||
)
|
||||
|
||||
func CreateLogger(config config.ModuleConfig) *slog.Logger {
|
||||
|
||||
+36
-102
@@ -2,60 +2,34 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
mqtt "github.com/eclipse/paho.mqtt.golang"
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Broker string
|
||||
ClientID string
|
||||
Topic string
|
||||
client mqtt.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "mqtt.client",
|
||||
Title: "MQTT Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"broker": {
|
||||
Title: "Broker URL",
|
||||
Description: "the URL of the MQTT broker to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"topic": {
|
||||
Title: "Topic",
|
||||
Description: "an MQTT topic to subscribe to",
|
||||
Type: "string",
|
||||
},
|
||||
"clientId": {
|
||||
Title: "Client ID",
|
||||
Description: "the client ID to use when connecting to the MQTT broker",
|
||||
Type: "string",
|
||||
},
|
||||
"qos": {
|
||||
Title: "QoS",
|
||||
Description: "the QoS level to use when publishing messages",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](0),
|
||||
Maximum: jsonschema.Ptr[float64](2),
|
||||
Default: json.RawMessage(`0`),
|
||||
},
|
||||
"retained": {
|
||||
Title: "Retained",
|
||||
Description: "whether to set the retained flag when publishing messages",
|
||||
Type: "boolean",
|
||||
Default: json.RawMessage(`false`),
|
||||
},
|
||||
},
|
||||
Required: []string{"broker", "topic", "clientId"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
Type: "mqtt.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
brokerString, err := params.GetString("broker")
|
||||
|
||||
if err != nil {
|
||||
@@ -74,46 +48,11 @@ func init() {
|
||||
return nil, fmt.Errorf("mqtt.client clientId error: %w", err)
|
||||
}
|
||||
|
||||
qosString, err := params.GetInt("qos")
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
qosString = 0
|
||||
} else {
|
||||
return nil, fmt.Errorf("mqtt.client qos error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
retainedBool, err := params.GetBool("retained")
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
retainedBool = false
|
||||
} else {
|
||||
return nil, fmt.Errorf("mqtt.client retained error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return &MQTTClient{config: moduleConfig, Broker: brokerString, Topic: topicString, ClientID: clientIdString, QoS: byte(qosString), Retained: retainedBool, logger: CreateLogger(moduleConfig)}, nil
|
||||
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type MQTTClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Broker string
|
||||
ClientID string
|
||||
Topic string
|
||||
QoS byte
|
||||
Retained bool
|
||||
client mqtt.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
clientMu sync.Mutex
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Id() string {
|
||||
return mc.config.Id
|
||||
}
|
||||
@@ -122,9 +61,14 @@ func (mc *MQTTClient) Type() string {
|
||||
return mc.config.Type
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
mc.logger.Debug("running")
|
||||
mc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client unable to get router from context")
|
||||
}
|
||||
mc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
mc.ctx = moduleContext
|
||||
mc.cancel = cancel
|
||||
@@ -137,15 +81,13 @@ func (mc *MQTTClient) Start(ctx context.Context, inputHandler common.InputHandle
|
||||
|
||||
opts.OnConnect = func(c mqtt.Client) {
|
||||
token := mc.client.Subscribe(mc.Topic, 1, func(c mqtt.Client, m mqtt.Message) {
|
||||
if mc.inputHandler != nil {
|
||||
mc.inputHandler(mc.ctx, mc.Id(), m)
|
||||
}
|
||||
mc.router.HandleInput(mc.ctx, mc.Id(), m)
|
||||
})
|
||||
token.Wait()
|
||||
}
|
||||
|
||||
mc.clientMu.Lock()
|
||||
mc.client = mqtt.NewClient(opts)
|
||||
defer mc.client.Disconnect(250)
|
||||
|
||||
token := mc.client.Connect()
|
||||
|
||||
@@ -154,22 +96,17 @@ func (mc *MQTTClient) Start(ctx context.Context, inputHandler common.InputHandle
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mc.clientMu.Unlock()
|
||||
|
||||
<-mc.ctx.Done()
|
||||
mc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Publish(ctx context.Context, topic string, payload any) error {
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
payloadMessage, ok := processor.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
if !ok {
|
||||
return errors.New("mqtt.client is only able to publish bytes or string")
|
||||
}
|
||||
payloadBytes = []byte(payloadString)
|
||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||
}
|
||||
|
||||
if mc.client == nil {
|
||||
@@ -180,7 +117,7 @@ func (mc *MQTTClient) Publish(ctx context.Context, topic string, payload any) er
|
||||
return errors.New("mqtt.client is not connected")
|
||||
}
|
||||
|
||||
token := mc.client.Publish(topic, mc.QoS, mc.Retained, payloadBytes)
|
||||
token := mc.client.Publish(payloadMessage.Topic(), payloadMessage.Qos(), payloadMessage.Retained(), payloadMessage.Payload())
|
||||
|
||||
token.Wait()
|
||||
|
||||
@@ -188,12 +125,9 @@ func (mc *MQTTClient) Publish(ctx context.Context, topic string, payload any) er
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Stop() {
|
||||
if mc.cancel != nil {
|
||||
mc.cancel()
|
||||
}
|
||||
mc.clientMu.Lock()
|
||||
defer mc.clientMu.Unlock()
|
||||
if mc.client != nil {
|
||||
mc.client.Disconnect(250)
|
||||
}
|
||||
mc.cancel()
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("mqtt.client does not support Get")
|
||||
}
|
||||
|
||||
@@ -4,36 +4,29 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
"github.com/nats-io/nats.go"
|
||||
)
|
||||
|
||||
type NATSClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
URL string
|
||||
Subject string
|
||||
client *nats.Conn
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "nats.client",
|
||||
Title: "NATS Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"url": {
|
||||
Title: "NATS Server URL",
|
||||
Description: "the URL of the NATS server to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"subject": {
|
||||
Title: "Subject",
|
||||
Description: "the subject to subscribe to",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"url", "subject"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "nats.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
@@ -51,20 +44,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type NATSClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
URL string
|
||||
Subject string
|
||||
client *nats.Conn
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
sub *nats.Subscription
|
||||
subMu sync.Mutex
|
||||
clientMu sync.Mutex
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Id() string {
|
||||
return nc.config.Id
|
||||
}
|
||||
@@ -73,9 +52,15 @@ func (nc *NATSClient) Type() string {
|
||||
return nc.config.Type
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
nc.logger.Debug("running")
|
||||
nc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client unable to get router from context")
|
||||
}
|
||||
|
||||
nc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
nc.ctx = moduleContext
|
||||
nc.cancel = cancel
|
||||
@@ -86,43 +71,36 @@ func (nc *NATSClient) Start(ctx context.Context, inputHandler common.InputHandle
|
||||
return err
|
||||
}
|
||||
|
||||
nc.clientMu.Lock()
|
||||
nc.client = client
|
||||
nc.clientMu.Unlock()
|
||||
|
||||
defer client.Drain()
|
||||
defer client.Close()
|
||||
|
||||
sub, err := nc.client.Subscribe(nc.Subject, func(msg *nats.Msg) {
|
||||
if nc.inputHandler != nil {
|
||||
nc.inputHandler(nc.ctx, nc.Id(), msg)
|
||||
if nc.router != nil {
|
||||
nc.router.HandleInput(nc.ctx, nc.Id(), msg)
|
||||
}
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nc.subMu.Lock()
|
||||
nc.sub = sub
|
||||
nc.subMu.Unlock()
|
||||
|
||||
defer sub.Unsubscribe()
|
||||
|
||||
<-nc.ctx.Done()
|
||||
nc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Publish(ctx context.Context, topic string, payload any) error {
|
||||
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
payloadMessage, ok := processor.GetAnyAs[processor.NATSMessage](payload)
|
||||
|
||||
if !ok {
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
if !ok {
|
||||
return errors.New("nats.client is only able to publish bytes or string")
|
||||
}
|
||||
payloadBytes = []byte(payloadString)
|
||||
return errors.New("nats.client is only able to output NATSMessage")
|
||||
}
|
||||
|
||||
nc.clientMu.Lock()
|
||||
defer nc.clientMu.Unlock()
|
||||
|
||||
if nc.client == nil {
|
||||
return errors.New("nats.client client is not setup")
|
||||
}
|
||||
@@ -131,26 +109,15 @@ func (nc *NATSClient) Publish(ctx context.Context, topic string, payload any) er
|
||||
return errors.New("nats.client is not connected")
|
||||
}
|
||||
|
||||
err := nc.client.Publish(topic, payloadBytes)
|
||||
err := nc.client.Publish(payloadMessage.Subject, payloadMessage.Payload)
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Stop() {
|
||||
if nc.cancel != nil {
|
||||
defer nc.cancel()
|
||||
}
|
||||
nc.subMu.Lock()
|
||||
defer nc.subMu.Unlock()
|
||||
if nc.sub != nil {
|
||||
nc.sub.Unsubscribe()
|
||||
}
|
||||
|
||||
nc.clientMu.Lock()
|
||||
defer nc.clientMu.Unlock()
|
||||
if nc.client != nil {
|
||||
nc.client.Drain()
|
||||
// TODO(jwetzell): setup closed callback to get when client is fully closed
|
||||
nc.client.Close()
|
||||
}
|
||||
nc.cancel()
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.client does not support Get")
|
||||
}
|
||||
|
||||
@@ -2,46 +2,33 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
)
|
||||
|
||||
type NATSServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
Ip string
|
||||
Port int
|
||||
router route.RouteIO
|
||||
server *server.Server
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "nats.server",
|
||||
Title: "NATS Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the IP address to bind the NATS server to",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the NATS server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`4222`),
|
||||
},
|
||||
},
|
||||
Required: []string{},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "nats.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
@@ -70,18 +57,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type NATSServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
Ip string
|
||||
Port int
|
||||
inputHandler common.InputHandler
|
||||
server *server.Server
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
serverMu sync.Mutex
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Id() string {
|
||||
return ns.config.Id
|
||||
}
|
||||
@@ -90,46 +65,55 @@ func (ns *NATSServer) Type() string {
|
||||
return ns.config.Type
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (ns *NATSServer) Start(ctx context.Context) error {
|
||||
ns.logger.Debug("running")
|
||||
ns.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.server unable to get router from context")
|
||||
}
|
||||
|
||||
ns.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
ns.ctx = moduleContext
|
||||
ns.cancel = cancel
|
||||
|
||||
natsServer, err := server.NewServer(&server.Options{
|
||||
Host: ns.Ip,
|
||||
Port: ns.Port,
|
||||
NoLog: true,
|
||||
NoSigs: true,
|
||||
Host: ns.Ip,
|
||||
Port: ns.Port,
|
||||
NoLog: true,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ns.serverMu.Lock()
|
||||
ns.server = natsServer
|
||||
natsServer.Start()
|
||||
defer natsServer.Shutdown()
|
||||
|
||||
if !natsServer.ReadyForConnections(5 * time.Second) {
|
||||
return errors.New("nats.server failed to start")
|
||||
}
|
||||
ns.serverMu.Unlock()
|
||||
ns.logger.Info("NATS server started", "client_url", natsServer.ClientURL())
|
||||
|
||||
<-ns.ctx.Done()
|
||||
|
||||
ns.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.ErrUnsupported
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Stop() {
|
||||
if ns.cancel != nil {
|
||||
defer ns.cancel()
|
||||
}
|
||||
ns.serverMu.Lock()
|
||||
defer ns.serverMu.Unlock()
|
||||
ns.cancel()
|
||||
if ns.server != nil {
|
||||
ns.server.Shutdown()
|
||||
ns.server.WaitForShutdown()
|
||||
}
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("nats.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -2,37 +2,38 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/psn-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type PSNClient struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
decoder *psn.Decoder
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "psn.client",
|
||||
Title: "PosiStageNet Client",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "psn.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
|
||||
return &PSNClient{config: config, decoder: psn.NewDecoder(), logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type PSNClient struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
decoder *psn.Decoder
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
connMu sync.Mutex
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Id() string {
|
||||
return pc.config.Id
|
||||
}
|
||||
@@ -41,9 +42,14 @@ func (pc *PSNClient) Type() string {
|
||||
return pc.config.Type
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (pc *PSNClient) Start(ctx context.Context) error {
|
||||
pc.logger.Debug("running")
|
||||
pc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("psn.client unable to get router from context")
|
||||
}
|
||||
pc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
pc.ctx = moduleContext
|
||||
pc.cancel = cancel
|
||||
@@ -57,26 +63,24 @@ func (pc *PSNClient) Start(ctx context.Context, inputHandler common.InputHandler
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
pc.connMu.Lock()
|
||||
pc.conn = client
|
||||
pc.connMu.Unlock()
|
||||
|
||||
buffer := make([]byte, 2048)
|
||||
for pc.ctx.Err() == nil {
|
||||
for {
|
||||
select {
|
||||
case <-pc.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
pc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
pc.connMu.Lock()
|
||||
pc.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := pc.conn.ReadFromUDP(buffer)
|
||||
pc.connMu.Unlock()
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok && opErr.Timeout() {
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
@@ -89,29 +93,34 @@ func (pc *PSNClient) Start(ctx context.Context, inputHandler common.InputHandler
|
||||
pc.logger.Error("problem decoding psn traffic", "error", err)
|
||||
}
|
||||
|
||||
if pc.inputHandler != nil {
|
||||
if pc.router != nil {
|
||||
// TODO(jwetzell): better input handling
|
||||
for _, tracker := range pc.decoder.Trackers {
|
||||
pc.inputHandler(pc.ctx, pc.Id(), tracker)
|
||||
pc.router.HandleInput(pc.ctx, pc.Id(), tracker)
|
||||
}
|
||||
} else {
|
||||
pc.logger.Error("has no input handler")
|
||||
pc.logger.Error("has no router")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
<-pc.ctx.Done()
|
||||
pc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Output(ctx context.Context, payload any) error {
|
||||
return fmt.Errorf("psn.client output is not implemented")
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Stop() {
|
||||
if pc.cancel != nil {
|
||||
defer pc.cancel()
|
||||
}
|
||||
pc.connMu.Lock()
|
||||
defer pc.connMu.Unlock()
|
||||
if pc.conn != nil {
|
||||
pc.conn.Close()
|
||||
pc.cancel()
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "trackers":
|
||||
return pc.decoder.Trackers, nil
|
||||
case "name":
|
||||
return pc.decoder.SystemName, nil
|
||||
default:
|
||||
return nil, errors.New("psn.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "redis.client",
|
||||
Title: "Redis Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Title: "Host",
|
||||
Description: "the hostname or IP address of the Redis server to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port to use when connecting to the Redis server",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, errors.New("redis.client host error: " + err.Error())
|
||||
}
|
||||
|
||||
portInt, err := params.GetInt("port")
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.New("redis.client port error: " + err.Error())
|
||||
}
|
||||
|
||||
return &RedisClient{config: config, Host: hostString, Port: uint16(portInt), logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type RedisClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Host string
|
||||
Port uint16
|
||||
client *redis.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
clientMu sync.Mutex
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Id() string {
|
||||
return rc.config.Id
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Type() string {
|
||||
return rc.config.Type
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Printf(ctx context.Context, format string, v ...any) {
|
||||
msg := fmt.Sprintf(format, v...)
|
||||
rc.logger.Debug(msg)
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
redis.SetLogger(rc)
|
||||
rc.logger.Debug("running")
|
||||
rc.inputHandler = inputHandler
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
rc.ctx = moduleContext
|
||||
rc.cancel = cancel
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: fmt.Sprintf("%s:%d", rc.Host, rc.Port),
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
rc.clientMu.Lock()
|
||||
rc.client = client
|
||||
rc.clientMu.Unlock()
|
||||
|
||||
<-rc.ctx.Done()
|
||||
rc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Stop() {
|
||||
if rc.cancel != nil {
|
||||
defer rc.cancel()
|
||||
}
|
||||
rc.clientMu.Lock()
|
||||
defer rc.clientMu.Unlock()
|
||||
if rc.client != nil {
|
||||
rc.client.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Get(ctx context.Context, key string) (any, error) {
|
||||
if rc.client != nil {
|
||||
val, err := rc.client.Get(ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
return nil, errors.New("redis.client not setup")
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Set(ctx context.Context, key string, value any) error {
|
||||
if rc.client != nil {
|
||||
status := rc.client.Set(ctx, key, value, 0)
|
||||
return status.Err()
|
||||
}
|
||||
return errors.New("redis.client not setup")
|
||||
}
|
||||
@@ -7,44 +7,32 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
type SerialClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Port string
|
||||
Framer framer.Framer
|
||||
Mode *serial.Mode
|
||||
port serial.Port
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "serial.client",
|
||||
Title: "Serial Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the name of the serial port to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"baudRate": {
|
||||
Title: "Baud Rate",
|
||||
Description: "the baud rate to use when connecting to the serial port",
|
||||
Type: "integer",
|
||||
},
|
||||
"framing": {
|
||||
Title: "Framing Method",
|
||||
Description: "the method to use for framing messages on the serial port",
|
||||
Type: "string",
|
||||
Enum: []any{"LF", "CR", "CRLF", "SLIP", "RAW"},
|
||||
},
|
||||
},
|
||||
Required: []string{"port", "baudRate", "framing"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "serial.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
@@ -56,14 +44,12 @@ func init() {
|
||||
return nil, fmt.Errorf("serial.client framing error: %w", err)
|
||||
}
|
||||
|
||||
inFramer := framer.GetFramer(framingMethodString)
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if inFramer == nil {
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("serial.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
outFramer := framer.GetFramer(framingMethodString)
|
||||
|
||||
baudRateInt, err := params.GetInt("baudRate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client baudRate error: %w", err)
|
||||
@@ -73,25 +59,11 @@ func init() {
|
||||
BaudRate: baudRateInt,
|
||||
}
|
||||
|
||||
return &SerialClient{config: config, Port: portString, inFramer: inFramer, outFramer: outFramer, Mode: &mode, logger: CreateLogger(config)}, nil
|
||||
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type SerialClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Port string
|
||||
inFramer framer.Framer
|
||||
outFramer framer.Framer
|
||||
Mode *serial.Mode
|
||||
port serial.Port
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
portMu sync.Mutex
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Id() string {
|
||||
return sc.config.Id
|
||||
}
|
||||
@@ -101,11 +73,10 @@ func (sc *SerialClient) Type() string {
|
||||
}
|
||||
|
||||
func (sc *SerialClient) SetupPort() error {
|
||||
sc.portMu.Lock()
|
||||
defer sc.portMu.Unlock()
|
||||
|
||||
port, err := serial.Open(sc.Port, sc.Mode)
|
||||
if err != nil {
|
||||
return err
|
||||
return fmt.Errorf("serial.client can't open input port: %s", sc.Port)
|
||||
}
|
||||
|
||||
sc.port = port
|
||||
@@ -113,20 +84,36 @@ func (sc *SerialClient) SetupPort() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
sc.logger.Debug("running")
|
||||
sc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client unable to get router from context")
|
||||
}
|
||||
|
||||
sc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
sc.ctx = moduleContext
|
||||
sc.cancel = cancel
|
||||
|
||||
for sc.ctx.Err() == nil {
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-sc.ctx.Done()
|
||||
sc.logger.Debug("done")
|
||||
if sc.port != nil {
|
||||
sc.port.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
err := sc.SetupPort()
|
||||
if err != nil {
|
||||
if sc.ctx.Err() != nil {
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
sc.logger.Error("port setup error", "port", sc.Port, "error", err.Error())
|
||||
sc.logger.Error("port setup error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
@@ -134,27 +121,29 @@ func (sc *SerialClient) Start(ctx context.Context, inputHandler common.InputHand
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for sc.ctx.Err() == nil {
|
||||
for {
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := sc.port.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
sc.inFramer.Clear()
|
||||
sc.Framer.Clear()
|
||||
break READ
|
||||
}
|
||||
|
||||
if sc.inFramer != nil {
|
||||
if sc.Framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := sc.inFramer.Decode(buffer[0:byteCount])
|
||||
messages := sc.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if sc.inputHandler != nil {
|
||||
sc.inputHandler(sc.ctx, sc.Id(), message)
|
||||
if sc.router != nil {
|
||||
sc.router.HandleInput(sc.ctx, sc.Id(), message)
|
||||
} else {
|
||||
sc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
@@ -165,38 +154,29 @@ func (sc *SerialClient) Start(ctx context.Context, inputHandler common.InputHand
|
||||
}
|
||||
}
|
||||
}
|
||||
<-sc.ctx.Done()
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client can only output bytes")
|
||||
return errors.New("serial.client can only ouptut bytes")
|
||||
}
|
||||
|
||||
_, err := sc.port.Write(sc.outFramer.Encode(payloadBytes))
|
||||
_, err := sc.port.Write(sc.Framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Stop() {
|
||||
if sc.cancel != nil {
|
||||
defer sc.cancel()
|
||||
}
|
||||
sc.portMu.Lock()
|
||||
defer sc.portMu.Unlock()
|
||||
if sc.port != nil {
|
||||
sc.port.Close()
|
||||
}
|
||||
sc.cancel()
|
||||
}
|
||||
|
||||
if sc.inFramer != nil {
|
||||
sc.inFramer.Clear()
|
||||
}
|
||||
|
||||
if sc.outFramer != nil {
|
||||
sc.outFramer.Clear()
|
||||
func (sc *SerialClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "port":
|
||||
return sc.Port, nil
|
||||
default:
|
||||
return nil, errors.New("serial.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,12 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -15,51 +15,41 @@ import (
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
type SIPCallServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
RecordingPath string
|
||||
dg *diago.Diago
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SIPCallMessage struct {
|
||||
To string
|
||||
}
|
||||
|
||||
type SIPCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
type sipCallContextKey string
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "sip.call.server",
|
||||
Title: "SIP Call Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the IP address to bind the SIP server to",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the SIP server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`5060`),
|
||||
},
|
||||
"transport": {
|
||||
Title: "Transport",
|
||||
Description: "the transport protocol to use for the SIP server",
|
||||
Type: "string",
|
||||
Enum: []any{"udp", "tcp", "ws", "udp4", "tcp4"},
|
||||
Default: json.RawMessage(`"udp"`),
|
||||
},
|
||||
"userAgent": {
|
||||
Title: "User Agent",
|
||||
Description: "the user agent string to use",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"showbridge"`),
|
||||
},
|
||||
},
|
||||
Required: []string{},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "sip.call.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
@@ -98,36 +88,23 @@ func init() {
|
||||
}
|
||||
}
|
||||
|
||||
return &SIPCallServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: CreateLogger(moduleConfig)}, nil
|
||||
recordingPathString := ""
|
||||
|
||||
recordingPath, ok := params["recordingPath"]
|
||||
if ok {
|
||||
specificRecordingPath, ok := recordingPath.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.call.server recordingPath must be a string")
|
||||
}
|
||||
recordingPathString = specificRecordingPath
|
||||
}
|
||||
|
||||
return &SIPCallServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, RecordingPath: recordingPathString, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type SIPCallServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
ua *sipgo.UserAgent
|
||||
uaMu sync.Mutex
|
||||
}
|
||||
|
||||
type SIPCallMessage struct {
|
||||
To string
|
||||
}
|
||||
|
||||
type SIPCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
type sipCallContextKey string
|
||||
|
||||
func (scs *SIPCallServer) Id() string {
|
||||
return scs.config.Id
|
||||
}
|
||||
@@ -136,9 +113,14 @@ func (scs *SIPCallServer) Type() string {
|
||||
return scs.config.Type
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (scs *SIPCallServer) Start(ctx context.Context) error {
|
||||
scs.logger.Debug("running")
|
||||
scs.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.call.server unable to get router from context")
|
||||
}
|
||||
scs.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
scs.ctx = moduleContext
|
||||
scs.cancel = cancel
|
||||
@@ -150,9 +132,7 @@ func (scs *SIPCallServer) Start(ctx context.Context, inputHandler common.InputHa
|
||||
sipgo.WithUserAgentTransportLayerOptions(sip.WithTransportLayerLogger(diagoLogger)),
|
||||
sipgo.WithUserAgentTransactionLayerOptions(sip.WithTransactionLayerLogger(diagoLogger)),
|
||||
)
|
||||
scs.uaMu.Lock()
|
||||
scs.ua = ua
|
||||
scs.uaMu.Unlock()
|
||||
defer ua.Close()
|
||||
|
||||
sip.SetDefaultLogger(diagoLogger)
|
||||
media.SetDefaultLogger(diagoLogger)
|
||||
@@ -164,12 +144,13 @@ func (scs *SIPCallServer) Start(ctx context.Context, inputHandler common.InputHa
|
||||
},
|
||||
))
|
||||
|
||||
err := dg.Serve(scs.ctx, func(inDialog *diago.DialogServerSession) {
|
||||
scs.HandleCall(inDialog)
|
||||
})
|
||||
if err != nil {
|
||||
scs.logger.Error("diago serve error", "error", err)
|
||||
}
|
||||
go func() {
|
||||
dg.Serve(scs.ctx, func(inDialog *diago.DialogServerSession) {
|
||||
scs.HandleCall(inDialog)
|
||||
})
|
||||
}()
|
||||
|
||||
scs.dg = dg
|
||||
|
||||
<-scs.ctx.Done()
|
||||
scs.logger.Debug("done")
|
||||
@@ -184,11 +165,44 @@ func (scs *SIPCallServer) HandleCall(inDialog *diago.DialogServerSession) {
|
||||
dialogContext := context.WithValue(scs.ctx, sipCallContextKey("call"), &SIPCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
if scs.inputHandler != nil {
|
||||
scs.inputHandler(dialogContext, scs.Id(), SIPCallMessage{
|
||||
To: inDialog.ToUser(),
|
||||
})
|
||||
|
||||
if scs.RecordingPath != "" {
|
||||
filename := path.Join(scs.RecordingPath, fmt.Sprintf("%s-%d.wav", inDialog.ToUser(), time.Now().Unix()))
|
||||
wavFile, err := os.OpenFile(filename, os.O_RDWR|os.O_CREATE, 0755)
|
||||
if err != nil {
|
||||
scs.logger.Error("error creating recording file", "error", err, "filename", filename)
|
||||
} else {
|
||||
recorder, err := inDialog.AudioStereoRecordingCreate(wavFile)
|
||||
if err != nil {
|
||||
scs.logger.Error("error creating recording", "error", err)
|
||||
wavFile.Close()
|
||||
} else {
|
||||
go func() {
|
||||
<-inDialog.Context().Done()
|
||||
err := recorder.Close()
|
||||
if err != nil {
|
||||
scs.logger.Error("error closing recording", "error", err)
|
||||
}
|
||||
wavFile.Close()
|
||||
scs.logger.Debug("finished recording", "filename", filename)
|
||||
}()
|
||||
|
||||
go func() {
|
||||
bytes, err := media.Copy(recorder.AudioReader(), recorder.AudioWriter())
|
||||
fmt.Println("recorded bytes", bytes)
|
||||
if err != nil {
|
||||
if !errors.Is(err, io.EOF) {
|
||||
scs.logger.Error("error while recording", "error", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
scs.router.HandleInput(dialogContext, scs.Id(), SIPCallMessage{
|
||||
To: inDialog.ToUser(),
|
||||
})
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
@@ -209,13 +223,10 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.call.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter, err := call.inDialog.AudioWriterDTMF()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
err := dtmfWriter.WriteDTMF(dtmfRune)
|
||||
@@ -228,7 +239,7 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
@@ -258,12 +269,9 @@ func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Stop() {
|
||||
if scs.cancel != nil {
|
||||
defer scs.cancel()
|
||||
}
|
||||
scs.uaMu.Lock()
|
||||
defer scs.uaMu.Unlock()
|
||||
if scs.ua != nil {
|
||||
scs.ua.Close()
|
||||
}
|
||||
scs.cancel()
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.call.server does not support Get")
|
||||
}
|
||||
|
||||
@@ -2,7 +2,6 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -16,58 +15,39 @@ import (
|
||||
"github.com/emiago/diago/media"
|
||||
"github.com/emiago/sipgo"
|
||||
"github.com/emiago/sipgo/sip"
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
type SIPDTMFServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
Separator string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SIPDTMFMessage struct {
|
||||
To string
|
||||
Digits string
|
||||
}
|
||||
|
||||
type SIPDTMFCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "sip.dtmf.server",
|
||||
Title: "SIP DTMF Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the IP address to bind the SIP server to",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the SIP server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`5060`),
|
||||
},
|
||||
"transport": {
|
||||
Title: "Transport",
|
||||
Description: "the transport protocol to use for the SIP server",
|
||||
Type: "string",
|
||||
Enum: []any{"udp", "tcp", "ws", "udp4", "tcp4"},
|
||||
Default: json.RawMessage(`"udp"`),
|
||||
},
|
||||
"userAgent": {
|
||||
Title: "User Agent",
|
||||
Description: "the user agent string to use",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"showbridge"`),
|
||||
},
|
||||
"separator": {
|
||||
Title: "DTMF Separator",
|
||||
Description: "the DTMF character to use as a separator between DTMF digit groups",
|
||||
Type: "string",
|
||||
MinLength: new(1),
|
||||
MaxLength: new(1),
|
||||
},
|
||||
},
|
||||
Required: []string{"separator"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "sip.dtmf.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
portNum, err := params.GetInt("port")
|
||||
@@ -124,31 +104,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type SIPDTMFServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
Separator string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
ua *sipgo.UserAgent
|
||||
uaMu sync.Mutex
|
||||
}
|
||||
|
||||
type SIPDTMFMessage struct {
|
||||
To string
|
||||
Digits string
|
||||
}
|
||||
|
||||
type SIPDTMFCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Id() string {
|
||||
return sds.config.Id
|
||||
}
|
||||
@@ -157,9 +112,14 @@ func (sds *SIPDTMFServer) Type() string {
|
||||
return sds.config.Type
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (sds *SIPDTMFServer) Start(ctx context.Context) error {
|
||||
sds.logger.Debug("running")
|
||||
sds.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.dtmf.server unable to get router from context")
|
||||
}
|
||||
sds.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
sds.ctx = moduleContext
|
||||
sds.cancel = cancel
|
||||
@@ -171,10 +131,7 @@ func (sds *SIPDTMFServer) Start(ctx context.Context, inputHandler common.InputHa
|
||||
sipgo.WithUserAgentTransportLayerOptions(sip.WithTransportLayerLogger(diagoLogger)),
|
||||
sipgo.WithUserAgentTransactionLayerOptions(sip.WithTransactionLayerLogger(diagoLogger)),
|
||||
)
|
||||
|
||||
sds.uaMu.Lock()
|
||||
sds.ua = ua
|
||||
sds.uaMu.Unlock()
|
||||
defer ua.Close()
|
||||
|
||||
sip.SetDefaultLogger(diagoLogger)
|
||||
media.SetDefaultLogger(diagoLogger)
|
||||
@@ -204,19 +161,16 @@ func (sds *SIPDTMFServer) HandleCall(inDialog *diago.DialogServerSession) error
|
||||
inDialog.Ringing()
|
||||
inDialog.Answer()
|
||||
|
||||
reader, err := inDialog.AudioReaderDTMF()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reader := inDialog.AudioReaderDTMF()
|
||||
userString := ""
|
||||
|
||||
return reader.Listen(func(dtmf rune) error {
|
||||
if dtmf == rune(sds.Separator[0]) {
|
||||
if sds.inputHandler != nil {
|
||||
if sds.router != nil {
|
||||
dialogContext := context.WithValue(sds.ctx, sipCallContextKey("call"), &SIPDTMFCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
sds.inputHandler(dialogContext, sds.Id(), SIPDTMFMessage{
|
||||
sds.router.HandleInput(dialogContext, sds.Id(), SIPDTMFMessage{
|
||||
To: inDialog.ToUser(),
|
||||
Digits: userString,
|
||||
})
|
||||
@@ -246,13 +200,10 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("sip.dtmf.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
payloadDTMFResponse, ok := processor.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter, err := call.inDialog.AudioWriterDTMF()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
@@ -266,7 +217,7 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
payloadAudioFileResponse, ok := processor.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
@@ -297,12 +248,9 @@ func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Stop() {
|
||||
if sds.cancel != nil {
|
||||
defer sds.cancel()
|
||||
}
|
||||
sds.uaMu.Lock()
|
||||
defer sds.uaMu.Unlock()
|
||||
if sds.ua != nil {
|
||||
sds.ua.Close()
|
||||
}
|
||||
sds.cancel()
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Get(key string) (any, error) {
|
||||
return nil, errors.New("sip.dtmf.server does not support Get")
|
||||
}
|
||||
|
||||
+86
-102
@@ -6,45 +6,30 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TCPClient struct {
|
||||
config config.ModuleConfig
|
||||
framer framer.Framer
|
||||
conn *net.TCPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Addr *net.TCPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.tcp.client",
|
||||
Title: "TCP Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Title: "Host",
|
||||
Description: "the hostname or IP address of the TCP server to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port of the TCP server to connect to",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"framing": {
|
||||
Title: "Framing Method",
|
||||
Description: "the method used to frame messages over the TCP connection",
|
||||
Type: "string",
|
||||
Enum: []any{"LF", "CR", "CRLF", "SLIP", "RAW"},
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port", "framing"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "net.tcp.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
@@ -66,31 +51,16 @@ func init() {
|
||||
return nil, fmt.Errorf("net.tcp.client framing error: %w", err)
|
||||
}
|
||||
|
||||
inFramer := framer.GetFramer(framingMethodString)
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if inFramer == nil {
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
outFramer := framer.GetFramer(framingMethodString)
|
||||
return &TCPClient{inFramer: inFramer, outFramer: outFramer, Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
return &TCPClient{framer: framer, Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type TCPClient struct {
|
||||
config config.ModuleConfig
|
||||
inFramer framer.Framer
|
||||
outFramer framer.Framer
|
||||
conn *net.TCPConn
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Addr *net.TCPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
connMu sync.Mutex
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Id() string {
|
||||
return tc.config.Id
|
||||
}
|
||||
@@ -99,19 +69,33 @@ func (tc *TCPClient) Type() string {
|
||||
return tc.config.Type
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (tc *TCPClient) Start(ctx context.Context) error {
|
||||
tc.logger.Debug("running")
|
||||
tc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
}
|
||||
tc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
tc.ctx = moduleContext
|
||||
tc.cancel = cancel
|
||||
|
||||
CONNECT_RETRY:
|
||||
for tc.ctx.Err() == nil {
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-tc.ctx.Done()
|
||||
tc.logger.Debug("done")
|
||||
if tc.conn != nil {
|
||||
tc.conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
err := tc.SetupConn()
|
||||
if err != nil {
|
||||
if tc.ctx.Err() != nil {
|
||||
break CONNECT_RETRY
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
tc.logger.Error("connection error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
@@ -119,82 +103,82 @@ CONNECT_RETRY:
|
||||
}
|
||||
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for {
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := tc.conn.Read(buffer)
|
||||
|
||||
READ:
|
||||
for tc.ctx.Err() == nil {
|
||||
tc.conn.SetReadDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
byteCount, err := tc.conn.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr.Timeout() {
|
||||
continue
|
||||
if err != nil {
|
||||
tc.framer.Clear()
|
||||
break READ
|
||||
}
|
||||
}
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
break CONNECT_RETRY
|
||||
}
|
||||
break READ
|
||||
}
|
||||
|
||||
if tc.inFramer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := tc.inFramer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if tc.inputHandler != nil {
|
||||
tc.inputHandler(tc.ctx, tc.Id(), message)
|
||||
} else {
|
||||
tc.logger.Error("input received but no input handler is configured")
|
||||
if tc.framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := tc.framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if tc.router != nil {
|
||||
tc.router.HandleInput(tc.ctx, tc.Id(), message)
|
||||
} else {
|
||||
tc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
<-tc.ctx.Done()
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (tc *TCPClient) SetupConn() error {
|
||||
tc.connMu.Lock()
|
||||
defer tc.connMu.Unlock()
|
||||
client, err := net.DialTCP("tcp", nil, tc.Addr)
|
||||
tc.conn = client
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
tc.connMu.Lock()
|
||||
defer tc.connMu.Unlock()
|
||||
// NOTE(jwetzell): not sure how this would occur but
|
||||
if tc.conn == nil {
|
||||
return errors.New("net.tcp.client client is not setup")
|
||||
err := tc.SetupConn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client is only able to output bytes")
|
||||
}
|
||||
_, err := tc.conn.Write(tc.inFramer.Encode(payloadBytes))
|
||||
_, err := tc.conn.Write(tc.framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Stop() {
|
||||
if tc.cancel != nil {
|
||||
defer tc.cancel()
|
||||
}
|
||||
tc.connMu.Lock()
|
||||
defer tc.connMu.Unlock()
|
||||
if tc.conn != nil {
|
||||
tc.conn.Close()
|
||||
}
|
||||
tc.cancel()
|
||||
}
|
||||
|
||||
if tc.inFramer != nil {
|
||||
tc.inFramer.Clear()
|
||||
}
|
||||
|
||||
if tc.outFramer != nil {
|
||||
tc.outFramer.Clear()
|
||||
func (tc *TCPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := tc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return tc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return tc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
+122
-139
@@ -2,53 +2,40 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TCPServer struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.TCPAddr
|
||||
Framer framer.Framer
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
quit chan interface{}
|
||||
wg sync.WaitGroup
|
||||
connections []*net.TCPConn
|
||||
connectionsMu sync.RWMutex
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.tcp.server",
|
||||
Title: "TCP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the IP address to bind the TCP server to",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the TCP server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"framing": {
|
||||
Title: "Framing Method",
|
||||
Description: "the method used to frame messages over the TCP connection",
|
||||
Type: "string",
|
||||
Enum: []any{"LF", "CR", "CRLF", "SLIP", "RAW"},
|
||||
},
|
||||
},
|
||||
Required: []string{"port", "framing"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "net.tcp.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
@@ -60,14 +47,12 @@ func init() {
|
||||
return nil, fmt.Errorf("net.tcp.server framing error: %w", err)
|
||||
}
|
||||
|
||||
inFramer := framer.GetFramer(framingMethodString)
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if inFramer == nil {
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.server unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
outFramer := framer.GetFramer(framingMethodString)
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
@@ -81,35 +66,11 @@ func init() {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &TCPServer{inFramer: inFramer, outFramer: outFramer, framerType: framingMethodString, Addr: addr, config: moduleConfig, logger: CreateLogger(moduleConfig)}, nil
|
||||
return &TCPServer{Framer: framer, Addr: addr, config: moduleConfig, quit: make(chan interface{}), logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type tcpConnection struct {
|
||||
conn *net.TCPConn
|
||||
framer framer.Framer
|
||||
}
|
||||
|
||||
type TCPServer struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.TCPAddr
|
||||
inFramer framer.Framer
|
||||
outFramer framer.Framer
|
||||
framerType string
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
wg sync.WaitGroup
|
||||
connections []tcpConnection
|
||||
connectionsMu sync.RWMutex
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
listener *net.TCPListener
|
||||
listenerMu sync.Mutex
|
||||
connectionShutdownCtx context.Context
|
||||
connectionShutdown context.CancelFunc
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Id() string {
|
||||
return ts.config.Id
|
||||
}
|
||||
@@ -120,44 +81,71 @@ func (ts *TCPServer) Type() string {
|
||||
|
||||
func (ts *TCPServer) handleClient(client *net.TCPConn) {
|
||||
ts.connectionsMu.Lock()
|
||||
ts.connections = append(ts.connections, tcpConnection{conn: client, framer: framer.GetFramer(ts.framerType)})
|
||||
ts.connections = append(ts.connections, client)
|
||||
ts.connectionsMu.Unlock()
|
||||
ts.logger.Debug("connection accepted", "remoteAddr", client.RemoteAddr().String())
|
||||
defer func() {
|
||||
client.Close()
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i].conn == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.connectionsMu.Unlock()
|
||||
ts.logger.Debug("connection closed", "remoteAddr", client.RemoteAddr().String())
|
||||
}()
|
||||
ts.logger.Debug("net.tcp.server connection accepted", "remoteAddr", client.RemoteAddr().String())
|
||||
defer client.Close()
|
||||
|
||||
buffer := make([]byte, 1024)
|
||||
for ts.ctx.Err() == nil && ts.connectionShutdownCtx.Err() == nil {
|
||||
client.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
byteCount, err := client.Read(buffer)
|
||||
if err != nil {
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr.Timeout() {
|
||||
continue
|
||||
ClientRead:
|
||||
for {
|
||||
select {
|
||||
case <-ts.quit:
|
||||
client.Close()
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
break
|
||||
}
|
||||
if ts.inFramer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := ts.inFramer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if ts.inputHandler != nil {
|
||||
ts.inputHandler(ts.ctx, ts.Id(), message)
|
||||
} else {
|
||||
ts.logger.Error("input received but no input handler is configured")
|
||||
ts.connectionsMu.Unlock()
|
||||
return
|
||||
default:
|
||||
client.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
byteCount, err := client.Read(buffer)
|
||||
|
||||
if err != nil {
|
||||
if opErr, ok := err.(*net.OpError); ok {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr.Timeout() {
|
||||
continue ClientRead
|
||||
}
|
||||
if errors.Is(opErr, syscall.ECONNRESET) {
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("connection reset", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
if err.Error() == "EOF" {
|
||||
ts.connectionsMu.Lock()
|
||||
for i := 0; i < len(ts.connections); i++ {
|
||||
if ts.connections[i] == client {
|
||||
ts.connections = slices.Delete(ts.connections, i, i+1)
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("stream ended", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
return
|
||||
}
|
||||
if ts.Framer != nil {
|
||||
if byteCount > 0 {
|
||||
messages := ts.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if ts.router != nil {
|
||||
ts.router.HandleInput(ts.ctx, ts.Id(), message)
|
||||
} else {
|
||||
ts.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,94 +153,89 @@ func (ts *TCPServer) handleClient(client *net.TCPConn) {
|
||||
}
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (ts *TCPServer) Start(ctx context.Context) error {
|
||||
ts.logger.Debug("running")
|
||||
ts.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server unable to get router from context")
|
||||
}
|
||||
ts.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
ts.ctx = moduleContext
|
||||
ts.cancel = cancel
|
||||
|
||||
shutdownCtx, shutdownCancel := context.WithCancel(context.Background())
|
||||
ts.connectionShutdownCtx = shutdownCtx
|
||||
ts.connectionShutdown = shutdownCancel
|
||||
|
||||
listener, err := net.ListenTCP("tcp", ts.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ts.listenerMu.Lock()
|
||||
ts.listener = listener
|
||||
ts.listenerMu.Unlock()
|
||||
ts.wg.Add(1)
|
||||
|
||||
go func() {
|
||||
<-ts.ctx.Done()
|
||||
close(ts.quit)
|
||||
listener.Close()
|
||||
ts.logger.Debug("done")
|
||||
}()
|
||||
|
||||
AcceptLoop:
|
||||
for ts.ctx.Err() == nil {
|
||||
for {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
break AcceptLoop
|
||||
}
|
||||
select {
|
||||
case <-ts.ctx.Done():
|
||||
case <-ts.quit:
|
||||
break AcceptLoop
|
||||
default:
|
||||
ts.logger.Debug("problem with listener", "error", err)
|
||||
}
|
||||
} else {
|
||||
ts.wg.Go(func() {
|
||||
ts.wg.Add(1)
|
||||
go func() {
|
||||
ts.handleClient(conn)
|
||||
})
|
||||
ts.wg.Done()
|
||||
}()
|
||||
}
|
||||
}
|
||||
ts.wg.Done()
|
||||
<-ts.ctx.Done()
|
||||
ts.logger.Debug("done")
|
||||
ts.wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server is only able to output bytes")
|
||||
}
|
||||
ts.connectionsMu.Lock()
|
||||
defer ts.connectionsMu.Unlock()
|
||||
var errorString strings.Builder
|
||||
|
||||
if ts.outFramer == nil {
|
||||
return errors.New("no output framer configured")
|
||||
}
|
||||
|
||||
outputBytes := ts.outFramer.Encode(payloadBytes)
|
||||
errorString := ""
|
||||
|
||||
for _, connection := range ts.connections {
|
||||
_, err := connection.conn.Write(outputBytes)
|
||||
_, err := connection.Write(payloadBytes)
|
||||
if err != nil {
|
||||
fmt.Fprintf(&errorString, "%s\n", err.Error())
|
||||
errorString += fmt.Sprintf("%s\n", err.Error())
|
||||
}
|
||||
}
|
||||
ts.connectionsMu.Unlock()
|
||||
|
||||
if errorString.String() == "" {
|
||||
if errorString == "" {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("net.tcp.server error during output: %s", errorString.String())
|
||||
return fmt.Errorf("net.tcp.server error during output: %s", errorString)
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Stop() {
|
||||
if ts.cancel != nil {
|
||||
defer ts.cancel()
|
||||
}
|
||||
if ts.connectionShutdown != nil {
|
||||
ts.connectionShutdown()
|
||||
}
|
||||
|
||||
ts.listenerMu.Lock()
|
||||
defer ts.listenerMu.Unlock()
|
||||
if ts.listener != nil {
|
||||
ts.listener.Close()
|
||||
}
|
||||
ts.logger.Debug("waiting for connections to close")
|
||||
ts.cancel()
|
||||
ts.wg.Wait()
|
||||
ts.logger.Debug("all connections closed")
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return ts.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return ts.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.tcp.server key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,139 +0,0 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestDbSqliteFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("db.sqlite")
|
||||
if !ok {
|
||||
t.Fatalf("db.sqlite module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "db.sqlite",
|
||||
Params: map[string]any{
|
||||
"dsn": ":memory:",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create db.sqlite module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("db.sqlite module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "db.sqlite" {
|
||||
t.Fatalf("db.sqlite module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodDbSqlite(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "in memory db",
|
||||
params: map[string]any{
|
||||
"dsn": ":memory:",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "file db",
|
||||
params: map[string]any{
|
||||
"dsn": "test.db",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("db.sqlite")
|
||||
if !ok {
|
||||
t.Fatalf("db.sqlite module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "db.sqlite",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("db.sqlite failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("db.sqlite failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadDbSqlite(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no dsn param",
|
||||
params: map[string]any{},
|
||||
errorString: "db.sqlite dsn error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string dsn",
|
||||
params: map[string]any{"dsn": 123},
|
||||
errorString: "db.sqlite dsn error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("db.sqlite")
|
||||
if !ok {
|
||||
t.Fatalf("db.sqlite module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "db.sqlite",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("db.sqlite got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("db.sqlite expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("db.sqlite got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestHTTPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["http.client"]
|
||||
if !ok {
|
||||
t.Fatalf("http.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.client",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create http.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("http.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "http.client" {
|
||||
t.Fatalf("http.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadHTTPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["http.client"]
|
||||
if !ok {
|
||||
t.Fatalf("http.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("http.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("http.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("http.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestHTTPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("http.server")
|
||||
registration, ok := module.ModuleRegistry["http.server"]
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
@@ -35,52 +34,6 @@ func TestHTTPServerFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodHTTPServer(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("http.server")
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("http.server failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("http.server failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadHTTPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -102,7 +55,7 @@ func TestBadHTTPServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("http.server")
|
||||
registration, ok := module.ModuleRegistry["http.server"]
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
@@ -120,7 +73,7 @@ func TestBadHTTPServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("http.server expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestMIDIInputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("midi.input")
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func TestBadMIDIInput(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("midi.input")
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
@@ -73,7 +73,7 @@ func TestBadMIDIInput(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.input expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestMIDIOutputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("midi.output")
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
@@ -55,7 +55,7 @@ func TestBadMIDIOutput(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("midi.output")
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
@@ -73,7 +73,7 @@ func TestBadMIDIOutput(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.output expected to fail")
|
||||
|
||||
@@ -1,34 +1,57 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/test"
|
||||
)
|
||||
|
||||
type TestModule struct {
|
||||
}
|
||||
|
||||
func (m *TestModule) Output(ctx context.Context, payload any) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *TestModule) Start(ctx context.Context) error {
|
||||
<-ctx.Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *TestModule) Stop() {}
|
||||
|
||||
func (m *TestModule) Type() string {
|
||||
return "module.test"
|
||||
}
|
||||
|
||||
func (m *TestModule) Id() string {
|
||||
return "test"
|
||||
}
|
||||
|
||||
func (m *TestModule) Get(key string) (any, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoType(t *testing.T) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("module registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
return test.NewTestModule("test"), nil
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoNew(t *testing.T) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("processor registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
@@ -41,23 +64,22 @@ func TestModuleBadRegistrationNoNew(t *testing.T) {
|
||||
|
||||
func TestModuleBadRegistrationExistingType(t *testing.T) {
|
||||
defer func() {
|
||||
r := recover()
|
||||
if r == nil {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("processor registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
return test.NewTestModule("test"), nil
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
return test.NewTestModule("test"), nil
|
||||
New: func(config config.ModuleConfig) (module.Module, error) {
|
||||
return &TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestMQTTClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("mqtt.client")
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
@@ -98,7 +98,7 @@ func TestBadMQTTClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("mqtt.client")
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestBadMQTTClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("mqtt.client expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestNATSClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("nats.client")
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
@@ -76,7 +76,7 @@ func TestBadNATSClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("nats.client")
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
@@ -94,7 +94,7 @@ func TestBadNATSClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.client expected to fail")
|
||||
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestNATSServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("nats.server")
|
||||
registration, ok := module.ModuleRegistry["nats.server"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
@@ -36,52 +35,6 @@ func TestNATSServerFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodNATSServer(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"port": 4222,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("nats.server")
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("nats.server failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("nats.server failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadNATSServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -100,7 +53,7 @@ func TestBadNATSServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("nats.server")
|
||||
registration, ok := module.ModuleRegistry["nats.server"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
@@ -118,7 +71,7 @@ func TestBadNATSServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.server expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestPSNClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("psn.client")
|
||||
registration, ok := module.ModuleRegistry["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
@@ -41,7 +41,7 @@ func TestBadPSNClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("psn.client")
|
||||
registration, ok := module.ModuleRegistry["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
@@ -59,7 +59,7 @@ func TestBadPSNClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("psn.client expected to fail")
|
||||
|
||||
@@ -1,108 +0,0 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestRedisClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("redis.client")
|
||||
if !ok {
|
||||
t.Fatalf("redis.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "redis.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 6379,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create redis.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("redis.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "redis.client" {
|
||||
t.Fatalf("redis.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadRedisClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 6379,
|
||||
},
|
||||
errorString: "redis.client host error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string host",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 6379,
|
||||
},
|
||||
errorString: "redis.client host error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
},
|
||||
errorString: "redis.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": "6379",
|
||||
},
|
||||
errorString: "redis.client port error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("redis.client")
|
||||
if !ok {
|
||||
t.Fatalf("redis.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "redis.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("redis.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("redis.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("redis.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestSerialClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("serial.client")
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func TestBadSerialClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("serial.client")
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
@@ -103,7 +103,7 @@ func TestBadSerialClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("serial.client expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestSIPCallServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("sip.call.server")
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
@@ -70,7 +70,7 @@ func TestBadSIPCallServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("sip.call.server")
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
@@ -88,7 +88,7 @@ func TestBadSIPCallServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.call.server expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestSIPDTMFServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("sip.dtmf.server")
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
@@ -89,7 +89,7 @@ func TestBadSIPDTMFServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("sip.dtmf.server")
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
@@ -107,7 +107,7 @@ func TestBadSIPDTMFServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.dtmf.server expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestTCPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("net.tcp.client")
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
@@ -77,7 +77,7 @@ func TestBadTCPClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.tcp.client")
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func TestBadTCPClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.client expected to fail")
|
||||
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTCPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("net.tcp.server")
|
||||
registration, ok := module.ModuleRegistry["net.tcp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.server module not registered")
|
||||
}
|
||||
@@ -36,52 +35,6 @@ func TestTCPServerFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodTCPServer(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.tcp.server")
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.tcp.server failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.tcp.server failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTCPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -149,7 +102,7 @@ func TestBadTCPServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.tcp.server")
|
||||
registration, ok := module.ModuleRegistry["net.tcp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.server module not registered")
|
||||
}
|
||||
@@ -167,7 +120,7 @@ func TestBadTCPServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.server expected to fail")
|
||||
|
||||
Binary file not shown.
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeIntervalFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("time.interval")
|
||||
registration, ok := module.ModuleRegistry["time.interval"]
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
@@ -35,51 +34,6 @@ func TestTimeIntervalFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodTimeInterval(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"duration": 1000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("time.interval")
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.interval",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("time.interval failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("time.interval failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeInterval(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -103,7 +57,7 @@ func TestBadTimeInterval(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("time.interval")
|
||||
registration, ok := module.ModuleRegistry["time.interval"]
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
@@ -121,7 +75,7 @@ func TestBadTimeInterval(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.interval expected to fail")
|
||||
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeTimerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("time.timer")
|
||||
registration, ok := module.ModuleRegistry["time.timer"]
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
@@ -35,51 +34,6 @@ func TestTimeTimerFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodTimeTimer(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"duration": 2000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("time.timer")
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.timer",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("time.timer failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("time.timer failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeTimer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -103,7 +57,7 @@ func TestBadTimeTimer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("time.timer")
|
||||
registration, ok := module.ModuleRegistry["time.timer"]
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
@@ -121,7 +75,7 @@ func TestBadTimeTimer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.timer expected to fail")
|
||||
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("net.udp.client")
|
||||
registration, ok := module.ModuleRegistry["net.udp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.client module not registered")
|
||||
}
|
||||
@@ -37,53 +36,6 @@ func TestUDPClientFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodUDPClient(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.udp.client")
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.udp.client failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.udp.client failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -125,7 +77,7 @@ func TestBadUDPClient(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.udp.client")
|
||||
registration, ok := module.ModuleRegistry["net.udp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.client module not registered")
|
||||
}
|
||||
@@ -143,7 +95,7 @@ func TestBadUDPClient(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.client expected to fail")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
func TestUDPMulticastFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("net.udp.multicast")
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.multicast module not registered")
|
||||
}
|
||||
@@ -84,7 +84,7 @@ func TestBadUDPMulticast(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.udp.multicast")
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.multicast module not registered")
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func TestBadUDPMulticast(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.multicast expected to fail")
|
||||
|
||||
@@ -2,14 +2,13 @@ package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("net.udp.server")
|
||||
registration, ok := module.ModuleRegistry["net.udp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.server module not registered")
|
||||
}
|
||||
@@ -35,52 +34,6 @@ func TestUDPServerFromRegistry(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodUDPServer(t *testing.T) {
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
}{
|
||||
{
|
||||
name: "minimal config",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range testCases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.udp.server")
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.udp.server failed to create module: %s", err)
|
||||
}
|
||||
// TODO(jwetzell) this is kind of hacky
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
moduleInstance.Stop()
|
||||
}()
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("net.udp.server failed to start: %s", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -128,7 +81,7 @@ func TestBadUDPServer(t *testing.T) {
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("net.udp.server")
|
||||
registration, ok := module.ModuleRegistry["net.udp.server"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.server module not registered")
|
||||
}
|
||||
@@ -146,7 +99,7 @@ func TestBadUDPServer(t *testing.T) {
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.server expected to fail")
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestWebSocketClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.GetModuleRegistration("websocket.client")
|
||||
if !ok {
|
||||
t.Fatalf("websocket.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "websocket.client",
|
||||
Params: map[string]any{
|
||||
"url": "ws://localhost",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create websocket.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("websocket.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "websocket.client" {
|
||||
t.Fatalf("websocket.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadWebSocketClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no url param",
|
||||
params: map[string]any{},
|
||||
errorString: "websocket.client url error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string url param",
|
||||
params: map[string]any{
|
||||
"url": 123,
|
||||
},
|
||||
errorString: "websocket.client url error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid url param",
|
||||
params: map[string]any{
|
||||
"url": "invalid-url",
|
||||
},
|
||||
errorString: "websocket.client url error: scheme must be ws or wss",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.GetModuleRegistration("websocket.client")
|
||||
if !ok {
|
||||
t.Fatalf("websocket.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "websocket.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("websocket.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context(), nil)
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("websocket.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("websocket.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,32 +2,30 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TimeInterval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
ticker *time.Ticker
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "time.interval",
|
||||
Title: "Interval",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"duration": {
|
||||
Title: "Duration",
|
||||
Description: "time in milliseconds between emitted events",
|
||||
Type: "integer",
|
||||
},
|
||||
},
|
||||
Required: []string{"duration"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "time.interval",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationInt, err := params.GetInt("duration")
|
||||
@@ -39,16 +37,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type TimeInterval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
ticker *time.Ticker
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Id() string {
|
||||
return i.config.Id
|
||||
}
|
||||
@@ -57,36 +45,50 @@ func (i *TimeInterval) Type() string {
|
||||
return i.config.Type
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (i *TimeInterval) Start(ctx context.Context) error {
|
||||
i.logger.Debug("running")
|
||||
i.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("time.interval unable to get router from context")
|
||||
}
|
||||
i.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
i.ctx = moduleContext
|
||||
i.cancel = cancel
|
||||
|
||||
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
||||
i.ticker = ticker
|
||||
defer ticker.Stop()
|
||||
|
||||
for i.ctx.Err() == nil {
|
||||
for {
|
||||
select {
|
||||
case <-i.ctx.Done():
|
||||
i.logger.Debug("done")
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if i.inputHandler != nil {
|
||||
i.inputHandler(i.ctx, i.Id(), time.Now())
|
||||
if i.router != nil {
|
||||
i.router.HandleInput(i.ctx, i.Id(), time.Now())
|
||||
}
|
||||
default:
|
||||
continue
|
||||
}
|
||||
}
|
||||
<-i.ctx.Done()
|
||||
i.logger.Debug("done")
|
||||
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Output(ctx context.Context, payload any) error {
|
||||
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Stop() {
|
||||
if i.cancel != nil {
|
||||
defer i.cancel()
|
||||
}
|
||||
if i.ticker != nil {
|
||||
i.ticker.Stop()
|
||||
i.cancel()
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return i.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.interval key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,32 +2,30 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type TimeTimer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
timer *time.Timer
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "time.timer",
|
||||
Title: "Timer",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"duration": {
|
||||
Title: "Duration",
|
||||
Description: "time in milliseconds before the timer fires",
|
||||
Type: "integer",
|
||||
},
|
||||
},
|
||||
Required: []string{"duration"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "time.timer",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationNum, err := params.GetInt("duration")
|
||||
@@ -40,16 +38,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type TimeTimer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
timer *time.Timer
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Id() string {
|
||||
return t.config.Id
|
||||
}
|
||||
@@ -58,34 +46,48 @@ func (t *TimeTimer) Type() string {
|
||||
return t.config.Type
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (t *TimeTimer) Start(ctx context.Context) error {
|
||||
t.logger.Debug("running")
|
||||
t.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client unable to get router from context")
|
||||
}
|
||||
t.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
t.ctx = moduleContext
|
||||
t.cancel = cancel
|
||||
|
||||
t.timer = time.NewTimer(time.Millisecond * time.Duration(t.Duration))
|
||||
for t.ctx.Err() == nil {
|
||||
defer t.timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
t.timer.Stop()
|
||||
t.logger.Debug("done")
|
||||
return nil
|
||||
case time := <-t.timer.C:
|
||||
if t.inputHandler != nil {
|
||||
t.inputHandler(t.ctx, t.Id(), time)
|
||||
if t.router != nil {
|
||||
t.router.HandleInput(t.ctx, t.Id(), time)
|
||||
}
|
||||
}
|
||||
}
|
||||
<-t.ctx.Done()
|
||||
t.logger.Debug("done")
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Output(ctx context.Context, payload any) error {
|
||||
t.timer.Reset(time.Millisecond * time.Duration(t.Duration))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Stop() {
|
||||
if t.cancel != nil {
|
||||
defer t.cancel()
|
||||
}
|
||||
if t.timer != nil {
|
||||
t.timer.Stop()
|
||||
t.cancel()
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "duration":
|
||||
return t.Duration, nil
|
||||
default:
|
||||
return nil, errors.New("time.timer key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,37 +6,28 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
type UDPClient struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.UDPAddr
|
||||
Port uint16
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.client",
|
||||
Title: "UDP Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Title: "Host",
|
||||
Description: "the hostname or IP address of the UDP server to connect to",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port of the UDP server to connect to",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
Type: "net.udp.client",
|
||||
New: func(config config.ModuleConfig) (Module, error) {
|
||||
params := config.Params
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
@@ -57,18 +48,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type UDPClient struct {
|
||||
config config.ModuleConfig
|
||||
Addr *net.UDPAddr
|
||||
Port uint16
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
connMu sync.Mutex
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Id() string {
|
||||
return uc.config.Id
|
||||
}
|
||||
@@ -78,16 +57,19 @@ func (uc *UDPClient) Type() string {
|
||||
}
|
||||
|
||||
func (uc *UDPClient) SetupConn() error {
|
||||
uc.connMu.Lock()
|
||||
defer uc.connMu.Unlock()
|
||||
client, err := net.DialUDP("udp", nil, uc.Addr)
|
||||
uc.conn = client
|
||||
return err
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
uc.logger.Debug("running")
|
||||
uc.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.client unable to get router from context")
|
||||
}
|
||||
uc.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
uc.ctx = moduleContext
|
||||
uc.cancel = cancel
|
||||
@@ -99,13 +81,15 @@ func (uc *UDPClient) Start(ctx context.Context, inputHandler common.InputHandler
|
||||
|
||||
<-uc.ctx.Done()
|
||||
uc.logger.Debug("done")
|
||||
if uc.conn != nil {
|
||||
uc.conn.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
uc.connMu.Lock()
|
||||
defer uc.connMu.Unlock()
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.client is only able to output bytes")
|
||||
}
|
||||
@@ -122,12 +106,22 @@ func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Stop() {
|
||||
if uc.cancel != nil {
|
||||
defer uc.cancel()
|
||||
}
|
||||
uc.connMu.Lock()
|
||||
defer uc.connMu.Unlock()
|
||||
if uc.conn != nil {
|
||||
uc.conn.Close()
|
||||
uc.cancel()
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "host":
|
||||
host, err := uc.config.Params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client host error: %w", err)
|
||||
}
|
||||
return host, nil
|
||||
case "ip":
|
||||
return uc.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return uc.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.client key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,38 +6,28 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"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"
|
||||
)
|
||||
|
||||
type UDPMulticast struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Addr *net.UDPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.multicast",
|
||||
Title: "UDP Multicast",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the multicast address to listen on",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"ip", "port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "net.udp.multicast",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
@@ -58,17 +48,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type UDPMulticast struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
Addr *net.UDPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
connMu sync.Mutex
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Id() string {
|
||||
return um.config.Id
|
||||
}
|
||||
@@ -77,9 +56,14 @@ func (um *UDPMulticast) Type() string {
|
||||
return um.config.Type
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
um.logger.Debug("running")
|
||||
um.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast unable to get router from context")
|
||||
}
|
||||
um.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
um.ctx = moduleContext
|
||||
um.cancel = cancel
|
||||
@@ -90,45 +74,43 @@ func (um *UDPMulticast) Start(ctx context.Context, inputHandler common.InputHand
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
um.connMu.Lock()
|
||||
um.conn = client
|
||||
um.connMu.Unlock()
|
||||
|
||||
buffer := make([]byte, 2048)
|
||||
for um.ctx.Err() == nil {
|
||||
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
for {
|
||||
select {
|
||||
case <-um.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
um.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := um.conn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
if errors.Is(err, net.ErrClosed) {
|
||||
break
|
||||
numBytes, _, err := um.conn.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if numBytes > 0 {
|
||||
message := buffer[:numBytes]
|
||||
if numBytes > 0 {
|
||||
message := buffer[:numBytes]
|
||||
|
||||
if um.inputHandler != nil {
|
||||
um.inputHandler(um.ctx, um.Id(), message)
|
||||
} else {
|
||||
um.logger.Error("input received but no input handler is configured")
|
||||
if um.router != nil {
|
||||
um.router.HandleInput(um.ctx, um.Id(), message)
|
||||
} else {
|
||||
um.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
<-um.ctx.Done()
|
||||
um.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
payloadBytes, ok := processor.GetAnyAs[[]byte](payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast can only output bytes")
|
||||
}
|
||||
@@ -142,12 +124,16 @@ func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Stop() {
|
||||
if um.cancel != nil {
|
||||
defer um.cancel()
|
||||
}
|
||||
um.connMu.Lock()
|
||||
defer um.connMu.Unlock()
|
||||
if um.conn != nil {
|
||||
um.conn.Close()
|
||||
um.cancel()
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return um.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return um.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.multicast key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,52 +2,31 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type UDPServer struct {
|
||||
Addr *net.UDPAddr
|
||||
BufferSize int
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.server",
|
||||
Title: "UDP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Description: "the IP address to bind the UDP server to",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Description: "the port for the UDP server to listen on",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"bufferSize": {
|
||||
Title: "Buffer Size",
|
||||
Description: "the size of the buffer for incoming UDP messages",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage("2048"),
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
Type: "net.udp.server",
|
||||
New: func(moduleConfig config.ModuleConfig) (Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
@@ -81,18 +60,6 @@ func init() {
|
||||
})
|
||||
}
|
||||
|
||||
type UDPServer struct {
|
||||
Addr *net.UDPAddr
|
||||
BufferSize int
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
inputHandler common.InputHandler
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
listener *net.UDPConn
|
||||
listenerMu sync.Mutex
|
||||
}
|
||||
|
||||
func (us *UDPServer) Id() string {
|
||||
return us.config.Id
|
||||
}
|
||||
@@ -101,9 +68,14 @@ func (us *UDPServer) Type() string {
|
||||
return us.config.Type
|
||||
}
|
||||
|
||||
func (us *UDPServer) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
func (us *UDPServer) Start(ctx context.Context) error {
|
||||
us.logger.Debug("running")
|
||||
us.inputHandler = inputHandler
|
||||
router, ok := ctx.Value(common.RouterContextKey).(route.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.udp.server unable to get router from context")
|
||||
}
|
||||
us.router = router
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
us.ctx = moduleContext
|
||||
us.cancel = cancel
|
||||
@@ -112,33 +84,36 @@ func (us *UDPServer) Start(ctx context.Context, inputHandler common.InputHandler
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
us.listenerMu.Lock()
|
||||
us.listener = listener
|
||||
us.listenerMu.Unlock()
|
||||
|
||||
defer listener.Close()
|
||||
|
||||
buffer := make([]byte, us.BufferSize)
|
||||
for us.ctx.Err() == nil {
|
||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
for {
|
||||
select {
|
||||
case <-us.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
us.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := listener.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
opErr, ok := err.(*net.OpError)
|
||||
if ok && opErr.Timeout() {
|
||||
continue
|
||||
numBytes, _, err := listener.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
continue
|
||||
}
|
||||
return err
|
||||
}
|
||||
message := buffer[:numBytes]
|
||||
if us.router != nil {
|
||||
us.router.HandleInput(us.ctx, us.Id(), message)
|
||||
} else {
|
||||
us.logger.Error("input received but no router is configured")
|
||||
}
|
||||
break
|
||||
}
|
||||
message := buffer[:numBytes]
|
||||
if us.inputHandler != nil {
|
||||
us.inputHandler(us.ctx, us.Id(), message)
|
||||
} else {
|
||||
us.logger.Error("input received but no input handler is configured")
|
||||
}
|
||||
}
|
||||
<-us.ctx.Done()
|
||||
us.logger.Debug("done")
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||
@@ -146,12 +121,16 @@ func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||
}
|
||||
|
||||
func (us *UDPServer) Stop() {
|
||||
if us.cancel != nil {
|
||||
defer us.cancel()
|
||||
}
|
||||
us.listenerMu.Lock()
|
||||
defer us.listenerMu.Unlock()
|
||||
if us.listener != nil {
|
||||
us.listener.Close()
|
||||
us.cancel()
|
||||
}
|
||||
|
||||
func (us *UDPServer) Get(key string) (any, error) {
|
||||
switch key {
|
||||
case "ip":
|
||||
return us.Addr.IP.String(), nil
|
||||
case "port":
|
||||
return us.Addr.Port, nil
|
||||
default:
|
||||
return nil, errors.New("net.udp.server key not found")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,217 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "websocket.client",
|
||||
Title: "WebSocket Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"url": {
|
||||
Title: "URL",
|
||||
Description: "the URL of the WebSocket server to connect",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"url"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("websocket.client url error: %w", err)
|
||||
}
|
||||
|
||||
parsedURL, err := url.Parse(urlString)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("websocket.client url error: %w", err)
|
||||
}
|
||||
|
||||
if parsedURL.Scheme != "ws" && parsedURL.Scheme != "wss" {
|
||||
return nil, fmt.Errorf("websocket.client url error: scheme must be ws or wss")
|
||||
}
|
||||
|
||||
return &WebSocketClient{URL: *parsedURL, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type WebSocketClient struct {
|
||||
config config.ModuleConfig
|
||||
URL url.URL
|
||||
ctx context.Context
|
||||
conn *websocket.Conn
|
||||
inputHandler common.InputHandler
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
connMu sync.Mutex
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) Id() string {
|
||||
return wc.config.Id
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) Type() string {
|
||||
return wc.config.Type
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) SetupConn() error {
|
||||
wc.connMu.Lock()
|
||||
defer wc.connMu.Unlock()
|
||||
if wc.conn != nil {
|
||||
wc.conn.Close()
|
||||
}
|
||||
conn, _, err := websocket.DefaultDialer.Dial(wc.URL.String(), nil)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("websocket.client dial error: %w", err)
|
||||
}
|
||||
|
||||
conn.SetCloseHandler(func(code int, text string) error {
|
||||
// NOTE(jwetzell): attempt to send close message back to server before closing connection
|
||||
err := wc.conn.WriteControl(
|
||||
websocket.CloseMessage,
|
||||
websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""),
|
||||
time.Now().Add(time.Minute),
|
||||
)
|
||||
wc.connMu.Lock()
|
||||
defer wc.connMu.Unlock()
|
||||
if wc.conn != nil {
|
||||
wc.conn.Close()
|
||||
}
|
||||
return err
|
||||
})
|
||||
|
||||
wc.conn = conn
|
||||
return err
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) Start(ctx context.Context, inputHandler common.InputHandler) error {
|
||||
wc.logger.Debug("running")
|
||||
wc.inputHandler = inputHandler
|
||||
moduleContext, cancel := context.WithCancel(ctx)
|
||||
wc.ctx = moduleContext
|
||||
wc.cancel = cancel
|
||||
|
||||
for wc.ctx.Err() == nil {
|
||||
err := wc.SetupConn()
|
||||
if err != nil {
|
||||
wc.logger.Error("connection error", "error", err)
|
||||
} else {
|
||||
// NOTE(jwetzell): enter read loop until an error occurs
|
||||
wc.readLoop()
|
||||
}
|
||||
// NOTE(jwetzell): if connection is lost or read error wait before trying again
|
||||
time.Sleep(2 * time.Second)
|
||||
}
|
||||
<-wc.ctx.Done()
|
||||
wc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) readLoop() {
|
||||
for wc.ctx.Err() == nil {
|
||||
if wc.conn == nil {
|
||||
wc.logger.Error("websocket connection is not established")
|
||||
return
|
||||
}
|
||||
// TODO(jwetzell): other ways to timeout?
|
||||
wc.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
|
||||
messageType, message, err := wc.conn.ReadMessage()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if wc.inputHandler != nil {
|
||||
switch messageType {
|
||||
case websocket.CloseMessage:
|
||||
return
|
||||
case websocket.PingMessage:
|
||||
err := wc.conn.WriteMessage(websocket.PongMessage, nil)
|
||||
if err != nil {
|
||||
wc.logger.Error("websocket pong error", "error", err)
|
||||
return
|
||||
}
|
||||
case websocket.TextMessage:
|
||||
wc.inputHandler(wc.ctx, wc.Id(), string(message))
|
||||
case websocket.BinaryMessage:
|
||||
wc.inputHandler(wc.ctx, wc.Id(), message)
|
||||
default:
|
||||
wc.logger.Warn("unsupported message type received", "messageType", messageType)
|
||||
}
|
||||
} else {
|
||||
wc.logger.Error("input received but no input handler is configured")
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) outputBytes(ctx context.Context, payload []byte) error {
|
||||
if wc.conn == nil {
|
||||
return errors.New("websocket.client client is not setup")
|
||||
}
|
||||
err := wc.conn.WriteMessage(websocket.BinaryMessage, payload)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) outputString(ctx context.Context, payload string) error {
|
||||
if wc.conn == nil {
|
||||
return errors.New("websocket.client client is not setup")
|
||||
}
|
||||
err := wc.conn.WriteMessage(websocket.TextMessage, []byte(payload))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) Output(ctx context.Context, payload any) error {
|
||||
wc.connMu.Lock()
|
||||
defer wc.connMu.Unlock()
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
if ok {
|
||||
return wc.outputBytes(ctx, payloadBytes)
|
||||
} else {
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
if ok {
|
||||
return wc.outputString(ctx, payloadString)
|
||||
} else {
|
||||
return errors.New("websocket.client payload must be string or []byte")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (wc *WebSocketClient) Stop() {
|
||||
if wc.cancel != nil {
|
||||
defer wc.cancel()
|
||||
}
|
||||
wc.connMu.Lock()
|
||||
defer wc.connMu.Unlock()
|
||||
if wc.conn != nil {
|
||||
err := wc.conn.WriteControl(websocket.CloseMessage, nil, time.Now().Add(time.Minute))
|
||||
if err != nil {
|
||||
wc.logger.Error("websocket close error", "error", err)
|
||||
}
|
||||
wc.conn.Close()
|
||||
}
|
||||
}
|
||||
@@ -5,45 +5,38 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.decode",
|
||||
Title: "Decode ArtNet Packet",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type ArtNetPacketDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (apd *ArtNetPacketDecode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
func (apd *ArtNetPacketDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||
return nil, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := artnet.Decode(payloadBytes)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
|
||||
return wrappedPayload, nil
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (apd *ArtNetPacketDecode) Type() string {
|
||||
return apd.config.Type
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.decode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,44 +5,37 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.encode",
|
||||
Title: "Encode ArtNet Packet",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type ArtNetPacketEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (ape *ArtNetPacketEncode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadPacket, ok := common.GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
func (ape *ArtNetPacketEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPacket, ok := GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||
return nil, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||
}
|
||||
|
||||
payloadBytes, err := payloadPacket.MarshalBinary()
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadBytes
|
||||
|
||||
return wrappedPayload, nil
|
||||
return payloadBytes, nil
|
||||
}
|
||||
|
||||
func (ape *ArtNetPacketEncode) Type() string {
|
||||
return ape.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type ArtNetPacketFilter struct {
|
||||
config config.ProcessorConfig
|
||||
OpCode uint16
|
||||
}
|
||||
|
||||
func (apf *ArtNetPacketFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPacket, ok := GetAnyAs[artnet.ArtNetPacket](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("artnet.packet.filter processor only accepts an ArtNetPacket")
|
||||
}
|
||||
|
||||
if payloadPacket.GetOpCode() != apf.OpCode {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadPacket, nil
|
||||
}
|
||||
|
||||
func (apf *ArtNetPacketFilter) Type() string {
|
||||
return apf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.filter",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
opCodeNum, err := params.GetInt("opCode")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("artnet.packet.filter opCode error: %w", err)
|
||||
}
|
||||
|
||||
return &ArtNetPacketFilter{config: config, OpCode: uint16(opCodeNum)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"text/template"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "db.query",
|
||||
Title: "Query Database",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"module": {
|
||||
Title: "Module ID",
|
||||
Description: "ID of the database module to query",
|
||||
Type: "string",
|
||||
},
|
||||
"query": {
|
||||
Title: "Query",
|
||||
Description: "SQL query to execute",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"module", "query"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
params := config.Params
|
||||
|
||||
moduleIdString, err := params.GetString("module")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db.query module error: %w", err)
|
||||
}
|
||||
|
||||
queryString, err := params.GetString("query")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("db.query query error: %w", err)
|
||||
}
|
||||
|
||||
queryTemplate, err := template.New("query").Parse(queryString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &DbQuery{config: config, ModuleId: moduleIdString, Query: queryTemplate, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type DbQuery struct {
|
||||
config config.ProcessorConfig
|
||||
ModuleId string
|
||||
Query *template.Template
|
||||
logger *slog.Logger
|
||||
module common.DatabaseModule
|
||||
}
|
||||
|
||||
func (dq *DbQuery) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
if dq.module == nil {
|
||||
if wrappedPayload.Modules == nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("db.query wrapped payload has no modules")
|
||||
}
|
||||
|
||||
module, ok := wrappedPayload.Modules[dq.ModuleId]
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query unable to find module with id: %s", dq.ModuleId)
|
||||
}
|
||||
|
||||
dbModule, ok := module.(common.DatabaseModule)
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query module with id %s is not a DatabaseModule", dq.ModuleId)
|
||||
}
|
||||
dq.module = dbModule
|
||||
}
|
||||
|
||||
var queryBuffer bytes.Buffer
|
||||
err := dq.Query.Execute(&queryBuffer, wrappedPayload)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
// support proper parameterized queries
|
||||
rows, err := dq.module.QueryContext(ctx, queryBuffer.String())
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query error executing query: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query error getting columns: %w", err)
|
||||
}
|
||||
|
||||
// TODO(jwetzell): optimize this
|
||||
results := make([]map[string]any, 0)
|
||||
|
||||
for rows.Next() {
|
||||
columnValues := make([]any, len(columns))
|
||||
|
||||
for i := range columnValues {
|
||||
columnValues[i] = new(any)
|
||||
}
|
||||
|
||||
if err := rows.Scan(columnValues...); err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query error scanning row: %w", err)
|
||||
}
|
||||
|
||||
rowMap := make(map[string]any)
|
||||
for i, colName := range columns {
|
||||
value := *columnValues[i].(*any)
|
||||
rowMap[colName] = value
|
||||
}
|
||||
results = append(results, rowMap)
|
||||
}
|
||||
|
||||
if len(results) == 0 {
|
||||
wrappedPayload.Payload = nil
|
||||
return wrappedPayload, nil
|
||||
} else if len(results) == 1 {
|
||||
wrappedPayload.Payload = results[0]
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
wrappedPayload.Payload = results
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (dq *DbQuery) Type() string {
|
||||
return dq.config.Type
|
||||
}
|
||||
@@ -5,35 +5,30 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "debug.log",
|
||||
Title: "Debug Log",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &DebugLog{config: config, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type DebugLog struct {
|
||||
config config.ProcessorConfig
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// TODO(jwetzell): maybe make a more useful logging processor
|
||||
func (dl *DebugLog) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString := fmt.Sprintf("%+v", payload)
|
||||
payloadType := fmt.Sprintf("%T", payload)
|
||||
dl.logger.Debug("", "payload", payloadString, "payloadType", payloadType)
|
||||
return wrappedPayload, nil
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Type() string {
|
||||
return dl.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "debug.log",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &DebugLog{config: config, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.change",
|
||||
Title: "Filter On Change",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FilterChange{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FilterChange struct {
|
||||
config config.ProcessorConfig
|
||||
previous any
|
||||
}
|
||||
|
||||
func (fc *FilterChange) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
|
||||
if reflect.DeepEqual(payload, fc.previous) {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
fc.previous = payload
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fc *FilterChange) Type() string {
|
||||
return fc.config.Type
|
||||
}
|
||||
@@ -6,27 +6,54 @@ import (
|
||||
|
||||
"github.com/expr-lang/expr"
|
||||
"github.com/expr-lang/expr/vm"
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
// NOTE(jwetzell): see language definition https://expr-lang.org/docs/language-definition
|
||||
type FilterExpr struct {
|
||||
config config.ProcessorConfig
|
||||
Program *vm.Program
|
||||
}
|
||||
|
||||
func SafeExprEnv(payload any) any {
|
||||
exprEnv := ExprEnv{
|
||||
Payload: payload,
|
||||
}
|
||||
|
||||
return exprEnv
|
||||
}
|
||||
|
||||
type ExprEnv struct {
|
||||
Payload any
|
||||
}
|
||||
|
||||
func (se *FilterExpr) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
exprEnv := SafeExprEnv(payload)
|
||||
|
||||
output, err := expr.Run(se.Program, exprEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
outputBool, ok := output.(bool)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("filter.expr expression did not return a boolean")
|
||||
}
|
||||
if !outputBool {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (se *FilterExpr) Type() string {
|
||||
return se.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.expr",
|
||||
Title: "Filter by Expr expression",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"expression": {
|
||||
Title: "Expression",
|
||||
Description: "Expr expression to evaluate, must return a boolean",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"expression"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
Type: "filter.expr",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
@@ -44,38 +71,3 @@ func init() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// NOTE(jwetzell): see language definition https://expr-lang.org/docs/language-definition
|
||||
type FilterExpr struct {
|
||||
config config.ProcessorConfig
|
||||
Program *vm.Program
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
|
||||
exprEnv := wrappedPayload
|
||||
|
||||
output, err := expr.Run(fe.Program, exprEnv)
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
outputBool, ok := output.(bool)
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("filter.expr expression did not return a boolean")
|
||||
}
|
||||
if !outputBool {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = exprEnv.Payload
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fe *FilterExpr) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"golang.org/x/time/rate"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.rate",
|
||||
Title: "Filter by Rate",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"rate": {
|
||||
Title: "Rate",
|
||||
Description: "number of events to allow per second",
|
||||
Type: "integer",
|
||||
},
|
||||
},
|
||||
Required: []string{"rate"},
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
rateInt, err := params.GetInt("rate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("filter.rate rate error: %w", err)
|
||||
}
|
||||
|
||||
limiter := rate.NewLimiter(rate.Limit(rateInt), rateInt*2)
|
||||
|
||||
return &FilterRate{config: config, limiter: limiter}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FilterRate struct {
|
||||
config config.ProcessorConfig
|
||||
limiter *rate.Limiter
|
||||
}
|
||||
|
||||
func (fc *FilterRate) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
err := fc.limiter.Wait(ctx)
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fc *FilterRate) Type() string {
|
||||
return fc.config.Type
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.regex",
|
||||
Title: "Filter by Regex",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"pattern": {
|
||||
Title: "Pattern",
|
||||
Description: "regex pattern to match against",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"pattern"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
patternString, err := params.GetString("pattern")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("filter.regex pattern error: %w", err)
|
||||
}
|
||||
|
||||
patternRegexp, err := regexp.Compile(patternString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FilterRegex{config: config, Pattern: patternRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FilterRegex struct {
|
||||
config config.ProcessorConfig
|
||||
Pattern *regexp.Regexp
|
||||
}
|
||||
|
||||
func (fr *FilterRegex) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("filter.regex processor only accepts a string")
|
||||
}
|
||||
|
||||
if !fr.Pattern.MatchString(payloadString) {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadString
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fr *FilterRegex) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
@@ -2,33 +2,39 @@ package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FloatParse struct {
|
||||
BitSize int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse processor only accepts a string")
|
||||
}
|
||||
|
||||
payloadFloat, err := strconv.ParseFloat(payloadString, fp.BitSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payloadFloat, nil
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Type() string {
|
||||
return fp.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.parse",
|
||||
Title: "Parse Float",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"bitSize": {
|
||||
Title: "Bit Size",
|
||||
Description: "bit size of the resulting float",
|
||||
Type: "integer",
|
||||
Enum: []any{32, 64},
|
||||
Default: json.RawMessage("64"),
|
||||
},
|
||||
},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
Type: "float.parse",
|
||||
New: func(moduleConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
@@ -44,30 +50,3 @@ func init() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FloatParse struct {
|
||||
BitSize int
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("float.parse processor only accepts a string")
|
||||
}
|
||||
|
||||
payloadFloat, err := strconv.ParseFloat(payloadString, fp.BitSize)
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
wrappedPayload.Payload = payloadFloat
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Type() string {
|
||||
return fp.config.Type
|
||||
}
|
||||
|
||||
@@ -2,44 +2,39 @@ package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FloatRandom struct {
|
||||
BitSize int
|
||||
Min float64
|
||||
Max float64
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Process(ctx context.Context, payload any) (any, error) {
|
||||
if fr.BitSize == 32 {
|
||||
payloadFloat := rand.Float32()*(float32(fr.Max)-float32(fr.Min)) + float32(fr.Min)
|
||||
return payloadFloat, nil
|
||||
}
|
||||
if fr.BitSize == 64 {
|
||||
payloadFloat := rand.Float64()*(fr.Max-fr.Min) + fr.Min
|
||||
return payloadFloat, nil
|
||||
}
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.random",
|
||||
Title: "Random Float",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"bitSize": {
|
||||
Title: "Bit Size",
|
||||
Description: "bit size of the resulting float",
|
||||
Type: "integer",
|
||||
Enum: []any{32, 64},
|
||||
Default: json.RawMessage("32"),
|
||||
},
|
||||
"min": {
|
||||
Title: "Minimum",
|
||||
Description: "inclusive minimum value of the random float",
|
||||
Type: "number",
|
||||
},
|
||||
"max": {
|
||||
Title: "Maximum",
|
||||
Description: "exclusive maximum value of the random float",
|
||||
Type: "number",
|
||||
},
|
||||
},
|
||||
Required: []string{"min", "max"},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
Type: "float.random",
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
|
||||
@@ -74,29 +69,3 @@ func init() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FloatRandom struct {
|
||||
BitSize int
|
||||
Min float64
|
||||
Max float64
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
if fr.BitSize == 32 {
|
||||
payloadFloat := rand.Float32()*(float32(fr.Max)-float32(fr.Min)) + float32(fr.Min)
|
||||
wrappedPayload.Payload = payloadFloat
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
if fr.BitSize == 64 {
|
||||
payloadFloat := rand.Float64()*(fr.Max-fr.Min) + fr.Min
|
||||
wrappedPayload.Payload = payloadFloat
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
func (fr *FloatRandom) Type() string {
|
||||
return fr.config.Type
|
||||
}
|
||||
|
||||
+172
-272
@@ -7,78 +7,184 @@ import (
|
||||
"strconv"
|
||||
"text/template"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FreeDCreate struct {
|
||||
config config.ProcessorConfig
|
||||
Id *template.Template
|
||||
Pan *template.Template
|
||||
Tilt *template.Template
|
||||
Roll *template.Template
|
||||
PosX *template.Template
|
||||
PosY *template.Template
|
||||
PosZ *template.Template
|
||||
Zoom *template.Template
|
||||
Focus *template.Template
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
templateData := GetTemplateData(ctx, payload)
|
||||
|
||||
var idBuffer bytes.Buffer
|
||||
err := fc.Id.Execute(&idBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
idString := idBuffer.String()
|
||||
|
||||
idNum, err := strconv.ParseUint(idString, 10, 8)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var panBuffer bytes.Buffer
|
||||
err = fc.Pan.Execute(&panBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
panString := panBuffer.String()
|
||||
|
||||
panNum, err := strconv.ParseFloat(panString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var tiltBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&tiltBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tiltString := tiltBuffer.String()
|
||||
|
||||
tiltNum, err := strconv.ParseFloat(tiltString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var rollBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&rollBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rollString := rollBuffer.String()
|
||||
|
||||
rollNum, err := strconv.ParseFloat(rollString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var posXBuffer bytes.Buffer
|
||||
err = fc.PosX.Execute(&posXBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posXString := posXBuffer.String()
|
||||
|
||||
posXNum, err := strconv.ParseFloat(posXString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var posYBuffer bytes.Buffer
|
||||
err = fc.PosY.Execute(&posYBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posYString := posYBuffer.String()
|
||||
|
||||
posYNum, err := strconv.ParseFloat(posYString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var posZBuffer bytes.Buffer
|
||||
err = fc.PosZ.Execute(&posZBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posZString := posZBuffer.String()
|
||||
|
||||
posZNum, err := strconv.ParseFloat(posZString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var zoomBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&zoomBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
zoomString := zoomBuffer.String()
|
||||
|
||||
zoomNum, err := strconv.ParseInt(zoomString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var focusBuffer bytes.Buffer
|
||||
err = fc.Focus.Execute(&focusBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
focusString := focusBuffer.String()
|
||||
|
||||
focusNum, err := strconv.ParseInt(focusString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
payloadMessage := freeD.FreeDPosition{
|
||||
ID: uint8(idNum),
|
||||
Pan: float32(panNum),
|
||||
Tilt: float32(tiltNum),
|
||||
Roll: float32(rollNum),
|
||||
PosX: float32(posXNum),
|
||||
PosY: float32(posYNum),
|
||||
PosZ: float32(posZNum),
|
||||
Zoom: int32(zoomNum),
|
||||
Focus: int32(focusNum),
|
||||
}
|
||||
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Type() string {
|
||||
return fc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.create",
|
||||
Title: "Create FreeD",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"id": {
|
||||
Title: "Camera ID",
|
||||
Description: "ID of the camera this FreeD position corresponds to",
|
||||
Type: "string",
|
||||
},
|
||||
"pan": {
|
||||
Title: "Pan",
|
||||
Description: "pan angle of the camera",
|
||||
Type: "string",
|
||||
},
|
||||
"tilt": {
|
||||
Title: "Tilt",
|
||||
Description: "tilt angle of the camera",
|
||||
Type: "string",
|
||||
},
|
||||
"roll": {
|
||||
Title: "Roll",
|
||||
Description: "roll angle of the camera",
|
||||
Type: "string",
|
||||
},
|
||||
"posX": {
|
||||
Title: "Position X",
|
||||
Description: "X coordinate of the camera's position",
|
||||
Type: "string",
|
||||
},
|
||||
"posY": {
|
||||
Title: "Position Y",
|
||||
Description: "Y coordinate of the camera's position",
|
||||
Type: "string",
|
||||
},
|
||||
"posZ": {
|
||||
Title: "Position Z",
|
||||
Description: "Z coordinate of the camera's position",
|
||||
Type: "string",
|
||||
},
|
||||
"zoom": {
|
||||
Title: "Zoom",
|
||||
Description: "zoom level of the camera",
|
||||
Type: "string",
|
||||
},
|
||||
"focus": {
|
||||
Title: "Focus",
|
||||
Description: "focus level of the camera",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{
|
||||
"id",
|
||||
"pan",
|
||||
"tilt",
|
||||
"roll",
|
||||
"posX",
|
||||
"posY",
|
||||
"posZ",
|
||||
"zoom",
|
||||
"focus",
|
||||
},
|
||||
AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}},
|
||||
},
|
||||
Type: "freed.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
// TODO(jwetzell): make some params optional
|
||||
@@ -101,10 +207,6 @@ func init() {
|
||||
|
||||
panTemplate, err := template.New("pan").Parse(panString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tiltString, err := params.GetString("tilt")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create tilt error: %w", err)
|
||||
@@ -112,10 +214,6 @@ func init() {
|
||||
|
||||
tiltTemplate, err := template.New("tilt").Parse(tiltString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rollString, err := params.GetString("roll")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create roll error: %w", err)
|
||||
@@ -167,19 +265,12 @@ func init() {
|
||||
|
||||
zoomTemplate, err := template.New("zoom").Parse(zoomString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
focusString, err := params.GetString("focus")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create focus error: %w", err)
|
||||
}
|
||||
|
||||
focusTemplate, err := template.New("focus").Parse(focusString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FreeDCreate{
|
||||
config: config,
|
||||
@@ -196,194 +287,3 @@ func init() {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FreeDCreate struct {
|
||||
config config.ProcessorConfig
|
||||
Id *template.Template
|
||||
Pan *template.Template
|
||||
Tilt *template.Template
|
||||
Roll *template.Template
|
||||
PosX *template.Template
|
||||
PosY *template.Template
|
||||
PosZ *template.Template
|
||||
Zoom *template.Template
|
||||
Focus *template.Template
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
|
||||
templateData := wrappedPayload
|
||||
|
||||
var idBuffer bytes.Buffer
|
||||
err := fc.Id.Execute(&idBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
idString := idBuffer.String()
|
||||
|
||||
idNum, err := strconv.ParseUint(idString, 10, 8)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var panBuffer bytes.Buffer
|
||||
err = fc.Pan.Execute(&panBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
panString := panBuffer.String()
|
||||
|
||||
panNum, err := strconv.ParseFloat(panString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var tiltBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&tiltBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
tiltString := tiltBuffer.String()
|
||||
|
||||
tiltNum, err := strconv.ParseFloat(tiltString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var rollBuffer bytes.Buffer
|
||||
err = fc.Roll.Execute(&rollBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
rollString := rollBuffer.String()
|
||||
|
||||
rollNum, err := strconv.ParseFloat(rollString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posXBuffer bytes.Buffer
|
||||
err = fc.PosX.Execute(&posXBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posXString := posXBuffer.String()
|
||||
|
||||
posXNum, err := strconv.ParseFloat(posXString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posYBuffer bytes.Buffer
|
||||
err = fc.PosY.Execute(&posYBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posYString := posYBuffer.String()
|
||||
|
||||
posYNum, err := strconv.ParseFloat(posYString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posZBuffer bytes.Buffer
|
||||
err = fc.PosZ.Execute(&posZBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posZString := posZBuffer.String()
|
||||
|
||||
posZNum, err := strconv.ParseFloat(posZString, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var zoomBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&zoomBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
zoomString := zoomBuffer.String()
|
||||
|
||||
zoomNum, err := strconv.ParseInt(zoomString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var focusBuffer bytes.Buffer
|
||||
err = fc.Focus.Execute(&focusBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
focusString := focusBuffer.String()
|
||||
|
||||
focusNum, err := strconv.ParseInt(focusString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
payloadMessage := freeD.FreeDPosition{
|
||||
ID: uint8(idNum),
|
||||
Pan: float32(panNum),
|
||||
Tilt: float32(tiltNum),
|
||||
Roll: float32(rollNum),
|
||||
PosX: float32(posXNum),
|
||||
PosY: float32(posYNum),
|
||||
PosZ: float32(posZNum),
|
||||
Zoom: int32(zoomNum),
|
||||
Focus: int32(focusNum),
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Type() string {
|
||||
return fc.config.Type
|
||||
}
|
||||
|
||||
@@ -5,50 +5,36 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type FreeDDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := GetAnyAs[[]byte](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := freeD.Decode(payloadBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return payloadMessage, nil
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Type() string {
|
||||
return fdd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.decode",
|
||||
Title: "Decode FreeD",
|
||||
Type: "freed.decode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FreeDDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
type FreeDDecode struct {
|
||||
config config.ProcessorConfig
|
||||
buf [29]byte
|
||||
}
|
||||
|
||||
func (fd *FreeDDecode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("freed.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
if len(payloadBytes) != 29 {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("freeD packet must be exactly 29 bytes")
|
||||
}
|
||||
|
||||
copy(fd.buf[:], payloadBytes)
|
||||
|
||||
payloadMessage, err := freeD.Decode(fd.buf)
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fd *FreeDDecode) Type() string {
|
||||
return fd.config.Type
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user