mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-28 05:45:30 +00:00
Compare commits
436 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
882af2948a | ||
|
|
e2e9fb5eb6 | ||
|
|
411888d8db | ||
|
|
e367d6eb5d | ||
|
|
7659f412fb | ||
|
|
85964f5e25 | ||
|
|
b9e8bb66c6 | ||
|
|
2f9ca82b81 | ||
|
|
25579cb941 | ||
|
|
9134f034c7 | ||
|
|
204ccab683 | ||
|
|
1361e16b28 | ||
|
|
6c9d1b317d | ||
|
|
53e5e7db9e | ||
|
|
13f7b9e927 | ||
|
|
9a50ca8cfe | ||
|
|
256eeac6a8 | ||
|
|
842495f010 | ||
|
|
0922ece656 | ||
|
|
4c7dd1b4d8 | ||
|
|
2fe2250a57 | ||
|
|
c91f14185a | ||
|
|
e32776b02c | ||
|
|
5bb3f08006 | ||
|
|
a0f3ee3b05 | ||
|
|
9843c116b2 | ||
|
|
71b6a6d4a8 | ||
|
|
bb3d939bcd | ||
|
|
97742d7e59 | ||
|
|
9646c3f2d3 | ||
|
|
26dc976565 | ||
|
|
70f64e83c7 | ||
|
|
13e5d4d85a | ||
|
|
bfd0d3a90a | ||
|
|
60e9253b51 | ||
|
|
5f056496ce | ||
|
|
279952f1ea | ||
|
|
94bc22928b | ||
|
|
e5e1ea9f63 | ||
|
|
1cdfe929b4 | ||
|
|
012c416432 | ||
|
|
0763b4d720 | ||
|
|
14f3ae74a7 | ||
|
|
c2b73ac710 | ||
|
|
57262c3377 | ||
|
|
1fb59cc947 | ||
|
|
2fbca6209e | ||
|
|
3fedb7ac92 | ||
|
|
3f4271b5ef | ||
|
|
1e3b2571fb | ||
|
|
4559c6efbd | ||
|
|
7e75fdb758 | ||
|
|
2127c6fd5b | ||
|
|
2a40fa561c | ||
|
|
1467d9de16 | ||
|
|
5fc7b7399f | ||
|
|
3d664fff67 | ||
|
|
9c03ad2c14 | ||
|
|
35262fd505 | ||
|
|
feccab91d5 | ||
|
|
b17e0489a5 | ||
|
|
97c1975c7f | ||
|
|
6336800641 | ||
|
|
d9ac6d1a85 | ||
|
|
be3b9e3d5a | ||
|
|
44cc2e322c | ||
|
|
5f9547fddb | ||
|
|
8d8c5d4073 | ||
|
|
6d382ecd20 | ||
|
|
f0aa5a9eb0 | ||
|
|
e84bd6ead4 | ||
|
|
3d54ac7a0d | ||
|
|
2eae266903 | ||
|
|
c7d407d507 | ||
|
|
2d74e14387 | ||
|
|
e2a0f4ef90 | ||
|
|
54307bc817 | ||
|
|
e95fb44064 | ||
|
|
36c0e9b23e | ||
|
|
b57faaccb9 | ||
|
|
814bb9c1dc | ||
|
|
6fa2c1a746 | ||
|
|
f273aedbc6 | ||
|
|
b6c1c5c600 | ||
|
|
b6ec615e40 | ||
|
|
216775c9c6 | ||
|
|
1bfee2186b | ||
|
|
fa612231fb | ||
|
|
c1161c5aa9 | ||
|
|
b1076ce1e4 | ||
|
|
7f5204aca0 | ||
|
|
f3d87e92f8 | ||
|
|
e50e269697 | ||
|
|
ca6aebadef | ||
|
|
818ddc18f4 | ||
|
|
3e7b245536 | ||
|
|
e996d84234 | ||
|
|
04c8ebbe06 | ||
|
|
0f57e123ce | ||
|
|
82ba1d5d10 | ||
|
|
20c53e4996 | ||
|
|
8132faaba6 | ||
|
|
5a0f21bd64 | ||
|
|
fd0f78733c | ||
|
|
65476d5ecc | ||
|
|
536bc2af4e | ||
|
|
b89d907759 | ||
|
|
a3c48de2ad | ||
|
|
8ca9d9940f | ||
|
|
53d0648774 | ||
|
|
cf2881e5c3 | ||
|
|
f437438dca | ||
|
|
6b3c470534 | ||
|
|
3bdff5309f | ||
|
|
3792d40bb1 | ||
|
|
0cca2e3be9 | ||
|
|
5447781232 | ||
|
|
c760b220c0 | ||
|
|
cb71b5c5b8 | ||
|
|
84fd7c1028 | ||
|
|
7bdf6e01b3 | ||
|
|
1b607f64cd | ||
|
|
28e9141cbc | ||
|
|
3b38110ffb | ||
|
|
25e8563cd1 | ||
|
|
80969ac1ff | ||
|
|
beb3664e3b | ||
|
|
6e53cbe8fd | ||
|
|
4ebaa48f93 | ||
|
|
79d535c283 | ||
|
|
85349f8540 | ||
|
|
e49900a3a7 | ||
|
|
1f706becdc | ||
|
|
13a494239e | ||
|
|
153de944a2 | ||
|
|
42c75074fe | ||
|
|
361b07ec00 | ||
|
|
8c4f0591e1 | ||
|
|
09ddc40f1f | ||
|
|
6382cf6944 | ||
|
|
0732113a02 | ||
|
|
e5db9a48a9 | ||
|
|
9502201261 | ||
|
|
9859aa8fd4 | ||
|
|
b7b05cbb77 | ||
|
|
7b1fe47039 | ||
|
|
0848d8ab6e | ||
|
|
c1bb2ff4cb | ||
|
|
50898b9130 | ||
|
|
05e68e90af | ||
|
|
cd4c3f59f2 | ||
|
|
50399fa811 | ||
|
|
2dd44a11fd | ||
|
|
b7a8b04a72 | ||
|
|
078e6ec68c | ||
|
|
b58187d6a9 | ||
|
|
38b8e44f04 | ||
|
|
dff33f722d | ||
|
|
572a54d3b2 | ||
|
|
6a21cc2639 | ||
|
|
0d4ec24a9b | ||
|
|
10c6e84682 | ||
|
|
7ac0ec7582 | ||
|
|
c25a36f09c | ||
|
|
8d2c022baf | ||
|
|
76318b4e10 | ||
|
|
633eaba0ec | ||
|
|
00b6f3660d | ||
|
|
a275cd2b78 | ||
|
|
5cb2f845a1 | ||
|
|
8f769f0a4a | ||
|
|
fdd4b341cb | ||
|
|
9a9bf10078 | ||
|
|
ea46885f70 | ||
|
|
fa8f0b7cfc | ||
|
|
d316147411 | ||
|
|
30564523d7 | ||
|
|
f7231e54c2 | ||
|
|
14de829e7a | ||
|
|
33a54eb24c | ||
|
|
3c6c50c914 | ||
|
|
da516f5102 | ||
|
|
1f88819428 | ||
|
|
df4f0f745d | ||
|
|
d86bff30cd | ||
|
|
22d8bbf88d | ||
|
|
925873a124 | ||
|
|
08308c1891 | ||
|
|
f68312ee84 | ||
|
|
cd1b5e1437 | ||
|
|
34af7d7aec | ||
|
|
df14024012 | ||
|
|
af39c16f30 | ||
|
|
7d2a3225a7 | ||
|
|
b5ffee022a | ||
|
|
cd264d9ed4 | ||
|
|
9d14e5929f | ||
|
|
8fe1463198 | ||
|
|
28a5d1ea90 | ||
|
|
e9d5931e9d | ||
|
|
d90f103d00 | ||
|
|
05b0de1dfd | ||
|
|
0d8dbab743 | ||
|
|
fb599f1057 | ||
|
|
a2efed0ee2 | ||
|
|
533fe150c8 | ||
|
|
b653179e6d | ||
|
|
695cabf15e | ||
|
|
ccac116f8d | ||
|
|
c298f63ffc | ||
|
|
183182e6cd | ||
|
|
01f172dbee | ||
|
|
20fd4170ed | ||
|
|
bcf9299505 | ||
|
|
4f7820af5e | ||
|
|
87fcc63068 | ||
|
|
1c49776662 | ||
|
|
1a7207ae4c | ||
|
|
f86a34cc92 | ||
|
|
d9d64bd248 | ||
|
|
e828dc1b0b | ||
|
|
cc4d50bc17 | ||
|
|
abd37439c5 | ||
|
|
8c3f93b601 | ||
|
|
2f7f6967e1 | ||
|
|
09b030efa6 | ||
|
|
bb49dba22e | ||
|
|
4ed6866731 | ||
|
|
2d392873ca | ||
|
|
11e25ab8f7 | ||
|
|
87e6b09156 | ||
|
|
8cb2a0e9f0 | ||
|
|
263943f4d6 | ||
|
|
f9865765c6 | ||
|
|
e6aaffbb95 | ||
|
|
90a14b4d1b | ||
|
|
8bdd338a27 | ||
|
|
b20c16be4f | ||
|
|
de060057e6 | ||
|
|
4526e805af | ||
|
|
1d8baa8c17 | ||
|
|
060c12512c | ||
|
|
444093d375 | ||
|
|
a217b729cd | ||
|
|
ad76480008 | ||
|
|
a408e281a3 | ||
|
|
f028634401 | ||
|
|
961316d28b | ||
|
|
e22a941e4a | ||
|
|
b0cffe819d | ||
|
|
0cdd1f6e6a | ||
|
|
a9245ab88c | ||
|
|
d69d3a370d | ||
|
|
019624f152 | ||
|
|
90a3119fb8 | ||
|
|
54c14cbbae | ||
|
|
969ac6e04b | ||
|
|
bfa63499c3 | ||
|
|
6b178d1ae4 | ||
|
|
988437fccf | ||
|
|
dc19d18b81 | ||
|
|
86f1082159 | ||
|
|
a46054c427 | ||
|
|
9dc4706fd8 | ||
|
|
f91cb9dbbf | ||
|
|
10b5cbae6c | ||
|
|
a9f9f1ba2c | ||
|
|
8e27dc81a2 | ||
|
|
42bd5c46b5 | ||
|
|
515a8d14fd | ||
|
|
1f3a2b9076 | ||
|
|
5dc897c4b2 | ||
|
|
7015a9d7a2 | ||
|
|
3c6d98638e | ||
|
|
8ec8ad91a6 | ||
|
|
f919017ca6 | ||
|
|
66f170047a | ||
|
|
7ff20e0136 | ||
|
|
b53494fddc | ||
|
|
3688510ded | ||
|
|
d0bdc44c30 | ||
|
|
1c49548a4c | ||
|
|
4ea6c8f11f | ||
|
|
0ef512eb28 | ||
|
|
ebbce3261c | ||
|
|
79fa925823 | ||
|
|
659c95102b | ||
|
|
e06c4195c7 | ||
|
|
28e3c99ad8 | ||
|
|
7312bfec20 | ||
|
|
4bbf69e644 | ||
|
|
1ba51446ad | ||
|
|
2266d6a9b8 | ||
|
|
f1f340f963 | ||
|
|
4ca989280c | ||
|
|
ef83e84e84 | ||
|
|
b8ad912855 | ||
|
|
f766d0e2a4 | ||
|
|
725e8ad670 | ||
|
|
7fa3b6d33d | ||
|
|
5e957d7d03 | ||
|
|
bd89df3da2 | ||
|
|
914f6aa833 | ||
|
|
2104d9f1a9 | ||
|
|
457ff83c23 | ||
|
|
37c7a23063 | ||
|
|
9ba3a88e8c | ||
|
|
33ecc94097 | ||
|
|
8f5091cf9b | ||
|
|
b095419b6e | ||
|
|
1e872ba0b9 | ||
|
|
b959b88527 | ||
|
|
0dfbf30fa7 | ||
|
|
abff674a75 | ||
|
|
a920f34926 | ||
|
|
4dac1faae0 | ||
|
|
ab5b40ee72 | ||
|
|
5a29139e63 | ||
|
|
1587f84981 | ||
|
|
0cb13a30f9 | ||
|
|
8212d15a70 | ||
|
|
eee356225f | ||
|
|
5cd02f9e3a | ||
|
|
100edab869 | ||
|
|
fd4c2cb59b | ||
|
|
b6ee3c68f1 | ||
|
|
7e0c2b2560 | ||
|
|
c9a3eb80bc | ||
|
|
2a5feec07a | ||
|
|
ced4bc839e | ||
|
|
ce6a9ff4a8 | ||
|
|
bd3b8a19d5 | ||
|
|
cb738a9b8e | ||
|
|
1b59dbc1e5 | ||
|
|
c75a2327d5 | ||
|
|
a17be985e6 | ||
|
|
78737f57af | ||
|
|
720c0cd52a | ||
|
|
3e1d4f07f9 | ||
|
|
452e308f8f | ||
|
|
d16d833520 | ||
|
|
f203b32261 | ||
|
|
361c4f4499 | ||
|
|
a76d12d799 | ||
|
|
7d91e64ec4 | ||
|
|
589c59c693 | ||
|
|
56c67c5445 | ||
|
|
13229215a6 | ||
|
|
909b4d2337 | ||
|
|
3bcb9a6608 | ||
|
|
17dcffc09b | ||
|
|
8318645eef | ||
|
|
0c777a8874 | ||
|
|
a8f9894ff0 | ||
|
|
f0f74f50e5 | ||
|
|
bb3a8b982b | ||
|
|
be9ce5a8aa | ||
|
|
ac2cf078a4 | ||
|
|
0fc264d0e9 | ||
|
|
3c99eef999 | ||
|
|
f7c3a85649 | ||
|
|
76caccd9f8 | ||
|
|
e8c71562a6 | ||
|
|
42551127ba | ||
|
|
a99fef9389 | ||
|
|
e6099b6acd | ||
|
|
b93d754c19 | ||
|
|
710dcf3a02 | ||
|
|
ac83b339a6 | ||
|
|
cb06e2dbb5 | ||
|
|
3ef41d0026 | ||
|
|
8dcb70bfee | ||
|
|
59f00c1a32 | ||
|
|
6e88d259b8 | ||
|
|
bb33974e1c | ||
|
|
bd2a68ff6e | ||
|
|
7e2d76ef3a | ||
|
|
d1cec1e094 | ||
|
|
477d70fad0 | ||
|
|
70f4636522 | ||
|
|
0248ca6973 | ||
|
|
4aa586427b | ||
|
|
6d3cf6692f | ||
|
|
a263b10690 | ||
|
|
3ce2909b0f | ||
|
|
b15e282d59 | ||
|
|
f97f9b9fc9 | ||
|
|
12de947f3d | ||
|
|
7335ba973a | ||
|
|
a994286402 | ||
|
|
b639a5c786 | ||
|
|
d170958d9b | ||
|
|
ed4c14e82b | ||
|
|
fcb1378784 | ||
|
|
97f4cbeace | ||
|
|
8ffc7d02a5 | ||
|
|
3458b52206 | ||
|
|
e12b6e098e | ||
|
|
58cb7766fe | ||
|
|
407f1f3618 | ||
|
|
3c0f555a6f | ||
|
|
6c6e50e0eb | ||
|
|
0ed4d6669f | ||
|
|
cc37559bde | ||
|
|
18b307bca1 | ||
|
|
17106b5096 | ||
|
|
df9ffdda9e | ||
|
|
479cf41ea0 | ||
|
|
af833cb212 | ||
|
|
a6a8e275ee | ||
|
|
6968539c59 | ||
|
|
e96913230b | ||
|
|
f1dff33704 | ||
|
|
ff426994e4 | ||
|
|
a1275b3b69 | ||
|
|
227d042feb | ||
|
|
e53515267e | ||
|
|
502586dec6 | ||
|
|
cad3714664 | ||
|
|
cf6519b594 | ||
|
|
7dcac9470a | ||
|
|
e5268f42f8 | ||
|
|
ccff105e37 | ||
|
|
6611821155 | ||
|
|
7cde1c244a | ||
|
|
70878e6df6 | ||
|
|
bd005da358 | ||
|
|
25f2ec30c2 | ||
|
|
e679bf2b46 | ||
|
|
460d2f051d | ||
|
|
efdcbae5c4 | ||
|
|
076a13f48a | ||
|
|
971eea6e41 | ||
|
|
1172159455 | ||
|
|
ecb415f321 | ||
|
|
b552672011 |
6
.github/dependabot.yml
vendored
6
.github/dependabot.yml
vendored
@@ -1,9 +1,9 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: 'github-actions'
|
||||
directory: '/'
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: 'weekly'
|
||||
interval: "weekly"
|
||||
- package-ecosystem: gomod
|
||||
directory: /
|
||||
schedule:
|
||||
|
||||
23
.github/labeler.yml
vendored
23
.github/labeler.yml
vendored
@@ -1,23 +0,0 @@
|
||||
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/**'
|
||||
|
||||
route:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'internal/route/**'
|
||||
|
||||
cli:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'cmd/showbridge/**'
|
||||
7
.github/release.yml
vendored
7
.github/release.yml
vendored
@@ -17,12 +17,13 @@ changelog:
|
||||
- title: Processor 🏭
|
||||
labels:
|
||||
- processor
|
||||
- title: Route 🛣️
|
||||
- title: Routing 🛣️
|
||||
labels:
|
||||
- router
|
||||
- route
|
||||
- title: CLI ⌨️
|
||||
labels:
|
||||
- cmd
|
||||
- cli
|
||||
- title: Other Changes
|
||||
labels:
|
||||
- '*'
|
||||
- "*"
|
||||
|
||||
18
.github/workflows/label-pr.yaml
vendored
18
.github/workflows/label-pr.yaml
vendored
@@ -1,18 +0,0 @@
|
||||
# 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
|
||||
16
.github/workflows/release-showbridge.yaml
vendored
16
.github/workflows/release-showbridge.yaml
vendored
@@ -19,9 +19,9 @@ jobs:
|
||||
- name: setup go
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: release
|
||||
uses: goreleaser/goreleaser-action@v6
|
||||
uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
workdir: cmd/showbridge
|
||||
distribution: goreleaser
|
||||
@@ -37,26 +37,26 @@ jobs:
|
||||
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@c7c53464625b32c7a7e944ae62b3e17d2b600130 # v3.7.0
|
||||
uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
|
||||
uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@5e57cd118135c172c3672efd75eb46360885c0ef # v3.6.0
|
||||
uses: docker/login-action@b45d80f862d83dbcd57f89517bcf500b2ab88fb2 # v4.0.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Setup Docker metadata
|
||||
id: meta
|
||||
uses: docker/metadata-action@c299e40c65443455700f0fdfc63efafe5b349051 # v5.10.0
|
||||
uses: docker/metadata-action@030e881283bb7a6894de51c315a6bfe6a94e05cf # v6.0.0
|
||||
with:
|
||||
images: |
|
||||
jwetzell/showbridge
|
||||
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
|
||||
uses: docker/build-push-action@d08e5c354a6adb9ed34480a06d141179aa583294 # v7.0.0
|
||||
with:
|
||||
push: true
|
||||
context: ./
|
||||
@@ -65,4 +65,4 @@ jobs:
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
platforms: linux/amd64,linux/arm64,linux/arm/v7
|
||||
platforms: linux/amd64
|
||||
|
||||
30
.github/workflows/test-showbridge.yaml
vendored
30
.github/workflows/test-showbridge.yaml
vendored
@@ -5,19 +5,19 @@ 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: read
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@@ -29,9 +29,21 @@ jobs:
|
||||
- uses: actions/checkout@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version-file: 'go.mod'
|
||||
go-version-file: "go.mod"
|
||||
- name: mod tidy
|
||||
run: go mod tidy
|
||||
|
||||
- name: run tests
|
||||
run: go test ./...
|
||||
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
|
||||
- name: Update coverage report
|
||||
uses: ncruces/go-coverage-report@v0.3.2
|
||||
with:
|
||||
coverage-file: coverage.nocmd.out
|
||||
report: true
|
||||
chart: true
|
||||
amend: true
|
||||
if: github.event_name == 'push'
|
||||
continue-on-error: true
|
||||
|
||||
3
.vscode/launch.json
vendored
3
.vscode/launch.json
vendored
@@ -4,14 +4,13 @@
|
||||
// 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": ["--debug"],
|
||||
"args": ["--log-level", "debug"],
|
||||
"cwd": "./"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
ARG GO_VERSION=1.25.5
|
||||
ARG GO_VERSION=1.26.0
|
||||
FROM golang:${GO_VERSION}-alpine AS build
|
||||
RUN apk --no-cache add ca-certificates tzdata
|
||||
WORKDIR /build
|
||||
|
||||
38
README.md
38
README.md
@@ -2,33 +2,45 @@
|
||||
|
||||
# showbridge (go edition)
|
||||
|
||||
[](https://raw.githack.com/wiki/jwetzell/showbridge-go/coverage.html)
|
||||
Simple protocol router _/s_
|
||||
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/jwetzell/showbridge-go/releases">Releases</a> ·
|
||||
<a href="https://docs.showbridge.io">Documentation</a>
|
||||
</p>
|
||||
|
||||
### Supported Protocols
|
||||
|
||||
- HTTP
|
||||
- client
|
||||
- server
|
||||
- UDP
|
||||
- client
|
||||
- server
|
||||
- TCP
|
||||
- client
|
||||
- server
|
||||
- [MQTT](https://mqtt.org/)
|
||||
- client
|
||||
- [NATS](https://nats.io/)
|
||||
- client
|
||||
- [PosiStageNet](https://posistage.net/)
|
||||
- client
|
||||
- MIDI (not included in pre-built binaries yet)
|
||||
- input
|
||||
- output
|
||||
- Serial (not included in pre-built binaries yet)
|
||||
- [OSC](https://opensoundcontrol.stanford.edu/spec-1_0.html)
|
||||
- [FreeD](https://ptzoptics.com/freed/)
|
||||
- [SIP](https://en.wikipedia.org/wiki/Session_Initiation_Protocol)
|
||||
- call server
|
||||
- [DTMF](https://en.wikipedia.org/wiki/Dual-tone_multi-frequency_signaling) server
|
||||
- [Redis](https://redis.io/)
|
||||
|
||||
### CLI Usage
|
||||
|
||||
```
|
||||
NAME:
|
||||
showbridge - Simple protocol router /s
|
||||
|
||||
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]
|
||||
--trace enable OpenTelemetry tracing [$SHOWBRIDGE_TRACE]
|
||||
--help, -h show help
|
||||
--version, -v print the version
|
||||
```
|
||||
|
||||
255
api.go
Normal file
255
api.go
Normal file
@@ -0,0 +1,255 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/jwetzell/showbridge-go/internal/schema"
|
||||
)
|
||||
|
||||
func (r *Router) startAPIServer(config config.ApiConfig) {
|
||||
if !config.Enabled {
|
||||
r.logger.Warn("API not enabled")
|
||||
return
|
||||
}
|
||||
r.logger.Debug("starting API server", "port", config.Port)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/ws", r.handleWebsocket)
|
||||
mux.HandleFunc("/health", r.handleHealthHTTP)
|
||||
mux.HandleFunc("/api/v1/config", r.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)
|
||||
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
r.apiServer = &http.Server{
|
||||
Addr: fmt.Sprintf(":%d", config.Port),
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
r.apiServer.ListenAndServe()
|
||||
r.apiServerShutdown()
|
||||
}()
|
||||
}
|
||||
|
||||
func (r *Router) stopAPIServer() {
|
||||
if r.apiServer == nil {
|
||||
return
|
||||
}
|
||||
r.logger.Debug("stopping API server")
|
||||
r.apiServerMu.Lock()
|
||||
defer r.apiServerMu.Unlock()
|
||||
if r.apiServer != nil {
|
||||
apiShutdownCtx, apiShutdownCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
r.apiServerShutdown = apiShutdownCancel
|
||||
r.apiServer.Shutdown(apiShutdownCtx)
|
||||
<-apiShutdownCtx.Done()
|
||||
r.apiServer = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleHealthHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) handleConfigHTTP(w http.ResponseWriter, req *http.Request) {
|
||||
|
||||
switch req.Method {
|
||||
case http.MethodGet:
|
||||
configJSON, err := json.Marshal(r.runningConfig)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write(configJSON)
|
||||
case http.MethodPut:
|
||||
if r.updatingConfig {
|
||||
http.Error(w, "Config update in progress.", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
//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 := r.UpdateConfig(newConfig)
|
||||
if len(moduleErrors) > 0 || len(routeErrors) > 0 {
|
||||
errorResponse := struct {
|
||||
ModuleErrors []module.ModuleError `json:"moduleErrors,omitempty"`
|
||||
RouteErrors []route.RouteError `json:"routeErrors,omitempty"`
|
||||
}{
|
||||
ModuleErrors: moduleErrors,
|
||||
RouteErrors: routeErrors,
|
||||
}
|
||||
errorResponseJSON, err := json.Marshal(errorResponse)
|
||||
if err != nil {
|
||||
http.Error(w, "Internal server error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write(errorResponseJSON)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
r.ConfigChange <- newConfig
|
||||
case http.MethodOptions:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
default:
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,7 @@ builds:
|
||||
- "amd64"
|
||||
- "arm64"
|
||||
ldflags:
|
||||
- '-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}'
|
||||
- "-s -w -X main.version={{.RawVersion}}-{{.ShortCommit}}"
|
||||
|
||||
archives:
|
||||
- formats: [tar.gz]
|
||||
|
||||
@@ -2,19 +2,33 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
"slices"
|
||||
"sync"
|
||||
"syscall"
|
||||
|
||||
"github.com/jwetzell/showbridge-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"github.com/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.40.0"
|
||||
"sigs.k8s.io/yaml"
|
||||
)
|
||||
|
||||
var (
|
||||
version = "dev"
|
||||
sigHangup = make(chan os.Signal, 1)
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -27,66 +41,47 @@ func main() {
|
||||
Name: "config",
|
||||
Value: "./config.yaml",
|
||||
Usage: "path to config file",
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_CONFIG"),
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "debug",
|
||||
Value: false,
|
||||
Usage: "set log level to DEBUG",
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "json",
|
||||
Value: false,
|
||||
Usage: "log using JSON",
|
||||
},
|
||||
},
|
||||
Action: func(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
return errors.New("config value cannot be empty")
|
||||
&cli.StringFlag{
|
||||
Name: "log-level",
|
||||
Value: "info",
|
||||
Usage: "set log level",
|
||||
Validator: func(level string) error {
|
||||
levels := []string{"debug", "info", "warn", "error"}
|
||||
if !slices.Contains(levels, level) {
|
||||
return fmt.Errorf("unknown log level: %s", level)
|
||||
}
|
||||
|
||||
config, err := readConfig(configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
logLevel := slog.LevelInfo
|
||||
|
||||
if c.Bool("debug") {
|
||||
logLevel = slog.LevelDebug
|
||||
}
|
||||
|
||||
logHandlerOptions := &slog.HandlerOptions{
|
||||
Level: logLevel,
|
||||
}
|
||||
|
||||
logOutput := os.Stderr
|
||||
|
||||
var logHandler slog.Handler = slog.NewTextHandler(logOutput, logHandlerOptions)
|
||||
|
||||
if c.Bool("json") {
|
||||
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
|
||||
}
|
||||
|
||||
logger := slog.New(logHandler)
|
||||
|
||||
slog.SetDefault(logger)
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(ctx, config)
|
||||
|
||||
for _, moduleError := range moduleErrors {
|
||||
logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
|
||||
for _, routeError := range routeErrors {
|
||||
logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
router.Run()
|
||||
return nil
|
||||
},
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_LOG_LEVEL"),
|
||||
},
|
||||
&cli.StringFlag{
|
||||
Name: "log-format",
|
||||
Value: "text",
|
||||
Usage: "log format to use",
|
||||
Validator: func(format string) error {
|
||||
formats := []string{"text", "json"}
|
||||
if !slices.Contains(formats, format) {
|
||||
return fmt.Errorf("unknown log format: %s", format)
|
||||
}
|
||||
return nil
|
||||
},
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_LOG_FORMAT"),
|
||||
},
|
||||
&cli.BoolFlag{
|
||||
Name: "trace",
|
||||
Value: false,
|
||||
Usage: "enable OpenTelemetry tracing",
|
||||
Sources: cli.EnvVars("SHOWBRIDGE_TRACE"),
|
||||
},
|
||||
},
|
||||
Action: run,
|
||||
}
|
||||
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, os.Interrupt)
|
||||
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
|
||||
signal.Notify(sigHangup, syscall.SIGHUP)
|
||||
defer cancel()
|
||||
err := cmd.Run(ctx, os.Args)
|
||||
|
||||
@@ -96,6 +91,15 @@ func main() {
|
||||
|
||||
}
|
||||
|
||||
type showbridgeApp struct {
|
||||
ctx context.Context
|
||||
configPath string
|
||||
logger *slog.Logger
|
||||
router *showbridge.Router
|
||||
routerRunner *sync.WaitGroup
|
||||
routerMutex sync.Mutex
|
||||
}
|
||||
|
||||
func readConfig(configPath string) (config.Config, error) {
|
||||
cfg := config.Config{}
|
||||
|
||||
@@ -105,10 +109,203 @@ func readConfig(configPath string) (config.Config, error) {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
err = yaml.Unmarshal(configBytes, &cfg)
|
||||
//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{}, err
|
||||
}
|
||||
|
||||
err = schema.ValidateConfig(yamlMap)
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
validatedConfigBytes, err := json.Marshal(yamlMap)
|
||||
|
||||
err = json.Unmarshal(validatedConfigBytes, &cfg)
|
||||
if err != nil {
|
||||
return config.Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func writeConfig(configPath string, newConfig config.Config) error {
|
||||
configBytes, err := yaml.Marshal(newConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = os.WriteFile(configPath, configBytes, 0644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func run(ctx context.Context, c *cli.Command) error {
|
||||
configPath := c.String("config")
|
||||
if configPath == "" {
|
||||
return errors.New("config path cannot be empty")
|
||||
}
|
||||
|
||||
logLevel := slog.LevelInfo
|
||||
|
||||
logLevelFromFlag := c.String("log-level")
|
||||
|
||||
switch logLevelFromFlag {
|
||||
case "debug":
|
||||
logLevel = slog.LevelDebug
|
||||
case "info":
|
||||
logLevel = slog.LevelInfo
|
||||
case "warn":
|
||||
logLevel = slog.LevelWarn
|
||||
case "error":
|
||||
logLevel = slog.LevelError
|
||||
default:
|
||||
logLevel = slog.LevelInfo
|
||||
}
|
||||
|
||||
logHandlerOptions := &slog.HandlerOptions{
|
||||
Level: logLevel,
|
||||
}
|
||||
|
||||
logOutput := os.Stderr
|
||||
|
||||
var logHandler slog.Handler
|
||||
|
||||
logFormat := c.String("log-format")
|
||||
|
||||
switch logFormat {
|
||||
case "json":
|
||||
logHandler = slog.NewJSONHandler(logOutput, logHandlerOptions)
|
||||
case "text":
|
||||
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
|
||||
default:
|
||||
logHandler = slog.NewTextHandler(logOutput, logHandlerOptions)
|
||||
}
|
||||
|
||||
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"),
|
||||
routerRunner: &sync.WaitGroup{},
|
||||
}
|
||||
|
||||
config, err := readConfig(showbridgeApp.configPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
router, moduleErrors, routeErrors := showbridge.NewRouter(config)
|
||||
|
||||
showbridgeApp.logConfigErrors(moduleErrors, routeErrors)
|
||||
|
||||
if moduleErrors != nil || routeErrors != nil {
|
||||
return fmt.Errorf("errors initializing modules or routes")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to initialize router: %w", err)
|
||||
}
|
||||
showbridgeApp.routerMutex.Lock()
|
||||
showbridgeApp.router = router
|
||||
|
||||
showbridgeApp.routerRunner.Go(func() {
|
||||
router.Start(context.Background())
|
||||
})
|
||||
showbridgeApp.routerMutex.Unlock()
|
||||
|
||||
go showbridgeApp.handleChannels()
|
||||
|
||||
<-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() {
|
||||
for {
|
||||
select {
|
||||
case <-sigHangup:
|
||||
app.logger.Info("received SIGHUP, reloading configuration")
|
||||
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 := app.router.UpdateConfig(config)
|
||||
app.logConfigErrors(moduleErrors, routeErrors)
|
||||
app.logger.Info("configuration reloaded successfully")
|
||||
app.routerMutex.Unlock()
|
||||
case config := <-app.router.ConfigChange:
|
||||
app.logger.Info("router config changed updating config file")
|
||||
err := writeConfig(app.configPath, config)
|
||||
if err != nil {
|
||||
app.logger.Error("failed to write config file", "error", err)
|
||||
continue
|
||||
}
|
||||
app.logger.Info("config file updated successfully")
|
||||
case <-app.ctx.Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (app *showbridgeApp) logConfigErrors(moduleErrors []module.ModuleError, routeErrors []route.RouteError) {
|
||||
for _, moduleError := range moduleErrors {
|
||||
app.logger.Error("problem initializing module", "index", moduleError.Index, "error", moduleError.Error)
|
||||
}
|
||||
|
||||
for _, routeError := range routeErrors {
|
||||
app.logger.Error("problem initializing route", "index", routeError.Index, "error", routeError.Error)
|
||||
}
|
||||
}
|
||||
|
||||
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,3 +1,6 @@
|
||||
api:
|
||||
enabled: true
|
||||
port: 8080
|
||||
modules:
|
||||
- id: http
|
||||
type: http.server
|
||||
@@ -13,6 +16,8 @@ routes:
|
||||
processors:
|
||||
- type: osc.message.create
|
||||
params:
|
||||
address: "{{.URL.Path}}"
|
||||
address: "{{.Payload.URL.Path}}"
|
||||
- type: osc.message.encode
|
||||
output: udp
|
||||
- type: router.output
|
||||
params:
|
||||
module: udp
|
||||
|
||||
64
events.go
Normal file
64
events.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package showbridge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
type Event struct {
|
||||
Type string `json:"type"`
|
||||
Data any `json:"data,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (e Event) toJSON() ([]byte, error) {
|
||||
return json.Marshal(e)
|
||||
}
|
||||
|
||||
func (r *Router) handleEvent(event Event, sender *websocket.Conn) {
|
||||
switch event.Type {
|
||||
case "ping":
|
||||
r.unicastEvent(Event{Type: "pong"}, sender)
|
||||
default:
|
||||
r.logger.Warn("unknown event type", "eventType", event.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) unicastEvent(event Event, conn *websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
err = conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Router) broadcastEvent(event Event, excluded ...*websocket.Conn) {
|
||||
eventJSON, err := event.toJSON()
|
||||
if err != nil {
|
||||
r.logger.Error("failed to marshal event to JSON", "error", err)
|
||||
return
|
||||
}
|
||||
r.wsConnsMu.Lock()
|
||||
defer r.wsConnsMu.Unlock()
|
||||
for _, conn := range r.wsConns {
|
||||
exclude := false
|
||||
for _, excludedConn := range excluded {
|
||||
if conn == excludedConn {
|
||||
exclude = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if exclude {
|
||||
continue
|
||||
}
|
||||
err := conn.WriteMessage(websocket.TextMessage, eventJSON)
|
||||
if err != nil {
|
||||
r.logger.Error("failed to write message to websocket connection", "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
77
go.mod
77
go.mod
@@ -1,55 +1,92 @@
|
||||
module github.com/jwetzell/showbridge-go
|
||||
|
||||
go 1.25.3
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/eclipse/paho.mqtt.golang v1.5.1
|
||||
github.com/emiago/diago v0.23.1-0.20251211215055-e1d875617111
|
||||
github.com/emiago/sipgo v1.0.1
|
||||
github.com/expr-lang/expr v1.17.7
|
||||
github.com/emiago/diago v0.28.0
|
||||
github.com/emiago/sipgo v1.2.1
|
||||
github.com/expr-lang/expr v1.17.8
|
||||
github.com/extism/go-sdk v1.7.1
|
||||
github.com/google/jsonschema-go v0.4.2
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jwetzell/artnet-go v0.2.1
|
||||
github.com/jwetzell/free-d-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.1.0
|
||||
github.com/jwetzell/osc-go v0.2.0
|
||||
github.com/jwetzell/psn-go v0.3.0
|
||||
github.com/nats-io/nats.go v1.48.0
|
||||
github.com/urfave/cli/v3 v3.6.1
|
||||
gitlab.com/gomidi/midi/v2 v2.3.18
|
||||
github.com/nats-io/nats-server/v2 v2.12.6
|
||||
github.com/nats-io/nats.go v1.49.0
|
||||
github.com/redis/go-redis/v9 v9.18.0
|
||||
github.com/urfave/cli/v3 v3.7.0
|
||||
gitlab.com/gomidi/midi/v2 v2.3.23
|
||||
go.bug.st/serial v1.6.4
|
||||
modernc.org/quickjs v0.17.0
|
||||
go.opentelemetry.io/otel v1.42.0
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0
|
||||
go.opentelemetry.io/otel/sdk v1.42.0
|
||||
go.opentelemetry.io/otel/trace v1.42.0
|
||||
modernc.org/quickjs v0.17.1
|
||||
modernc.org/sqlite v1.47.0
|
||||
sigs.k8s.io/yaml v1.6.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op // indirect
|
||||
github.com/cenkalti/backoff/v5 v5.0.3 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/creack/goselect v0.1.2 // indirect
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // 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/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20240805132620-81f5be970eca // indirect
|
||||
github.com/icholy/digest v1.1.0 // indirect
|
||||
github.com/klauspost/compress v1.18.0 // indirect
|
||||
github.com/klauspost/compress v1.18.4 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/nats-io/nkeys v0.4.11 // indirect
|
||||
github.com/minio/highwayhash v1.0.4-0.20251030100505-070ab1a87a76 // indirect
|
||||
github.com/nats-io/jwt/v2 v2.8.1 // indirect
|
||||
github.com/nats-io/nkeys v0.4.15 // indirect
|
||||
github.com/nats-io/nuid v1.0.1 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // 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.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/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 // indirect
|
||||
github.com/tetratelabs/wazero v1.9.0 // indirect
|
||||
github.com/zaf/g711 v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.42.0 // indirect
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 // indirect
|
||||
go.uber.org/atomic v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/crypto v0.42.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/net v0.44.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/crypto v0.49.0 // indirect
|
||||
golang.org/x/net v0.51.0 // indirect
|
||||
golang.org/x/sync v0.20.0 // indirect
|
||||
golang.org/x/sys v0.42.0 // indirect
|
||||
golang.org/x/text v0.35.0 // indirect
|
||||
golang.org/x/time v0.15.0 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260209200024-4cfbd4190f57 // indirect
|
||||
google.golang.org/grpc v1.79.2 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/hraban/opus.v2 v2.0.0-20230925203106-0188a62cb302 // indirect
|
||||
modernc.org/libc v1.66.10 // indirect
|
||||
modernc.org/libquickjs v0.12.2 // indirect
|
||||
modernc.org/libc v1.70.0 // indirect
|
||||
modernc.org/libquickjs v0.12.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
|
||||
194
go.sum
194
go.sum
@@ -1,57 +1,104 @@
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op h1:kpBdlEPbRvff0mDD1gk7o9BhI16b9p5yYAXRlidpqJE=
|
||||
github.com/antithesishq/antithesis-sdk-go v0.6.0-default-no-op/go.mod h1:IUpT2DPAKh6i/YhSbt6Gl3v2yvUZjmKncl7U91fup7E=
|
||||
github.com/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/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/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
|
||||
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
|
||||
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-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.23.1-0.20251211215055-e1d875617111 h1:jqhOZbH40pf2jiUhGaBNk334wOtNYvAaXg/mHOXhy/Y=
|
||||
github.com/emiago/diago v0.23.1-0.20251211215055-e1d875617111/go.mod h1:3vLCCq8/G/Ei5I64IHtrmBTag+nPLcgXcKeN1KkLtuc=
|
||||
github.com/emiago/sipgo v1.0.1 h1:8eCZ6L/VX3isyByyv1RrBoQ5GyBoRXBHkNMYjwacRfk=
|
||||
github.com/emiago/sipgo v1.0.1/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/expr-lang/expr v1.17.7 h1:Q0xY/e/2aCIp8g9s/LGvMDCC5PxYlvHgDZRQ4y16JX8=
|
||||
github.com/expr-lang/expr v1.17.7/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/emiago/diago v0.28.0 h1:VCiimhFYLoBTsxH6WrufLSt6tKWG8Fv7LfCkZHqct2E=
|
||||
github.com/emiago/diago v0.28.0/go.mod h1:eQT6j9co9PMQ/25aUiM2jpvwxxWFXLWi2w5R3lZNmKg=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0 h1:o4LxpUnZ1zxiQ+Qjc9kLwXcjz31NGAHmnZ7xoJto3VM=
|
||||
github.com/emiago/dtls/v3 v3.0.0-20260122183559-8b8d23e359c0/go.mod h1:ydcZ977eS1I6uOWodzMuw30BwvNAzT9su/xcNYSJqjA=
|
||||
github.com/emiago/sipgo v1.2.1 h1:5JTwogbe3yQFA3sjBVueN2Q4WTU350tGeBwPYT8HMv0=
|
||||
github.com/emiago/sipgo v1.2.1/go.mod h1:DuwAxBZhKMqIzQFPGZb1MVAGU6Wuxj64oTOhd5dx/FY=
|
||||
github.com/expr-lang/expr v1.17.8 h1:W1loDTT+0PQf5YteHSTpju2qfUfNoBt4yw9+wOEU9VM=
|
||||
github.com/expr-lang/expr v1.17.8/go.mod h1:8/vRC7+7HBzESEqt5kKpYXxrxkr31SaO8r40VO/1IT4=
|
||||
github.com/extism/go-sdk v1.7.1 h1:lWJos6uY+tRFdlIHR+SJjwFDApY7OypS/2nMhiVQ9Sw=
|
||||
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=
|
||||
github.com/gobwas/httphead v0.1.0/go.mod h1:O/RXo79gxV8G+RqlR/otEwx4Q36zl9rqC5u12GKvMCM=
|
||||
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.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
|
||||
github.com/google/jsonschema-go v0.4.2/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-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.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.1.0 h1:EXxup5VWBErHot2Ri4MFToPf6KCzLDTbCt2x6GLfw8I=
|
||||
github.com/jwetzell/osc-go v0.1.0/go.mod h1:xLz0jTwebSxtx1TkKN1YVdeRqvpFNweDhTut5TE393A=
|
||||
github.com/jwetzell/osc-go v0.2.0 h1:4as+BYCeZhEddFczGveP5yZZxvY728Uavz+ZSLZfOII=
|
||||
github.com/jwetzell/osc-go v0.2.0/go.mod h1:D3ZIXYB12bt4S35lKFUqgCFbF1Y+9Ld0sOhHA9mGZZM=
|
||||
github.com/jwetzell/psn-go v0.3.0 h1:WVpCEmExYE8a+I5hQak5jNJJp2x35VdGX/VuMUKPmhY=
|
||||
github.com/jwetzell/psn-go v0.3.0/go.mod h1:bcEAeti4sQM375buujb3mIfmUstD4Aby18gq3ENb6+o=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=
|
||||
github.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
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.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/nats-io/nats.go v1.48.0 h1:pSFyXApG+yWU/TgbKCjmm5K4wrHu86231/w84qRVR+U=
|
||||
github.com/nats-io/nats.go v1.48.0/go.mod h1:iRWIPokVIFbVijxuMQq4y9ttaBTMe0SFdlZfMDd+33g=
|
||||
github.com/nats-io/nkeys v0.4.11 h1:q44qGV008kYd9W1b1nEBkNzvnWxtRSQ7A8BoqRrcfa0=
|
||||
github.com/nats-io/nkeys v0.4.11/go.mod h1:szDimtgmfOi9n25JpfIdGw12tZFYXqhGxjhVxsatHVE=
|
||||
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.1 h1:V0xpGuD/N8Mi+fQNDynXohVvp7ZztevW5io8CUWlPmU=
|
||||
github.com/nats-io/jwt/v2 v2.8.1/go.mod h1:nWnOEEiVMiKHQpnAy4eXlizVEtSfzacZ1Q43LIRavZg=
|
||||
github.com/nats-io/nats-server/v2 v2.12.6 h1:Egbx9Vl7Ch8wTtpXPGqbehkZ+IncKqShUxvrt1+Enc8=
|
||||
github.com/nats-io/nats-server/v2 v2.12.6/go.mod h1:4HPlrvtmSO3yd7KcElDNMx9kv5EBJBnJJzQPptXlheo=
|
||||
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.15 h1:JACV5jRVO9V856KOapQ7x+EY8Jo3qw1vJt/9Jpwzkk4=
|
||||
github.com/nats-io/nkeys v0.4.15/go.mod h1:CpMchTXC9fxA5zrMo4KpySxNjiDVvr8ANOSZdiNfUrs=
|
||||
github.com/nats-io/nuid v1.0.1 h1:5iA8DT8V7q8WK2EScv2padNa/rTESc1KdnPw4TC2paw=
|
||||
github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
||||
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
||||
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
@@ -64,41 +111,86 @@ 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.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=
|
||||
github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=
|
||||
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.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=
|
||||
github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/urfave/cli/v3 v3.6.1 h1:j8Qq8NyUawj/7rTYdBGrxcH7A/j7/G8Q5LhWEW4G3Mo=
|
||||
github.com/urfave/cli/v3 v3.6.1/go.mod h1:ysVLtOEmg2tOy6PknnYVhDoouyC/6N42TMeoMzskhso=
|
||||
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.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=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.18 h1:sj2fOhtvOe+zI8YJe8qTxLw5zv0ntULLUDwcFOaZQbI=
|
||||
gitlab.com/gomidi/midi/v2 v2.3.18/go.mod h1:jDpP4O4skYi+7iVwt6Zyp18bd2M4hkjtMuw2cmgKgfw=
|
||||
github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0=
|
||||
github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA=
|
||||
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.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=
|
||||
go.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=
|
||||
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=
|
||||
go.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=
|
||||
go.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=
|
||||
go.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
|
||||
go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
|
||||
go.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=
|
||||
go.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0 h1:l706jCMITVouPOqEnii2fIAuO3IVGBRPV5ICjceRb/A=
|
||||
go.opentelemetry.io/proto/otlp v1.9.0/go.mod h1:xE+Cx5E/eEHw+ISFkwPLwCZefwVjY+pqKg1qcK03+/4=
|
||||
go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE=
|
||||
go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0=
|
||||
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.3 h1:bXOww4E/J3f66rav3pX3m8w6jDE4knZjGOw8b5Y6iNE=
|
||||
go.yaml.in/yaml/v3 v3.0.3/go.mod h1:tBHosrYAkRZjRAOREWbDnBXUf08JOwYq++0QNwQiWzI=
|
||||
golang.org/x/crypto v0.42.0 h1:chiH31gIWm57EkTXpwnqf8qeuMUi0yekh6mT2AvFlqI=
|
||||
golang.org/x/crypto v0.42.0/go.mod h1:4+rDnOTJhQCx2q7/j6rAN5XDw8kPjeaXEUR2eL94ix8=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA=
|
||||
golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w=
|
||||
golang.org/x/net v0.44.0 h1:evd8IRDyfNBMBTTY5XRF1vaZlD+EmWx6x8PkhR04H/I=
|
||||
golang.org/x/net v0.44.0/go.mod h1:ECOoLqd5U3Lhyeyo/QDCEVQ4sNgYsqvCZ722XogGieY=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
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.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4=
|
||||
golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA=
|
||||
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
|
||||
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
|
||||
golang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=
|
||||
golang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=
|
||||
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
|
||||
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE=
|
||||
golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w=
|
||||
golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=
|
||||
golang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8=
|
||||
golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA=
|
||||
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.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
|
||||
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
|
||||
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.2 h1:fRMD94s2tITpyJGtBBn7MkMseNpOZU8ZxgC3MMBaXRU=
|
||||
google.golang.org/grpc v1.79.2/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
@@ -110,30 +202,32 @@ 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.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/ccgo/v4 v4.32.0 h1:hjG66bI/kqIPX1b2yT6fr/jt+QedtP2fqojG2VrFuVw=
|
||||
modernc.org/ccgo/v4 v4.32.0/go.mod h1:6F08EBCx5uQc38kMGl+0Nm0oWczoo1c7cgpzEry7Uc0=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
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.1 h1:k8T3gkXWY9sEiytKhcgyiZ2L0DTyCQ/nvX+LoCljoRE=
|
||||
modernc.org/gc/v3 v3.1.1/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/gc/v3 v3.1.2 h1:ZtDCnhonXSZexk/AYsegNRV1lJGgaNZJuKjJSWKyEqo=
|
||||
modernc.org/gc/v3 v3.1.2/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.66.10 h1:yZkb3YeLx4oynyR+iUsXsybsX4Ubx7MQlSYEw4yj59A=
|
||||
modernc.org/libc v1.66.10/go.mod h1:8vGSEwvoUoltr4dlywvHqjtAqHBaw0j1jI7iFBTAr2I=
|
||||
modernc.org/libquickjs v0.12.2 h1:XtF6iD+aoN/pEz1MAQjg1wMZT412pzmOlO11UGLW/wQ=
|
||||
modernc.org/libquickjs v0.12.2/go.mod h1:n+vyuJ4mXh1pQYt1bJttvoCE+2t+MqCM8BFlcSDg/70=
|
||||
modernc.org/libc v1.70.0 h1:U58NawXqXbgpZ/dcdS9kMshu08aiA6b7gusEusqzNkw=
|
||||
modernc.org/libc v1.70.0/go.mod h1:OVmxFGP1CI/Z4L3E0Q3Mf1PDE0BucwMkcXjjLntvHJo=
|
||||
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.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/quickjs v0.17.0 h1:gYZRSCKVokyOiHhZEKwran/NoBaGjAaWk+xJq52SWfQ=
|
||||
modernc.org/quickjs v0.17.0/go.mod h1:TE+wpAYX4V7Nvi/sHRUrd9l5L176ZIiS0as3MMObvC0=
|
||||
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.47.0 h1:R1XyaNpoW4Et9yly+I2EeX7pBza/w+pmYee/0HJDyKk=
|
||||
modernc.org/sqlite v1.47.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
|
||||
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=
|
||||
|
||||
175
internal/common/common.go
Normal file
175
internal/common/common.go
Normal file
@@ -0,0 +1,175 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
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) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]byte, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
elemValue, ok := GetAnyAsByte(elem)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
result[i] = elemValue
|
||||
}
|
||||
return result, true
|
||||
}
|
||||
|
||||
func GetAnyAsIntSlice(value any) ([]int, bool) {
|
||||
v := reflect.ValueOf(value)
|
||||
if v.Kind() != reflect.Slice {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
result := make([]int, v.Len())
|
||||
for i := 0; i < v.Len(); i++ {
|
||||
elem := v.Index(i).Interface()
|
||||
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
|
||||
}
|
||||
424
internal/common/common_test.go
Normal file
424
internal/common/common_test.go
Normal file
@@ -0,0 +1,424 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
8
internal/common/context.go
Normal file
8
internal/common/context.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package common
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RouterContextKey contextKey = contextKey("router")
|
||||
const SourceContextKey contextKey = contextKey("source")
|
||||
const ModulesContextKey contextKey = contextKey("modules")
|
||||
const SenderContextKey contextKey = contextKey("sender")
|
||||
26
internal/common/module.go
Normal file
26
internal/common/module.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type Module interface {
|
||||
Id() string
|
||||
Type() string
|
||||
Start(context.Context) error
|
||||
Stop()
|
||||
}
|
||||
|
||||
type OutputModule interface {
|
||||
Output(context.Context, any) error
|
||||
}
|
||||
|
||||
type KeyValueModule interface {
|
||||
Get(key string) (any, error)
|
||||
Set(key string, value any) error
|
||||
}
|
||||
|
||||
type DatabaseModule interface {
|
||||
Database() *sql.DB
|
||||
}
|
||||
40
internal/common/payload.go
Normal file
40
internal/common/payload.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type WrappedPayload struct {
|
||||
Payload any
|
||||
Modules map[string]Module
|
||||
Sender any
|
||||
Source string
|
||||
End bool
|
||||
}
|
||||
|
||||
func GetWrappedPayload(ctx context.Context, payload any) WrappedPayload {
|
||||
wrappedPayload := WrappedPayload{
|
||||
Payload: payload,
|
||||
End: false,
|
||||
}
|
||||
modules := ctx.Value(ModulesContextKey)
|
||||
if modules != nil {
|
||||
moduleMap, ok := modules.(map[string]Module)
|
||||
if ok {
|
||||
wrappedPayload.Modules = moduleMap
|
||||
} else {
|
||||
wrappedPayload.Modules = make(map[string]Module)
|
||||
}
|
||||
}
|
||||
|
||||
sender := ctx.Value(SenderContextKey)
|
||||
if sender != nil {
|
||||
wrappedPayload.Sender = sender
|
||||
}
|
||||
|
||||
source := ctx.Value(SourceContextKey)
|
||||
if source != nil {
|
||||
wrappedPayload.Source = source.(string)
|
||||
}
|
||||
return wrappedPayload
|
||||
}
|
||||
82
internal/common/payload_test.go
Normal file
82
internal/common/payload_test.go
Normal file
@@ -0,0 +1,82 @@
|
||||
package common_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/test"
|
||||
)
|
||||
|
||||
func TestGoodGetWrappedPayload(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
ctx context.Context
|
||||
payload any
|
||||
expected common.WrappedPayload
|
||||
}{
|
||||
{
|
||||
name: "basic",
|
||||
ctx: t.Context(),
|
||||
payload: "test",
|
||||
expected: common.WrappedPayload{
|
||||
Payload: "test",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "with modules in context",
|
||||
ctx: test.GetContextWithModules(t.Context(), map[string]common.Module{}),
|
||||
payload: "test",
|
||||
expected: common.WrappedPayload{
|
||||
Payload: "test",
|
||||
Modules: map[string]common.Module{},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "with sender in context",
|
||||
ctx: test.GetContextWithSender(t.Context(), "sender"),
|
||||
payload: "test",
|
||||
expected: common.WrappedPayload{
|
||||
Payload: "test",
|
||||
Sender: "sender",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "with source in context",
|
||||
ctx: test.GetContextWithSource(t.Context(), "source"),
|
||||
payload: "test",
|
||||
expected: common.WrappedPayload{
|
||||
Payload: "test",
|
||||
Source: "source",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "with all fields in context",
|
||||
ctx: test.GetContextWithSource(
|
||||
test.GetContextWithSender(
|
||||
test.GetContextWithModules(t.Context(), map[string]common.Module{}),
|
||||
"sender",
|
||||
),
|
||||
"source",
|
||||
),
|
||||
payload: "test",
|
||||
expected: common.WrappedPayload{
|
||||
Payload: "test",
|
||||
Modules: map[string]common.Module{},
|
||||
Sender: "sender",
|
||||
Source: "source",
|
||||
},
|
||||
},
|
||||
}
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
wrappedPayload := common.GetWrappedPayload(testCase.ctx, testCase.payload)
|
||||
|
||||
if !reflect.DeepEqual(wrappedPayload, testCase.expected) {
|
||||
t.Fatalf("GetWrappedPayload expected got %+v, expected %+v", wrappedPayload, testCase.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
15
internal/common/routing.go
Normal file
15
internal/common/routing.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package common
|
||||
|
||||
import "context"
|
||||
|
||||
type RouteIO interface {
|
||||
HandleInput(ctx context.Context, sourceId string, payload any) (bool, []RouteIOError)
|
||||
HandleOutput(ctx context.Context, destinationId string, payload any) error
|
||||
}
|
||||
|
||||
type RouteIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError error `json:"outputError"`
|
||||
ProcessError error `json:"processError"`
|
||||
InputError error `json:"inputError"`
|
||||
}
|
||||
6
internal/config/api.go
Normal file
6
internal/config/api.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
type ApiConfig struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
Port int `json:"port"`
|
||||
}
|
||||
@@ -1,23 +1,7 @@
|
||||
package config
|
||||
|
||||
type Config struct {
|
||||
Api ApiConfig `json:"api"`
|
||||
Modules []ModuleConfig `json:"modules"`
|
||||
Routes []RouteConfig `json:"routes"`
|
||||
}
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params map[string]any `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 map[string]any `json:"params"`
|
||||
}
|
||||
|
||||
7
internal/config/module.go
Normal file
7
internal/config/module.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package config
|
||||
|
||||
type ModuleConfig struct {
|
||||
Id string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
140
internal/config/params.go
Normal file
140
internal/config/params.go
Normal file
@@ -0,0 +1,140 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"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
|
||||
}
|
||||
628
internal/config/params_test.go
Normal file
628
internal/config/params_test.go
Normal file
@@ -0,0 +1,628 @@
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
6
internal/config/processor.go
Normal file
6
internal/config/processor.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
type ProcessorConfig struct {
|
||||
Type string `json:"type"`
|
||||
Params Params `json:"params,omitempty"`
|
||||
}
|
||||
6
internal/config/route.go
Normal file
6
internal/config/route.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package config
|
||||
|
||||
type RouteConfig struct {
|
||||
Input string `json:"input"`
|
||||
Processors []ProcessorConfig `json:"processors"`
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
package framer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Framer interface {
|
||||
Decode([]byte) [][]byte
|
||||
Encode([]byte) []byte
|
||||
@@ -11,19 +7,19 @@ type Framer interface {
|
||||
Buffer() []byte
|
||||
}
|
||||
|
||||
func GetFramer(framingType string) (Framer, error) {
|
||||
func GetFramer(framingType string) Framer {
|
||||
switch framingType {
|
||||
case "CR":
|
||||
return NewByteSeparatorFramer([]byte{'\r'}), nil
|
||||
return NewByteSeparatorFramer([]byte{'\r'})
|
||||
case "LF":
|
||||
return NewByteSeparatorFramer([]byte{'\n'}), nil
|
||||
return NewByteSeparatorFramer([]byte{'\n'})
|
||||
case "CRLF":
|
||||
return NewByteSeparatorFramer([]byte{'\r', '\n'}), nil
|
||||
return NewByteSeparatorFramer([]byte{'\r', '\n'})
|
||||
case "SLIP":
|
||||
return NewSlipFramer(), nil
|
||||
return NewSlipFramer()
|
||||
case "RAW":
|
||||
return NewRawFramer(), nil
|
||||
return NewRawFramer()
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown framing method: %s", framingType)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSeparatorFramer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "new line separator",
|
||||
framer: framer.NewByteSeparatorFramer([]byte{0x0a}),
|
||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "CRLF separator",
|
||||
framer: framer.NewByteSeparatorFramer([]byte{0x0d, 0x0a}),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "extra data after separator",
|
||||
framer: framer.NewByteSeparatorFramer([]byte{0x0d, 0x0a}),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\nextra"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte("extra"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Errorf("separator framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||
}
|
||||
for i, frame := range frames {
|
||||
if !slices.Equal(frame, test.expected[i]) {
|
||||
t.Errorf("separator framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||
t.Errorf("separator framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -59,9 +59,9 @@ func (sf *SlipFramer) Encode(data []byte) []byte {
|
||||
for _, byteToEncode := range data {
|
||||
switch byteToEncode {
|
||||
case END:
|
||||
encodedBytes = append(encodedBytes, ESC_END)
|
||||
encodedBytes = append(encodedBytes, ESC, ESC_END)
|
||||
case ESC:
|
||||
encodedBytes = append(encodedBytes, ESC_ESC)
|
||||
encodedBytes = append(encodedBytes, ESC, ESC_ESC)
|
||||
default:
|
||||
encodedBytes = append(encodedBytes, byteToEncode)
|
||||
}
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSLIPFramer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "OSC SLIP messages",
|
||||
framer: framer.NewSlipFramer(),
|
||||
input: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||
expected: [][]byte{
|
||||
{0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00},
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Errorf("SLIP framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||
}
|
||||
for i, frame := range frames {
|
||||
if !slices.Equal(frame, test.expected[i]) {
|
||||
t.Errorf("SLIP framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||
t.Errorf("SLIP framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
15
internal/framer/test/framer_test.go
Normal file
15
internal/framer/test/framer_test.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestNilGetFramer(t *testing.T) {
|
||||
nilFramer := framer.GetFramer("asldfiudchuehrkbjbkjrbb")
|
||||
|
||||
if nilFramer != nil {
|
||||
t.Fatalf("Expected nil framer, got %v", nilFramer)
|
||||
}
|
||||
}
|
||||
78
internal/framer/test/raw_test.go
Normal file
78
internal/framer/test/raw_test.go
Normal file
@@ -0,0 +1,78 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodRawFramerDecode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
}{
|
||||
{
|
||||
name: "basic raw framer",
|
||||
framer: framer.GetFramer("RAW"),
|
||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello\nWorld\nThis is a test\n"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Fatalf("raw framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||
}
|
||||
for i, frame := range frames {
|
||||
if !slices.Equal(frame, test.expected[i]) {
|
||||
t.Errorf("raw framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodRawFramerEncode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
expected []byte
|
||||
input []byte
|
||||
}{
|
||||
{
|
||||
name: "basic raw framer",
|
||||
framer: framer.GetFramer("RAW"),
|
||||
expected: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frame := test.framer.Encode(test.input)
|
||||
if !slices.Equal(frame, test.expected) {
|
||||
t.Fatalf("raw frame encode got %s, expected %s", frame, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRawFramerBuffer(t *testing.T) {
|
||||
framer := framer.GetFramer("RAW")
|
||||
framer.Decode([]byte("Hello, World!"))
|
||||
|
||||
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||
t.Fatalf("raw framer buffer got %s, expected empty", framer.Buffer())
|
||||
}
|
||||
framer.Clear()
|
||||
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||
t.Fatalf("raw framer buffer got %s, expected empty after clear", framer.Buffer())
|
||||
}
|
||||
}
|
||||
130
internal/framer/test/separator_test.go
Normal file
130
internal/framer/test/separator_test.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSeparatorFramerDecode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "new line separator",
|
||||
framer: framer.GetFramer("LF"),
|
||||
input: []byte("Hello\nWorld\nThis is a test\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "CR separator",
|
||||
framer: framer.GetFramer("CR"),
|
||||
input: []byte("Hello\rWorld\rThis is a test\r"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "CRLF separator",
|
||||
framer: framer.GetFramer("CRLF"),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\n"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "extra data after separator",
|
||||
framer: framer.GetFramer("CRLF"),
|
||||
input: []byte("Hello\r\nWorld\r\nThis is a test\r\nextra"),
|
||||
expected: [][]byte{
|
||||
[]byte("Hello"),
|
||||
[]byte("World"),
|
||||
[]byte("This is a test"),
|
||||
},
|
||||
buffer: []byte("extra"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Fatalf("separator framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||
}
|
||||
for i, frame := range frames {
|
||||
if !slices.Equal(frame, test.expected[i]) {
|
||||
t.Errorf("separator framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||
t.Fatalf("separator framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodSeparatorFramerEncode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "new line separator",
|
||||
framer: framer.GetFramer("LF"),
|
||||
input: []byte("Hello"),
|
||||
expected: []byte("Hello\n"),
|
||||
},
|
||||
{
|
||||
name: "CR separator",
|
||||
framer: framer.GetFramer("CR"),
|
||||
input: []byte("Hello"),
|
||||
expected: []byte("Hello\r"),
|
||||
},
|
||||
{
|
||||
name: "CRLF separator",
|
||||
framer: framer.GetFramer("CRLF"),
|
||||
input: []byte("Hello"),
|
||||
expected: []byte("Hello\r\n"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frame := test.framer.Encode(test.input)
|
||||
if !slices.Equal(frame, test.expected) {
|
||||
t.Fatalf("separator framer got %s, expected %s", frame, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeparatorFrameBuffer(t *testing.T) {
|
||||
framer := framer.GetFramer("LF")
|
||||
framer.Decode([]byte("Hello\nWorld\nThis is a test\nextra"))
|
||||
if !slices.Equal(framer.Buffer(), []byte("extra")) {
|
||||
t.Fatalf("separator framer buffer got %s, expected %s", framer.Buffer(), []byte("extra"))
|
||||
}
|
||||
|
||||
framer.Clear()
|
||||
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||
t.Fatalf("separator framer buffer got %s, expected empty slice", framer.Buffer())
|
||||
}
|
||||
}
|
||||
110
internal/framer/test/slip_test.go
Normal file
110
internal/framer/test/slip_test.go
Normal file
@@ -0,0 +1,110 @@
|
||||
package framer_test
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/framer"
|
||||
)
|
||||
|
||||
func TestGoodSLIPFramerDecode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected [][]byte
|
||||
buffer []byte
|
||||
}{
|
||||
{
|
||||
name: "OSC SLIP messages",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
input: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||
expected: [][]byte{
|
||||
{0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00},
|
||||
},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "SLIP decode escaped end",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
expected: [][]byte{{0xc0}},
|
||||
input: []byte{0xc0, 0xdb, 0xdc, 0xc0},
|
||||
buffer: []byte{},
|
||||
},
|
||||
{
|
||||
name: "SLIP decode escaped escape",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
expected: [][]byte{{0xdb}},
|
||||
input: []byte{0xc0, 0xdb, 0xdd, 0xc0},
|
||||
buffer: []byte{},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frames := test.framer.Decode(test.input)
|
||||
if len(frames) != len(test.expected) {
|
||||
t.Fatalf("SLIP framer got %d frames, expected %d", len(frames), len(test.expected))
|
||||
}
|
||||
for i, frame := range frames {
|
||||
if !slices.Equal(frame, test.expected[i]) {
|
||||
t.Errorf("SLIP framer frame %d got %s, expected %s", i, frame, test.expected[i])
|
||||
}
|
||||
}
|
||||
if !slices.Equal(test.framer.Buffer(), test.buffer) {
|
||||
t.Fatalf("SLIP framer buffer got %s, expected %s", test.framer.Buffer(), test.buffer)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGoodSLIPFramerEncode(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
framer framer.Framer
|
||||
input []byte
|
||||
expected []byte
|
||||
}{
|
||||
{
|
||||
name: "OSC SLIP messages",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
input: []byte{
|
||||
0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
|
||||
},
|
||||
expected: []byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0},
|
||||
},
|
||||
{
|
||||
name: "SLIP encode end",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
input: []byte{0xc0},
|
||||
expected: []byte{0xc0, 0xdb, 0xdc, 0xc0},
|
||||
},
|
||||
{
|
||||
name: "SLIP encode esc",
|
||||
framer: framer.GetFramer("SLIP"),
|
||||
input: []byte{0xdb},
|
||||
expected: []byte{0xc0, 0xdb, 0xdd, 0xc0},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
frame := test.framer.Encode(test.input)
|
||||
if !slices.Equal(frame, test.expected) {
|
||||
t.Fatalf("SLIP framer frame got %s, expected %s", frame, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlipFramerBuffer(t *testing.T) {
|
||||
framer := framer.GetFramer("SLIP")
|
||||
framer.Decode([]byte{0xc0, 0x2f, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0xc0, 0xc0, 0x45})
|
||||
if !slices.Equal(framer.Buffer(), []byte{0x45}) {
|
||||
t.Fatalf("SLIP framer buffer got %s, expected %s", framer.Buffer(), []byte{0x45})
|
||||
}
|
||||
framer.Clear()
|
||||
if !slices.Equal(framer.Buffer(), []byte{}) {
|
||||
t.Fatalf("SLIP framer buffer got %s, expected empty slice", framer.Buffer())
|
||||
}
|
||||
}
|
||||
89
internal/module/db-sqlite.go
Normal file
89
internal/module/db-sqlite.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type DbSqlite struct {
|
||||
config config.ModuleConfig
|
||||
Dsn string
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
db *sql.DB
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "db.sqlite",
|
||||
Title: "SQLite Database",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"dsn": {
|
||||
Type: "string",
|
||||
MinLength: jsonschema.Ptr(1),
|
||||
},
|
||||
},
|
||||
Required: []string{"dsn"},
|
||||
},
|
||||
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
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *DbSqlite) Id() string {
|
||||
return t.config.Id
|
||||
}
|
||||
|
||||
func (t *DbSqlite) Type() string {
|
||||
return t.config.Type
|
||||
}
|
||||
|
||||
func (t *DbSqlite) Start(ctx context.Context) error {
|
||||
t.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("db.sqlite unable to get router from context")
|
||||
}
|
||||
t.router = router
|
||||
t.ctx = ctx
|
||||
|
||||
db, err := sql.Open("sqlite", t.Dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("db.sqlite error opening database: %w", err)
|
||||
}
|
||||
t.db = db
|
||||
defer t.db.Close()
|
||||
<-ctx.Done()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *DbSqlite) Stop() {
|
||||
if t.db != nil {
|
||||
t.db.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (t *DbSqlite) Database() *sql.DB {
|
||||
return t.db
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"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
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
|
||||
return &HTTPClient{config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Id() string {
|
||||
return hc.config.Id
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Type() string {
|
||||
return hc.config.Type
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Run() error {
|
||||
|
||||
hc.client = &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
<-hc.ctx.Done()
|
||||
hc.logger.Debug("router context done in module")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hc *HTTPClient) Output(payload any) error {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
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.Id(), response)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -6,42 +6,78 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"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/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type HTTPServer struct {
|
||||
config config.ModuleConfig
|
||||
Port uint16
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type ResponseData struct {
|
||||
type ResponseIOError struct {
|
||||
Index int `json:"index"`
|
||||
OutputError *string `json:"outputError"`
|
||||
ProcessError *string `json:"processError"`
|
||||
InputError *string `json:"inputError"`
|
||||
}
|
||||
|
||||
type IOResponseData struct {
|
||||
IOErrors []ResponseIOError `json:"ioErrors"`
|
||||
Message string `json:"message"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
type httpServerContextKey string
|
||||
|
||||
type HTTPServerResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
done bool
|
||||
}
|
||||
|
||||
func (hsrw *HTTPServerResponseWriter) WriteHeader(status int) {
|
||||
hsrw.done = true
|
||||
hsrw.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (hsrw *HTTPServerResponseWriter) Write(data []byte) (int, error) {
|
||||
hsrw.done = true
|
||||
return hsrw.ResponseWriter.Write(data)
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "http.server",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "HTTP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("http.server requires a port parameter")
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.server port error: %w", err)
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.server port must be uint16")
|
||||
}
|
||||
|
||||
return &HTTPServer{Port: uint16(portNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &HTTPServer{Port: uint16(portNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -54,57 +90,133 @@ func (hs *HTTPServer) Type() string {
|
||||
return hs.config.Type
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) HandleDefault(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
func (hs *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
responseWriter := HTTPServerResponseWriter{ResponseWriter: w}
|
||||
|
||||
response := ResponseData{
|
||||
response := IOResponseData{
|
||||
Message: "routing successful",
|
||||
Status: "ok",
|
||||
}
|
||||
|
||||
if hs.router != nil {
|
||||
routingErrors := hs.router.HandleInput(hs.Id(), r)
|
||||
inputContext := context.WithValue(hs.ctx, httpServerContextKey("responseWriter"), &responseWriter)
|
||||
senderAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr)
|
||||
if err == nil {
|
||||
inputContext = context.WithValue(inputContext, common.SenderContextKey, senderAddr)
|
||||
}
|
||||
aRouteFound, routingErrors := hs.router.HandleInput(inputContext, hs.Id(), r)
|
||||
if !responseWriter.done {
|
||||
if aRouteFound {
|
||||
if routingErrors != nil {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Status = "error"
|
||||
response.Message = "routing failed"
|
||||
|
||||
response.IOErrors = []ResponseIOError{}
|
||||
for _, responseIOError := range routingErrors {
|
||||
errorToAdd := ResponseIOError{
|
||||
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)
|
||||
|
||||
}
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
} else {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
response.Message = "routing successful"
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
response.Status = "error"
|
||||
response.Message = "no matching routes found"
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
} else {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
response.Message = "no router registered"
|
||||
response.Status = "error"
|
||||
}
|
||||
|
||||
json.NewEncoder(w).Encode(response)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Run() error {
|
||||
http.HandleFunc("/", hs.HandleDefault)
|
||||
func (hs *HTTPServer) Start(ctx context.Context) error {
|
||||
hs.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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),
|
||||
Handler: http.DefaultServeMux,
|
||||
Handler: hs,
|
||||
}
|
||||
|
||||
go func() {
|
||||
<-hs.ctx.Done()
|
||||
hs.logger.Debug("router context done in module")
|
||||
httpServer.Close()
|
||||
}()
|
||||
|
||||
err := httpServer.ListenAndServe()
|
||||
// TODO(jwetzell): handle server closed error differently
|
||||
if err != nil {
|
||||
if err.Error() != "http: Server closed" {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
<-hs.ctx.Done()
|
||||
hs.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Output(payload any) error {
|
||||
return errors.New("http.server output is not implemented")
|
||||
func (hs *HTTPServer) Output(ctx context.Context, payload any) error {
|
||||
responseWriter, ok := ctx.Value(httpServerContextKey("responseWriter")).(*HTTPServerResponseWriter)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server output must originate from an http.server input")
|
||||
}
|
||||
|
||||
payloadResponse, ok := common.GetAnyAs[processor.HTTPResponse](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("http.server is only able to output HTTPResponse")
|
||||
}
|
||||
|
||||
if responseWriter.done {
|
||||
return errors.New("http.server response writer has already been written to")
|
||||
}
|
||||
|
||||
responseWriter.WriteHeader(payloadResponse.Status)
|
||||
responseWriter.Write(payloadResponse.Body)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (hs *HTTPServer) Stop() {
|
||||
hs.cancel()
|
||||
}
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type Interval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
ticker *time.Ticker
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "gen.interval",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
duration, ok := params["duration"]
|
||||
if !ok {
|
||||
return nil, errors.New("gen.interval requires a duration parameter")
|
||||
}
|
||||
|
||||
durationNum, ok := duration.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("gen.interval duration must be number")
|
||||
}
|
||||
|
||||
return &Interval{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (i *Interval) Id() string {
|
||||
return i.config.Id
|
||||
}
|
||||
|
||||
func (i *Interval) Type() string {
|
||||
return i.config.Type
|
||||
}
|
||||
|
||||
func (i *Interval) Run() error {
|
||||
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
||||
i.ticker = ticker
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-i.ctx.Done():
|
||||
i.logger.Debug("router context done in module")
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if i.router != nil {
|
||||
i.router.HandleInput(i.Id(), time.Now())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (i *Interval) Output(payload any) error {
|
||||
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
||||
return nil
|
||||
}
|
||||
@@ -8,8 +8,9 @@ import (
|
||||
"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"
|
||||
)
|
||||
@@ -17,30 +18,36 @@ import (
|
||||
type MIDIInput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.input",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "MIDI Input",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.input requires a port parameter")
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.input port error: %w", err)
|
||||
}
|
||||
|
||||
portString, ok := port.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.input port must be a string")
|
||||
}
|
||||
|
||||
return &MIDIInput{config: config, Port: portString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &MIDIInput{config: config, Port: portString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -53,8 +60,18 @@ func (mi *MIDIInput) Type() string {
|
||||
return mi.config.Type
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Run() error {
|
||||
func (mi *MIDIInput) Start(ctx context.Context) error {
|
||||
mi.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
in, err := midi.FindInPort(mi.Port)
|
||||
if err != nil {
|
||||
@@ -63,7 +80,7 @@ func (mi *MIDIInput) Run() error {
|
||||
|
||||
stop, err := midi.ListenTo(in, func(msg midi.Message, timestampms int32) {
|
||||
if mi.router != nil {
|
||||
mi.router.HandleInput(mi.Id(), msg)
|
||||
mi.router.HandleInput(mi.ctx, mi.Id(), msg)
|
||||
}
|
||||
}, midi.UseSysEx())
|
||||
|
||||
@@ -74,10 +91,10 @@ func (mi *MIDIInput) Run() error {
|
||||
defer stop()
|
||||
|
||||
<-mi.ctx.Done()
|
||||
mi.logger.Debug("router context done in module")
|
||||
mi.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mi *MIDIInput) Output(payload any) error {
|
||||
return errors.New("midi.input output is not implemented")
|
||||
func (mi *MIDIInput) Stop() {
|
||||
mi.cancel()
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
//go:build cgo
|
||||
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"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 MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
Port string
|
||||
SendFunc func(midi.Message) error
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "midi.output",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
port, ok := params["port"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.output requires a port parameter")
|
||||
}
|
||||
|
||||
portString, ok := port.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("midi.output port must be a string")
|
||||
}
|
||||
|
||||
return &MIDIOutput{config: config, Port: portString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Id() string {
|
||||
return mo.config.Id
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Type() string {
|
||||
return mo.config.Type
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Run() error {
|
||||
defer midi.CloseDriver()
|
||||
|
||||
out, err := midi.FindOutPort(mo.Port)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("midi.output can't find output port: %s", mo.Port)
|
||||
}
|
||||
|
||||
send, err := midi.SendTo(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mo.SendFunc = send
|
||||
|
||||
<-mo.ctx.Done()
|
||||
mo.logger.Debug("router context done in module")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Output(payload any) error {
|
||||
if mo.SendFunc == nil {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := payload.(midi.Message)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only ouptut midi.Message")
|
||||
}
|
||||
|
||||
return mo.SendFunc(payloadMessage)
|
||||
}
|
||||
111
internal/module/midi-output.go
Normal file
111
internal/module/midi-output.go
Normal file
@@ -0,0 +1,111 @@
|
||||
//go:build cgo
|
||||
|
||||
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"
|
||||
"gitlab.com/gomidi/midi/v2"
|
||||
_ "gitlab.com/gomidi/midi/v2/drivers/rtmididrv"
|
||||
)
|
||||
|
||||
type MIDIOutput struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.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",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("midi.output port error: %w", err)
|
||||
}
|
||||
|
||||
return &MIDIOutput{config: config, Port: portString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Id() string {
|
||||
return mo.config.Id
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Type() string {
|
||||
return mo.config.Type
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Start(ctx context.Context) error {
|
||||
mo.logger.Debug("running")
|
||||
defer midi.CloseDriver()
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
out, err := midi.FindOutPort(mo.Port)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("midi.output can't find output port: %s", mo.Port)
|
||||
}
|
||||
|
||||
send, err := midi.SendTo(out)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
mo.SendFunc = send
|
||||
|
||||
<-mo.ctx.Done()
|
||||
mo.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Output(ctx context.Context, payload any) error {
|
||||
if mo.SendFunc == nil {
|
||||
return errors.New("midi.output output is not setup")
|
||||
}
|
||||
|
||||
payloadMessage, ok := common.GetAnyAs[midi.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("midi.output can only output midi.Message")
|
||||
}
|
||||
|
||||
return mo.SendFunc(payloadMessage)
|
||||
}
|
||||
|
||||
func (mo *MIDIOutput) Stop() {
|
||||
mo.cancel()
|
||||
}
|
||||
@@ -1,30 +1,27 @@
|
||||
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"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type ModuleError struct {
|
||||
Index int
|
||||
Config config.ModuleConfig
|
||||
Error error
|
||||
}
|
||||
|
||||
type Module interface {
|
||||
Id() string
|
||||
Type() string
|
||||
Run() error
|
||||
Output(any) error
|
||||
Index int `json:"index"`
|
||||
Config config.ModuleConfig `json:"config"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type ModuleRegistration struct {
|
||||
Type string `json:"type"`
|
||||
New func(context.Context, config.ModuleConfig, route.RouteIO) (Module, error)
|
||||
Title string `json:"title,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
ParamsSchema *jsonschema.Schema `json:"paramsSchema,omitempty"`
|
||||
New func(config.ModuleConfig) (common.Module, error)
|
||||
}
|
||||
|
||||
func RegisterModule(mod ModuleRegistration) {
|
||||
@@ -49,3 +46,7 @@ var (
|
||||
moduleRegistryMu sync.RWMutex
|
||||
ModuleRegistry = make(map[string]ModuleRegistration)
|
||||
)
|
||||
|
||||
func CreateLogger(config config.ModuleConfig) *slog.Logger {
|
||||
return slog.Default().With("component", "module", "id", config.Id, "type", config.Type)
|
||||
}
|
||||
|
||||
@@ -7,63 +7,67 @@ import (
|
||||
"log/slog"
|
||||
|
||||
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/route"
|
||||
)
|
||||
|
||||
type MQTTClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Broker string
|
||||
ClientID string
|
||||
Topic string
|
||||
client mqtt.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "mqtt.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "MQTT Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"broker": {
|
||||
Title: "Broker URL",
|
||||
Type: "string",
|
||||
},
|
||||
"topic": {
|
||||
Title: "Topic",
|
||||
Type: "string",
|
||||
},
|
||||
"clientId": {
|
||||
Title: "Client ID",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"broker", "topic", "clientId"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
broker, ok := params["broker"]
|
||||
brokerString, err := params.GetString("broker")
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client requires a broker parameter")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client broker error: %w", err)
|
||||
}
|
||||
|
||||
brokerString, ok := broker.(string)
|
||||
topicString, err := params.GetString("topic")
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client broker must be string")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client topic error: %w", err)
|
||||
}
|
||||
|
||||
topic, ok := params["topic"]
|
||||
clientIdString, err := params.GetString("clientId")
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client requires a topic parameter")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("mqtt.client clientId error: %w", err)
|
||||
}
|
||||
|
||||
topicString, ok := topic.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client topic must be string")
|
||||
}
|
||||
|
||||
clientId, ok := params["clientId"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client requires a clientId parameter")
|
||||
}
|
||||
|
||||
clientIdString, ok := clientId.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("mqtt.client clientId must be string")
|
||||
}
|
||||
|
||||
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &MQTTClient{config: config, Broker: brokerString, Topic: topicString, ClientID: clientIdString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -76,7 +80,18 @@ func (mc *MQTTClient) Type() string {
|
||||
return mc.config.Type
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Run() error {
|
||||
func (mc *MQTTClient) Start(ctx context.Context) error {
|
||||
mc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
opts := mqtt.NewClientOptions()
|
||||
opts.AddBroker(mc.Broker)
|
||||
opts.SetClientID(mc.ClientID)
|
||||
@@ -85,12 +100,13 @@ func (mc *MQTTClient) Run() error {
|
||||
|
||||
opts.OnConnect = func(c mqtt.Client) {
|
||||
token := mc.client.Subscribe(mc.Topic, 1, func(c mqtt.Client, m mqtt.Message) {
|
||||
mc.router.HandleInput(mc.Id(), m)
|
||||
mc.router.HandleInput(mc.ctx, mc.Id(), m)
|
||||
})
|
||||
token.Wait()
|
||||
}
|
||||
|
||||
mc.client = mqtt.NewClient(opts)
|
||||
defer mc.client.Disconnect(250)
|
||||
|
||||
token := mc.client.Connect()
|
||||
|
||||
@@ -101,14 +117,12 @@ func (mc *MQTTClient) Run() error {
|
||||
}
|
||||
|
||||
<-mc.ctx.Done()
|
||||
mc.logger.Debug("router context done in module")
|
||||
mc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Output(payload any) error {
|
||||
payloadMessage, ok := payload.(mqtt.Message)
|
||||
|
||||
fmt.Printf("payload type: %T\n", payload)
|
||||
func (mc *MQTTClient) Output(ctx context.Context, payload any) error {
|
||||
payloadMessage, ok := common.GetAnyAs[mqtt.Message](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("mqtt.client is only able to output a MQTTMessage")
|
||||
@@ -128,3 +142,7 @@ func (mc *MQTTClient) Output(payload any) error {
|
||||
|
||||
return token.Error()
|
||||
}
|
||||
|
||||
func (mc *MQTTClient) Stop() {
|
||||
mc.cancel()
|
||||
}
|
||||
|
||||
@@ -5,52 +5,57 @@ import (
|
||||
"errors"
|
||||
"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/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
|
||||
router common.RouteIO
|
||||
URL string
|
||||
Subject string
|
||||
client *nats.Conn
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "nats.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "NATS Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"url": {
|
||||
Title: "NATS Server URL",
|
||||
Type: "string",
|
||||
},
|
||||
"subject": {
|
||||
Title: "Subject",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"url", "subject"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
url, ok := params["url"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("nats.client requires a url parameter")
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, errors.New("nats.client url error: " + err.Error())
|
||||
}
|
||||
|
||||
urlString, ok := url.(string)
|
||||
subjectString, err := params.GetString("subject")
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("nats.client url must be string")
|
||||
if err != nil {
|
||||
return nil, errors.New("nats.client subject error: " + err.Error())
|
||||
}
|
||||
|
||||
subject, ok := params["subject"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("nats.client requires a subject parameter")
|
||||
}
|
||||
|
||||
subjectString, ok := subject.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("nats.client subject must be string")
|
||||
}
|
||||
|
||||
return &NATSClient{config: config, URL: urlString, Subject: subjectString, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &NATSClient{config: config, URL: urlString, Subject: subjectString, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -63,7 +68,19 @@ func (nc *NATSClient) Type() string {
|
||||
return nc.config.Type
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Run() error {
|
||||
func (nc *NATSClient) Start(ctx context.Context) error {
|
||||
nc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
client, err := nats.Connect(nc.URL, nats.RetryOnFailedConnect(true))
|
||||
|
||||
if err != nil {
|
||||
@@ -77,7 +94,7 @@ func (nc *NATSClient) Run() error {
|
||||
|
||||
sub, err := nc.client.Subscribe(nc.Subject, func(msg *nats.Msg) {
|
||||
if nc.router != nil {
|
||||
nc.router.HandleInput(nc.Id(), msg)
|
||||
nc.router.HandleInput(nc.ctx, nc.Id(), msg)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -88,13 +105,13 @@ func (nc *NATSClient) Run() error {
|
||||
defer sub.Unsubscribe()
|
||||
|
||||
<-nc.ctx.Done()
|
||||
nc.logger.Debug("router context done in module")
|
||||
nc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Output(payload any) error {
|
||||
func (nc *NATSClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadMessage, ok := payload.(processor.NATSMessage)
|
||||
payloadMessage, ok := common.GetAnyAs[processor.NATSMessage](payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("nats.client is only able to output NATSMessage")
|
||||
@@ -112,3 +129,7 @@ func (nc *NATSClient) Output(payload any) error {
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (nc *NATSClient) Stop() {
|
||||
nc.cancel()
|
||||
}
|
||||
|
||||
133
internal/module/nats-server.go
Normal file
133
internal/module/nats-server.go
Normal file
@@ -0,0 +1,133 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
)
|
||||
|
||||
type NATSServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
Ip string
|
||||
Port int
|
||||
router common.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",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`4222`),
|
||||
},
|
||||
},
|
||||
Required: []string{},
|
||||
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 4222
|
||||
} else {
|
||||
return nil, fmt.Errorf("nats.server port error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("nats.server ip error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
_, err = net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &NATSServer{config: moduleConfig, logger: CreateLogger(moduleConfig), Ip: ipString, Port: portNum}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Id() string {
|
||||
return ns.config.Id
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Type() string {
|
||||
return ns.config.Type
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Start(ctx context.Context) error {
|
||||
ns.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ns.server = natsServer
|
||||
natsServer.Start()
|
||||
defer natsServer.Shutdown()
|
||||
|
||||
if !natsServer.ReadyForConnections(5 * time.Second) {
|
||||
return errors.New("nats.server failed to start")
|
||||
}
|
||||
ns.logger.Info("NATS server started", "client_url", natsServer.ClientURL())
|
||||
|
||||
<-ns.ctx.Done()
|
||||
|
||||
ns.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ns *NATSServer) Stop() {
|
||||
ns.cancel()
|
||||
if ns.server != nil {
|
||||
ns.server.Shutdown()
|
||||
}
|
||||
}
|
||||
@@ -2,31 +2,33 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"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
|
||||
router common.RouteIO
|
||||
decoder *psn.Decoder
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "psn.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "PosiStageNet Client",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
|
||||
return &PSNClient{config: config, decoder: psn.NewDecoder(), ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &PSNClient{config: config, decoder: psn.NewDecoder(), logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -39,7 +41,17 @@ func (pc *PSNClient) Type() string {
|
||||
return pc.config.Type
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Run() error {
|
||||
func (pc *PSNClient) Start(ctx context.Context) error {
|
||||
pc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", "236.10.10.10:56565")
|
||||
if err != nil {
|
||||
@@ -59,7 +71,7 @@ func (pc *PSNClient) Run() error {
|
||||
select {
|
||||
case <-pc.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
pc.logger.Debug("router context done in module")
|
||||
pc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
pc.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
@@ -77,21 +89,22 @@ func (pc *PSNClient) Run() error {
|
||||
message := buffer[:numBytes]
|
||||
err := pc.decoder.Decode(message)
|
||||
if err != nil {
|
||||
pc.logger.Error("psn.client problem decoding psn traffic", "error", err)
|
||||
pc.logger.Error("problem decoding psn traffic", "error", err)
|
||||
}
|
||||
|
||||
if pc.router != nil {
|
||||
// TODO(jwetzell): better input handling
|
||||
for _, tracker := range pc.decoder.Trackers {
|
||||
pc.router.HandleInput(pc.Id(), tracker)
|
||||
pc.router.HandleInput(pc.ctx, pc.Id(), tracker)
|
||||
}
|
||||
} else {
|
||||
pc.logger.Error("psn.client has no router")
|
||||
pc.logger.Error("has no router")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (pc *PSNClient) Output(payload any) error {
|
||||
return fmt.Errorf("psn.client output is not implemented")
|
||||
func (pc *PSNClient) Stop() {
|
||||
pc.cancel()
|
||||
}
|
||||
|
||||
126
internal/module/redis-client.go
Normal file
126
internal/module/redis-client.go
Normal file
@@ -0,0 +1,126 @@
|
||||
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/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router common.RouteIO
|
||||
Host string
|
||||
Port uint16
|
||||
client *redis.Client
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "redis.client",
|
||||
Title: "Redis Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
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
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
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 ...interface{}) {
|
||||
msg := fmt.Sprintf(format, v...)
|
||||
rc.logger.Debug(msg)
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Start(ctx context.Context) error {
|
||||
redis.SetLogger(rc)
|
||||
rc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
||||
|
||||
if !ok {
|
||||
return errors.New("redis.client unable to get router from context")
|
||||
}
|
||||
|
||||
rc.router = router
|
||||
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.client = client
|
||||
|
||||
defer client.Close()
|
||||
|
||||
<-rc.ctx.Done()
|
||||
rc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Stop() {
|
||||
rc.cancel()
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Get(key string) (any, error) {
|
||||
if rc.client != nil {
|
||||
val, err := rc.client.Get(rc.ctx, key).Result()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return val, nil
|
||||
}
|
||||
return nil, errors.New("redis.client not setup")
|
||||
}
|
||||
|
||||
func (rc *RedisClient) Set(key string, value any) error {
|
||||
if rc.client != nil {
|
||||
status := rc.client.Set(rc.ctx, key, value, 0)
|
||||
return status.Err()
|
||||
}
|
||||
return errors.New("redis.client not setup")
|
||||
}
|
||||
@@ -9,74 +9,72 @@ import (
|
||||
"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/framer"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
"go.bug.st/serial"
|
||||
)
|
||||
|
||||
type SerialClient struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.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",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "Serial Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "string",
|
||||
},
|
||||
"baudRate": {
|
||||
Title: "Baud Rate",
|
||||
Type: "integer",
|
||||
},
|
||||
},
|
||||
Required: []string{"port", "baudRate"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("serial.client requires a port parameter")
|
||||
}
|
||||
|
||||
portString, ok := port.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("serial.client port must be a string")
|
||||
}
|
||||
|
||||
framingMethod := "RAW"
|
||||
|
||||
framingMethodRaw, ok := params["framing"]
|
||||
|
||||
if ok {
|
||||
framingMethodString, ok := framingMethodRaw.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("serial.client framing method must be a string")
|
||||
}
|
||||
framingMethod = framingMethodString
|
||||
}
|
||||
|
||||
framer, err := framer.GetFramer(framingMethod)
|
||||
|
||||
portString, err := params.GetString("port")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("serial.client port error: %w", err)
|
||||
}
|
||||
|
||||
buadRate, ok := params["baudRate"]
|
||||
if !ok {
|
||||
return nil, errors.New("serial.client requires a baudRate parameter")
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client framing error: %w", err)
|
||||
}
|
||||
|
||||
baudRateNum, ok := buadRate.(float64)
|
||||
if !ok {
|
||||
return nil, errors.New("serial.client baudRate must be a number")
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("serial.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
baudRateInt, err := params.GetInt("baudRate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("serial.client baudRate error: %w", err)
|
||||
}
|
||||
|
||||
mode := serial.Mode{
|
||||
BaudRate: int(baudRateNum),
|
||||
BaudRate: baudRateInt,
|
||||
}
|
||||
|
||||
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &SerialClient{config: config, Port: portString, Framer: framer, Mode: &mode, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -101,12 +99,23 @@ func (sc *SerialClient) SetupPort() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Run() error {
|
||||
func (sc *SerialClient) Start(ctx context.Context) error {
|
||||
sc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-sc.ctx.Done()
|
||||
sc.logger.Debug("router context done in module")
|
||||
sc.logger.Debug("done")
|
||||
if sc.port != nil {
|
||||
sc.port.Close()
|
||||
}
|
||||
@@ -116,10 +125,10 @@ func (sc *SerialClient) Run() error {
|
||||
err := sc.SetupPort()
|
||||
if err != nil {
|
||||
if sc.ctx.Err() != nil {
|
||||
sc.logger.Debug("router context done in module")
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
sc.logger.Error("serial.client", "error", err.Error())
|
||||
sc.logger.Error("port setup error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
@@ -127,14 +136,14 @@ func (sc *SerialClient) Run() error {
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("router context done in module")
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for {
|
||||
select {
|
||||
case <-sc.ctx.Done():
|
||||
sc.logger.Debug("router context done in module")
|
||||
sc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := sc.port.Read(buffer)
|
||||
@@ -149,9 +158,9 @@ func (sc *SerialClient) Run() error {
|
||||
messages := sc.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if sc.router != nil {
|
||||
sc.router.HandleInput(sc.Id(), message)
|
||||
sc.router.HandleInput(sc.ctx, sc.Id(), message)
|
||||
} else {
|
||||
sc.logger.Error("serial.client has no router")
|
||||
sc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,14 +171,18 @@ func (sc *SerialClient) Run() error {
|
||||
}
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Output(payload any) error {
|
||||
func (sc *SerialClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("serial.client can only ouptut bytes")
|
||||
return errors.New("serial.client can only output bytes")
|
||||
}
|
||||
|
||||
_, err := sc.port.Write(sc.Framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (sc *SerialClient) Stop() {
|
||||
sc.cancel()
|
||||
}
|
||||
|
||||
@@ -2,92 +2,123 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/diago"
|
||||
"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/route"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type SIPCallServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent 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",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
portNum := 5060
|
||||
Title: "SIP Call Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`5060`),
|
||||
},
|
||||
"transport": {
|
||||
Title: "Transport",
|
||||
Type: "string",
|
||||
Enum: []any{"udp", "tcp", "ws", "udp4", "tcp4"},
|
||||
Default: json.RawMessage(`"udp"`),
|
||||
},
|
||||
"userAgent": {
|
||||
Title: "User Agent",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"showbridge"`),
|
||||
},
|
||||
},
|
||||
Required: []string{},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
|
||||
port, ok := params["port"]
|
||||
if ok {
|
||||
specificPortNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.call.server port must be a number")
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 5060
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server port error: %w", err)
|
||||
}
|
||||
portNum = int(specificPortNum)
|
||||
}
|
||||
|
||||
ipString := "0.0.0.0"
|
||||
|
||||
ip, ok := params["ip"]
|
||||
if ok {
|
||||
|
||||
specificIpString, ok := ip.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.call.server ip must be a string")
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server ip error: %w", err)
|
||||
}
|
||||
ipString = specificIpString
|
||||
}
|
||||
|
||||
transportString := "udp"
|
||||
|
||||
transport, ok := params["transport"]
|
||||
if ok {
|
||||
|
||||
specificTransportString, ok := transport.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.call.server transport must be a string")
|
||||
transportString, err := params.GetString("transport")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
transportString = "udp"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server transport error: %w", err)
|
||||
}
|
||||
transportString = specificTransportString
|
||||
}
|
||||
|
||||
userAgentString := "showbridge"
|
||||
|
||||
userAgent, ok := params["userAgent"]
|
||||
if ok {
|
||||
|
||||
specificTransportString, ok := userAgent.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.call.server userAgent must be a string")
|
||||
userAgentString, err := params.GetString("userAgent")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
userAgentString = "showbridge"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.call.server userAgent error: %w", err)
|
||||
}
|
||||
userAgentString = specificTransportString
|
||||
}
|
||||
return &SIPCallServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
|
||||
return &SIPCallServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -100,7 +131,18 @@ func (scs *SIPCallServer) Type() string {
|
||||
return scs.config.Type
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Run() error {
|
||||
func (scs *SIPCallServer) Start(ctx context.Context) error {
|
||||
scs.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
diagoLogger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
|
||||
ua, _ := sipgo.NewUA(
|
||||
@@ -129,7 +171,7 @@ func (scs *SIPCallServer) Run() error {
|
||||
scs.dg = dg
|
||||
|
||||
<-scs.ctx.Done()
|
||||
scs.logger.Debug("router context done in module")
|
||||
scs.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -137,51 +179,78 @@ func (scs *SIPCallServer) HandleCall(inDialog *diago.DialogServerSession) {
|
||||
inDialog.Trying()
|
||||
inDialog.Ringing()
|
||||
inDialog.Answer()
|
||||
scs.router.HandleInput(scs.Id(), SIPCallMessage{
|
||||
|
||||
dialogContext := context.WithValue(scs.ctx, sipCallContextKey("call"), &SIPCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
scs.router.HandleInput(dialogContext, scs.Id(), SIPCallMessage{
|
||||
To: inDialog.ToUser(),
|
||||
})
|
||||
<-inDialog.Context().Done()
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Output(payload any) error {
|
||||
func (scs *SIPCallServer) Output(ctx context.Context, payload any) error {
|
||||
|
||||
call, ok := ctx.Value(sipCallContextKey("call")).(*SIPCall)
|
||||
|
||||
payloadMsg, ok := payload.(string)
|
||||
if !ok {
|
||||
return errors.New("sip.call.server output payload must be of type string")
|
||||
return errors.New("sip.call.server output must originate from sip.call.server input")
|
||||
}
|
||||
|
||||
if scs.dg == nil {
|
||||
return errors.New("sip.call.server diago is not initialized")
|
||||
gotLock := call.lock.TryLock()
|
||||
|
||||
if !gotLock {
|
||||
return errors.New("sip.call.server call is already locked")
|
||||
}
|
||||
|
||||
var uri sip.Uri
|
||||
err := sip.ParseUri(payloadMsg, &uri)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.call.server output payload is not a valid SIP URI: %s", err)
|
||||
}
|
||||
outDialog, err := scs.dg.NewDialog(uri, diago.NewDialogOptions{
|
||||
Transport: scs.Transport,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.call.server failed to create new dialog: %s", err)
|
||||
if call.inDialog.LoadState() == sip.DialogStateEnded {
|
||||
return errors.New("sip.call.server inDialog already ended")
|
||||
}
|
||||
|
||||
err = outDialog.Invite(scs.ctx, diago.InviteClientOptions{})
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
err := dtmfWriter.WriteDTMF(dtmfRune)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.call.server failed to send invite: %s", err)
|
||||
return fmt.Errorf("sip.dtmf.server error output dtmf digit at index %d", i)
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PostWait))
|
||||
return nil
|
||||
}
|
||||
|
||||
err = outDialog.Ack(scs.ctx)
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.call.server failed to send ack: %s", err)
|
||||
return err
|
||||
}
|
||||
// TODO(jwetzell): make this configurable
|
||||
// NOTE(jwetzell): wait 5 seconds before hanging up the call
|
||||
time.Sleep(5 * time.Second)
|
||||
err = outDialog.Hangup(scs.ctx)
|
||||
defer audioFile.Close()
|
||||
|
||||
playback, err := call.inDialog.PlaybackCreate()
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.call.server failed to hangup call: %s", err)
|
||||
return err
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PreWait))
|
||||
|
||||
_, err = playback.Play(audioFile, "audio/wav")
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PostWait))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return errors.New("sip.dtmf.server can only output SipDTMFResponse or SipAudioFileResponse")
|
||||
}
|
||||
|
||||
func (scs *SIPCallServer) Stop() {
|
||||
scs.cancel()
|
||||
}
|
||||
|
||||
@@ -2,29 +2,37 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emiago/diago"
|
||||
"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/route"
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
type SIPDTMFServer struct {
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
IP string
|
||||
Port int
|
||||
Transport string
|
||||
UserAgent string
|
||||
Separator string
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type SIPDTMFMessage struct {
|
||||
@@ -32,56 +40,94 @@ type SIPDTMFMessage struct {
|
||||
Digits string
|
||||
}
|
||||
|
||||
type SIPDTMFCall struct {
|
||||
inDialog *diago.DialogServerSession
|
||||
lock sync.Mutex
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "sip.dtmf.server",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
portNum := 5060
|
||||
Title: "SIP DTMF Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage(`5060`),
|
||||
},
|
||||
"transport": {
|
||||
Title: "Transport",
|
||||
Type: "string",
|
||||
Enum: []any{"udp", "tcp", "ws", "udp4", "tcp4"},
|
||||
Default: json.RawMessage(`"udp"`),
|
||||
},
|
||||
"userAgent": {
|
||||
Title: "User Agent",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"showbridge"`),
|
||||
},
|
||||
"separator": {
|
||||
Title: "DTMF Separator",
|
||||
Type: "string",
|
||||
MinLength: jsonschema.Ptr(1),
|
||||
MaxLength: jsonschema.Ptr(1),
|
||||
},
|
||||
},
|
||||
Required: []string{"separator"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
port, ok := params["port"]
|
||||
if ok {
|
||||
specificPortNum, ok := port.(float64)
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.dtmf.server port must be a number")
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
portNum = 5060
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server port error: %w", err)
|
||||
}
|
||||
portNum = int(specificPortNum)
|
||||
}
|
||||
|
||||
ipString := "0.0.0.0"
|
||||
|
||||
ip, ok := params["ip"]
|
||||
if ok {
|
||||
|
||||
specificIpString, ok := ip.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.dtmf.server ip must be a string")
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server ip error: %w", err)
|
||||
}
|
||||
ipString = specificIpString
|
||||
}
|
||||
|
||||
transportString := "udp"
|
||||
|
||||
transport, ok := params["transport"]
|
||||
if ok {
|
||||
|
||||
specificTransportString, ok := transport.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("sip.dtmf.server transport must be a string")
|
||||
transportString, err := params.GetString("transport")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
transportString = "udp"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server transport error: %w", err)
|
||||
}
|
||||
transportString = specificTransportString
|
||||
}
|
||||
|
||||
separator, ok := params["separator"]
|
||||
if !ok {
|
||||
return nil, errors.New("sip.dtmf.server requires a separator parameter")
|
||||
userAgentString, err := params.GetString("userAgent")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
userAgentString = "showbridge"
|
||||
} else {
|
||||
return nil, fmt.Errorf("sip.dtmf.server userAgent error: %w", err)
|
||||
}
|
||||
separatorString, ok := separator.(string)
|
||||
if !ok {
|
||||
return nil, errors.New("sip.dtmf.server separator must be a string")
|
||||
}
|
||||
|
||||
separatorString, err := params.GetString("separator")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("sip.dtmf.server separator error: %w", err)
|
||||
}
|
||||
|
||||
if len(separatorString) != 1 {
|
||||
@@ -91,7 +137,7 @@ func init() {
|
||||
if !strings.ContainsRune("0123456789*#ABCD", rune(separatorString[0])) {
|
||||
return nil, errors.New("sip.dtmf.server separator must be a valid DTMF character")
|
||||
}
|
||||
return &SIPDTMFServer{config: config, ctx: ctx, router: router, IP: ipString, Port: int(portNum), Transport: transportString, Separator: separatorString, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &SIPDTMFServer{config: moduleConfig, IP: ipString, Port: int(portNum), Transport: transportString, UserAgent: userAgentString, Separator: separatorString, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -104,10 +150,22 @@ func (sds *SIPDTMFServer) Type() string {
|
||||
return sds.config.Type
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Run() error {
|
||||
func (sds *SIPDTMFServer) Start(ctx context.Context) error {
|
||||
sds.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
diagoLogger := slog.New(slog.NewJSONHandler(io.Discard, nil))
|
||||
|
||||
ua, _ := sipgo.NewUA(
|
||||
sipgo.WithUserAgent(sds.UserAgent),
|
||||
sipgo.WithUserAgentTransportLayerOptions(sip.WithTransportLayerLogger(diagoLogger)),
|
||||
sipgo.WithUserAgentTransactionLayerOptions(sip.WithTransactionLayerLogger(diagoLogger)),
|
||||
)
|
||||
@@ -132,7 +190,7 @@ func (sds *SIPDTMFServer) Run() error {
|
||||
}
|
||||
|
||||
<-sds.ctx.Done()
|
||||
sds.logger.Debug("router context done in module")
|
||||
sds.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -143,10 +201,14 @@ func (sds *SIPDTMFServer) HandleCall(inDialog *diago.DialogServerSession) error
|
||||
|
||||
reader := inDialog.AudioReaderDTMF()
|
||||
userString := ""
|
||||
|
||||
return reader.Listen(func(dtmf rune) error {
|
||||
if dtmf == rune(sds.Separator[0]) {
|
||||
if sds.router != nil {
|
||||
sds.router.HandleInput(sds.Id(), SIPDTMFMessage{
|
||||
dialogContext := context.WithValue(sds.ctx, sipCallContextKey("call"), &SIPDTMFCall{
|
||||
inDialog: inDialog,
|
||||
})
|
||||
sds.router.HandleInput(dialogContext, sds.Id(), SIPDTMFMessage{
|
||||
To: inDialog.ToUser(),
|
||||
Digits: userString,
|
||||
})
|
||||
@@ -159,6 +221,70 @@ func (sds *SIPDTMFServer) HandleCall(inDialog *diago.DialogServerSession) error
|
||||
}, 5*time.Second)
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Output(payload any) error {
|
||||
return errors.New("sip.dtmf.server output is not implemented")
|
||||
func (sds *SIPDTMFServer) Output(ctx context.Context, payload any) error {
|
||||
call, ok := ctx.Value(sipCallContextKey("call")).(*SIPDTMFCall)
|
||||
|
||||
if !ok {
|
||||
return errors.New("sip.dtmf.server output must originate from sip.dtmf.server input")
|
||||
}
|
||||
|
||||
gotLock := call.lock.TryLock()
|
||||
|
||||
if !gotLock {
|
||||
return errors.New("sip.dtmf.server call is already locked")
|
||||
}
|
||||
|
||||
if call.inDialog.LoadState() == sip.DialogStateEnded {
|
||||
return errors.New("sip.dtmf.server inDialog already ended")
|
||||
}
|
||||
|
||||
payloadDTMFResponse, ok := common.GetAnyAs[processor.SipDTMFResponse](payload)
|
||||
|
||||
if ok {
|
||||
dtmfWriter := call.inDialog.AudioWriterDTMF()
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PreWait))
|
||||
for i, dtmfRune := range payloadDTMFResponse.Digits {
|
||||
err := dtmfWriter.WriteDTMF(dtmfRune)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("sip.dtmf.server error output dtmf digit at index %d", i)
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadDTMFResponse.PostWait))
|
||||
return nil
|
||||
}
|
||||
|
||||
payloadAudioFileResponse, ok := common.GetAnyAs[processor.SipAudioFileResponse](payload)
|
||||
|
||||
if ok {
|
||||
audioFile, err := os.Open(payloadAudioFileResponse.AudioFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer audioFile.Close()
|
||||
|
||||
playback, err := call.inDialog.PlaybackCreate()
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PreWait))
|
||||
|
||||
_, err = playback.Play(audioFile, "audio/wav")
|
||||
|
||||
time.Sleep(time.Millisecond * time.Duration(payloadAudioFileResponse.PostWait))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("sip.dtmf.server can only output SipDTMFResponse or SipAudioFileResponse")
|
||||
}
|
||||
|
||||
func (sds *SIPDTMFServer) Stop() {
|
||||
sds.cancel()
|
||||
}
|
||||
|
||||
@@ -8,9 +8,10 @@ import (
|
||||
"net"
|
||||
"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/route"
|
||||
)
|
||||
|
||||
type TCPClient struct {
|
||||
@@ -18,37 +19,48 @@ type TCPClient struct {
|
||||
framer framer.Framer
|
||||
conn *net.TCPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Addr *net.TCPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.tcp.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "TCP Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Title: "Host",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"framing": {
|
||||
Title: "Framing Method",
|
||||
Type: "string",
|
||||
Enum: []any{"LF", "CR", "CRLF", "SLIP", "RAW"},
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port", "framing"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
host, ok := params["host"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.client requires a host parameter")
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client host error: %w", err)
|
||||
}
|
||||
|
||||
hostString, ok := host.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.client host must be string")
|
||||
}
|
||||
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.client requires a port parameter")
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.client port must be a number")
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.client port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", hostString, uint16(portNum)))
|
||||
@@ -56,26 +68,17 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
framingMethod := "RAW"
|
||||
|
||||
framingMethodRaw, ok := params["framing"]
|
||||
|
||||
if ok {
|
||||
framingMethodString, ok := framingMethodRaw.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("misc.serial.client framing method must be a string")
|
||||
}
|
||||
framingMethod = framingMethodString
|
||||
}
|
||||
|
||||
framer, err := framer.GetFramer(framingMethod)
|
||||
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("net.tcp.client framing error: %w", err)
|
||||
}
|
||||
|
||||
return &TCPClient{framer: framer, Addr: addr, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.client unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
return &TCPClient{framer: framer, Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -88,12 +91,22 @@ func (tc *TCPClient) Type() string {
|
||||
return tc.config.Type
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Run() error {
|
||||
func (tc *TCPClient) Start(ctx context.Context) error {
|
||||
tc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
// TODO(jwetzell): shutdown with router.Context properly
|
||||
go func() {
|
||||
<-tc.ctx.Done()
|
||||
tc.logger.Debug("router context done in module")
|
||||
tc.logger.Debug("done")
|
||||
if tc.conn != nil {
|
||||
tc.conn.Close()
|
||||
}
|
||||
@@ -103,10 +116,10 @@ func (tc *TCPClient) Run() error {
|
||||
err := tc.SetupConn()
|
||||
if err != nil {
|
||||
if tc.ctx.Err() != nil {
|
||||
tc.logger.Debug("router context done in module")
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
}
|
||||
tc.logger.Error("net.tcp.client", "error", err.Error())
|
||||
tc.logger.Error("connection error", "error", err.Error())
|
||||
time.Sleep(time.Second * 2)
|
||||
continue
|
||||
}
|
||||
@@ -114,14 +127,14 @@ func (tc *TCPClient) Run() error {
|
||||
buffer := make([]byte, 1024)
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("router context done in module")
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
READ:
|
||||
for {
|
||||
select {
|
||||
case <-tc.ctx.Done():
|
||||
tc.logger.Debug("router context done in module")
|
||||
tc.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
byteCount, err := tc.conn.Read(buffer)
|
||||
@@ -136,9 +149,9 @@ func (tc *TCPClient) Run() error {
|
||||
messages := tc.framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if tc.router != nil {
|
||||
tc.router.HandleInput(tc.Id(), message)
|
||||
tc.router.HandleInput(tc.ctx, tc.Id(), message)
|
||||
} else {
|
||||
tc.logger.Error("net.tcp.client has no router")
|
||||
tc.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -155,7 +168,7 @@ func (tc *TCPClient) SetupConn() error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Output(payload any) error {
|
||||
func (tc *TCPClient) Output(ctx context.Context, payload any) error {
|
||||
// NOTE(jwetzell): not sure how this would occur but
|
||||
if tc.conn == nil {
|
||||
err := tc.SetupConn()
|
||||
@@ -163,10 +176,14 @@ func (tc *TCPClient) Output(payload any) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
if !ok {
|
||||
return errors.New("net.tcp.client is only able to output bytes")
|
||||
}
|
||||
_, err := tc.conn.Write(tc.framer.Encode(payloadBytes))
|
||||
return err
|
||||
}
|
||||
|
||||
func (tc *TCPClient) Stop() {
|
||||
tc.cancel()
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
@@ -11,9 +12,10 @@ import (
|
||||
"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/route"
|
||||
)
|
||||
|
||||
type TCPServer struct {
|
||||
@@ -21,68 +23,74 @@ type TCPServer struct {
|
||||
Addr *net.TCPAddr
|
||||
Framer framer.Framer
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.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",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.server requires a port parameter")
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.server port must be a number")
|
||||
}
|
||||
|
||||
framingMethod := "RAW"
|
||||
|
||||
framingMethodRaw, ok := params["framing"]
|
||||
|
||||
if ok {
|
||||
framingMethodString, ok := framingMethodRaw.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("misc.serial.client framing method must be a string")
|
||||
}
|
||||
framingMethod = framingMethodString
|
||||
}
|
||||
|
||||
framer, err := framer.GetFramer(framingMethod)
|
||||
|
||||
Title: "TCP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"framing": {
|
||||
Title: "Framing Method",
|
||||
Type: "string",
|
||||
Enum: []any{"LF", "CR", "CRLF", "SLIP", "RAW"},
|
||||
},
|
||||
},
|
||||
Required: []string{"port", "framing"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("net.tcp.server port error: %w", err)
|
||||
}
|
||||
|
||||
ipString := "0.0.0.0"
|
||||
|
||||
ip, ok := params["ip"]
|
||||
if ok {
|
||||
|
||||
specificIpString, ok := ip.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.tcp.server ip must be a string")
|
||||
framingMethodString, err := params.GetString("framing")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.tcp.server framing error: %w", err)
|
||||
}
|
||||
|
||||
framer := framer.GetFramer(framingMethodString)
|
||||
|
||||
if framer == nil {
|
||||
return nil, fmt.Errorf("net.tcp.server unknown framing method: %s", framingMethodString)
|
||||
}
|
||||
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.tcp.server ip error: %w", err)
|
||||
}
|
||||
ipString = specificIpString
|
||||
}
|
||||
|
||||
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &TCPServer{Framer: framer, Addr: addr, config: config, quit: make(chan interface{}), ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &TCPServer{Framer: framer, Addr: addr, config: moduleConfig, quit: make(chan interface{}), logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -107,6 +115,15 @@ 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
|
||||
}
|
||||
}
|
||||
ts.connectionsMu.Unlock()
|
||||
return
|
||||
default:
|
||||
client.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
@@ -126,7 +143,7 @@ ClientRead:
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("net.tcp.server connection reset", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.logger.Debug("connection reset", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -139,7 +156,7 @@ ClientRead:
|
||||
break
|
||||
}
|
||||
}
|
||||
ts.logger.Debug("net.tcp.server stream ended", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.logger.Debug("stream ended", "remoteAddr", client.RemoteAddr().String())
|
||||
ts.connectionsMu.Unlock()
|
||||
}
|
||||
return
|
||||
@@ -149,9 +166,15 @@ ClientRead:
|
||||
messages := ts.Framer.Decode(buffer[0:byteCount])
|
||||
for _, message := range messages {
|
||||
if ts.router != nil {
|
||||
ts.router.HandleInput(ts.Id(), message)
|
||||
senderAddr, ok := client.RemoteAddr().(*net.TCPAddr)
|
||||
if ok {
|
||||
senderCtx := context.WithValue(ts.ctx, common.SenderContextKey, senderAddr)
|
||||
ts.router.HandleInput(senderCtx, ts.Id(), message)
|
||||
} else {
|
||||
ts.logger.Error("net.tcp.server has no router")
|
||||
ts.router.HandleInput(ts.ctx, ts.Id(), message)
|
||||
}
|
||||
} else {
|
||||
ts.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -160,7 +183,18 @@ ClientRead:
|
||||
}
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Run() error {
|
||||
func (ts *TCPServer) Start(ctx context.Context) error {
|
||||
ts.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
listener, err := net.ListenTCP("tcp", ts.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -171,7 +205,7 @@ func (ts *TCPServer) Run() error {
|
||||
<-ts.ctx.Done()
|
||||
close(ts.quit)
|
||||
listener.Close()
|
||||
ts.logger.Debug("router context done in module")
|
||||
ts.logger.Debug("done")
|
||||
}()
|
||||
|
||||
AcceptLoop:
|
||||
@@ -182,7 +216,7 @@ AcceptLoop:
|
||||
case <-ts.quit:
|
||||
break AcceptLoop
|
||||
default:
|
||||
ts.logger.Debug("net.tcp.server problem with listener", "error", err)
|
||||
ts.logger.Debug("problem with listener", "error", err)
|
||||
}
|
||||
} else {
|
||||
ts.wg.Add(1)
|
||||
@@ -197,8 +231,8 @@ AcceptLoop:
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Output(payload any) error {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
func (ts *TCPServer) Output(ctx context.Context, payload any) error {
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
return errors.New("net.tcp.server is only able to output bytes")
|
||||
@@ -219,3 +253,8 @@ func (ts *TCPServer) Output(payload any) error {
|
||||
}
|
||||
return fmt.Errorf("net.tcp.server error during output: %s", errorString)
|
||||
}
|
||||
|
||||
func (ts *TCPServer) Stop() {
|
||||
ts.cancel()
|
||||
ts.wg.Wait()
|
||||
}
|
||||
|
||||
87
internal/module/test/db-sqlite_test.go
Normal file
87
internal/module/test/db-sqlite_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestDbSqliteFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["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 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.ModuleRegistry["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())
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
87
internal/module/test/http-server_test.go
Normal file
87
internal/module/test/http-server_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestHTTPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["http.server"]
|
||||
if !ok {
|
||||
t.Fatalf("http.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "http.server",
|
||||
Params: map[string]any{
|
||||
"port": 3000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create http.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("http.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "http.server" {
|
||||
t.Fatalf("http.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadHTTPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "http.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-numeric port",
|
||||
params: map[string]any{"port": "3000"},
|
||||
errorString: "http.server port error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("http.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("http.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("http.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
87
internal/module/test/midi-input_test.go
Normal file
87
internal/module/test/midi-input_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMIDIInputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.input",
|
||||
Params: map[string]any{
|
||||
"port": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create midi.input module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("midi.input module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "midi.input" {
|
||||
t.Fatalf("midi.input module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMIDIInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "midi.input port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port",
|
||||
params: map[string]any{"port": 123},
|
||||
errorString: "midi.input port error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["midi.input"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.input module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.input",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("midi.input got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.input expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("midi.input got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
87
internal/module/test/midi-output_test.go
Normal file
87
internal/module/test/midi-output_test.go
Normal file
@@ -0,0 +1,87 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMIDIOutputFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.output",
|
||||
Params: map[string]any{
|
||||
"port": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create midi.output module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("midi.output module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "midi.output" {
|
||||
t.Fatalf("midi.output module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMIDIOutput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "midi.output port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port",
|
||||
params: map[string]any{"port": 123},
|
||||
errorString: "midi.output port error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["midi.output"]
|
||||
if !ok {
|
||||
t.Fatalf("midi.output module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "midi.output",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("midi.output got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("midi.output expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("midi.output got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
60
internal/module/test/module_test.go
Normal file
60
internal/module/test/module_test.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"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"
|
||||
)
|
||||
|
||||
func TestModuleBadRegistrationNoType(t *testing.T) {
|
||||
defer func() {
|
||||
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.TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationNoNew(t *testing.T) {
|
||||
defer func() {
|
||||
if r := recover(); r == nil {
|
||||
t.Fatalf("processor registration should have panicked but did not")
|
||||
}
|
||||
}()
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: nil,
|
||||
})
|
||||
}
|
||||
|
||||
func TestModuleBadRegistrationExistingType(t *testing.T) {
|
||||
defer func() {
|
||||
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.TestModule{}, nil
|
||||
},
|
||||
})
|
||||
|
||||
module.RegisterModule(module.ModuleRegistration{
|
||||
Type: "module.test",
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
return &test.TestModule{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
130
internal/module/test/mqtt-client_test.go
Normal file
130
internal/module/test/mqtt-client_test.go
Normal file
@@ -0,0 +1,130 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestMQTTClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "mqtt.client",
|
||||
Params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create mqtt.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("mqtt.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "mqtt.client" {
|
||||
t.Fatalf("mqtt.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadMQTTClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no broker param",
|
||||
params: map[string]any{
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client broker error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string broker",
|
||||
params: map[string]any{
|
||||
"broker": 123,
|
||||
"topic": "test/topic",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client broker error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no topic param",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client topic error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string topic",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": 123,
|
||||
"clientId": "test",
|
||||
},
|
||||
errorString: "mqtt.client topic error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no clientId param",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
},
|
||||
errorString: "mqtt.client clientId error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string clientId",
|
||||
params: map[string]any{
|
||||
"broker": "mqtt://localhost:1883",
|
||||
"topic": "test/topic",
|
||||
"clientId": 123,
|
||||
},
|
||||
errorString: "mqtt.client clientId error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["mqtt.client"]
|
||||
if !ok {
|
||||
t.Fatalf("mqtt.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "mqtt.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("mqtt.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("mqtt.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("mqtt.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
108
internal/module/test/nats-client_test.go
Normal file
108
internal/module/test/nats-client_test.go
Normal file
@@ -0,0 +1,108 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestNATSClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.client",
|
||||
Params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
"subject": "test",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create nats.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("nats.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "nats.client" {
|
||||
t.Fatalf("nats.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadNATSClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no url param",
|
||||
params: map[string]any{
|
||||
"subject": "test/subject",
|
||||
},
|
||||
errorString: "nats.client url error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string url",
|
||||
params: map[string]any{
|
||||
"url": 123,
|
||||
"subject": "test/subject",
|
||||
},
|
||||
errorString: "nats.client url error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no subject param",
|
||||
params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
},
|
||||
errorString: "nats.client subject error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string subject",
|
||||
params: map[string]any{
|
||||
"url": "nats://127.0.0.1:4222",
|
||||
"subject": 123,
|
||||
},
|
||||
errorString: "nats.client subject error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["nats.client"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("nats.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("nats.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
85
internal/module/test/nats-server_test.go
Normal file
85
internal/module/test/nats-server_test.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestNATSServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["nats.server"]
|
||||
if !ok {
|
||||
t.Fatalf("nats.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "nats.server",
|
||||
Params: map[string]any{
|
||||
"ip": "127.0.0.1",
|
||||
"port": 4222,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create nats.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("nats.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "nats.server" {
|
||||
t.Fatalf("nats.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadNATSServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "non-string ip",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "nats.server ip error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("nats.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("nats.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("nats.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
73
internal/module/test/psn-client_test.go
Normal file
73
internal/module/test/psn-client_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestPSNClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "psn.client",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create psn.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("psn.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "psn.client" {
|
||||
t.Fatalf("psn.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadPSNClient(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["psn.client"]
|
||||
if !ok {
|
||||
t.Fatalf("psn.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "psn.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("psn.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("psn.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("psn.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
108
internal/module/test/redis-client_test.go
Normal file
108
internal/module/test/redis-client_test.go
Normal file
@@ -0,0 +1,108 @@
|
||||
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.ModuleRegistry["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.ModuleRegistry["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())
|
||||
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
117
internal/module/test/serial-client_test.go
Normal file
117
internal/module/test/serial-client_test.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSerialClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "serial.client",
|
||||
Params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": "LF",
|
||||
"baudRate": 9600,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create serial.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("serial.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "serial.client" {
|
||||
t.Fatalf("serial.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSerialClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "serial.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string port param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "serial.client port error: not a string",
|
||||
},
|
||||
{
|
||||
name: "no framing param",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
},
|
||||
errorString: "serial.client framing error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string framing param",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": 1,
|
||||
},
|
||||
errorString: "serial.client framing error: not a string",
|
||||
},
|
||||
{
|
||||
name: "unkown framing method",
|
||||
params: map[string]any{
|
||||
"port": "/dev/ttyUSB0",
|
||||
"framing": "asdfasdfasdfasdflkj",
|
||||
},
|
||||
errorString: "serial.client unknown framing method: asdfasdfasdfasdflkj",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["serial.client"]
|
||||
if !ok {
|
||||
t.Fatalf("serial.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "serial.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("serial.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("serial.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("serial.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
102
internal/module/test/sip-call-server_test.go
Normal file
102
internal/module/test/sip-call-server_test.go
Normal file
@@ -0,0 +1,102 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSIPCallServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.call.server",
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create sip.call.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("sip.call.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "sip.call.server" {
|
||||
t.Fatalf("sip.call.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSIPCallServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "sip.call.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "sip.call.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string transport param",
|
||||
params: map[string]any{
|
||||
"transport": 123,
|
||||
},
|
||||
errorString: "sip.call.server transport error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string userAgent param",
|
||||
params: map[string]any{
|
||||
"userAgent": 123,
|
||||
},
|
||||
errorString: "sip.call.server userAgent error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["sip.call.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.call.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.call.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("sip.call.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.call.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("sip.call.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
121
internal/module/test/sip-dtmf-server_test.go
Normal file
121
internal/module/test/sip-dtmf-server_test.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestSIPDTMFServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.dtmf.server",
|
||||
Params: map[string]any{
|
||||
"separator": "#",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create sip.dtmf.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("sip.dtmf.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "sip.dtmf.server" {
|
||||
t.Fatalf("sip.dtmf.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadSIPDTMFServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no separator param",
|
||||
params: map[string]any{},
|
||||
errorString: "sip.dtmf.server separator error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string separator param",
|
||||
params: map[string]any{
|
||||
"separator": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server separator error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "sip.dtmf.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string transport param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"transport": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server transport error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-string userAgent param",
|
||||
params: map[string]any{
|
||||
"separator": "#",
|
||||
"userAgent": 123,
|
||||
},
|
||||
errorString: "sip.dtmf.server userAgent error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["sip.dtmf.server"]
|
||||
if !ok {
|
||||
t.Fatalf("sip.dtmf.server module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "sip.dtmf.server",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("sip.dtmf.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("sip.dtmf.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("sip.dtmf.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
109
internal/module/test/tcp-client_test.go
Normal file
109
internal/module/test/tcp-client_test.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTCPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.tcp.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.tcp.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.tcp.client" {
|
||||
t.Fatalf("net.tcp.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTCPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
},
|
||||
errorString: "net.tcp.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.tcp.client port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.client host error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.tcp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("net.tcp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.tcp.client",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.tcp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.tcp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
134
internal/module/test/tcp-server_test.go
Normal file
134
internal/module/test/tcp-server_test.go
Normal file
@@ -0,0 +1,134 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTCPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["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: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.tcp.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.tcp.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.tcp.server" {
|
||||
t.Fatalf("net.tcp.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTCPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "net.tcp.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "net.tcp.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string framing param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": 1,
|
||||
},
|
||||
errorString: "net.tcp.server framing error: not a string",
|
||||
},
|
||||
{
|
||||
name: "unkown framing method",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "asdfasdfasdfasdflkj",
|
||||
},
|
||||
errorString: "net.tcp.server unknown framing method: asdfasdfasdfasdflkj",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "net.tcp.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.tcp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.tcp.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.tcp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
89
internal/module/test/time-interval_test.go
Normal file
89
internal/module/test/time-interval_test.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeIntervalFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["time.interval"]
|
||||
if !ok {
|
||||
t.Fatalf("time.interval module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.interval",
|
||||
Params: map[string]any{
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create time.interval module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("time.interval module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "time.interval" {
|
||||
t.Fatalf("time.interval module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeInterval(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no duration param",
|
||||
params: map[string]any{},
|
||||
errorString: "time.interval duration error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number duration param",
|
||||
params: map[string]any{
|
||||
"duration": "8000",
|
||||
},
|
||||
errorString: "time.interval duration error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("time.interval got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.interval expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("time.interval got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
89
internal/module/test/time-timer_test.go
Normal file
89
internal/module/test/time-timer_test.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestTimeTimerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["time.timer"]
|
||||
if !ok {
|
||||
t.Fatalf("time.timer module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "time.timer",
|
||||
Params: map[string]any{
|
||||
"duration": 1000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create time.timer module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("time.timer module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "time.timer" {
|
||||
t.Fatalf("time.timer module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadTimeTimer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no duration param",
|
||||
params: map[string]any{},
|
||||
errorString: "time.timer duration error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number duration param",
|
||||
params: map[string]any{
|
||||
"duration": "8000",
|
||||
},
|
||||
errorString: "time.timer duration error: not a number",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("time.timer got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("time.timer expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("time.timer got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
109
internal/module/test/udp-client_test.go
Normal file
109
internal/module/test/udp-client_test.go
Normal file
@@ -0,0 +1,109 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPClientFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.udp.client"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.client module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.client",
|
||||
Params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": 8000,
|
||||
"framing": "LF",
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.udp.client module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.udp.client module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.client" {
|
||||
t.Fatalf("net.udp.client module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPClient(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
},
|
||||
errorString: "net.udp.client port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"host": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.client port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no host param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string host param",
|
||||
params: map[string]any{
|
||||
"host": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.client host error: not a string",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.client expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.client got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
116
internal/module/test/udp-multicast_test.go
Normal file
116
internal/module/test/udp-multicast_test.go
Normal file
@@ -0,0 +1,116 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPMulticastFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("udp.multicast module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.multicast",
|
||||
Params: map[string]any{
|
||||
"ip": "236.10.10.10",
|
||||
"port": 56565,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create net.udp.multicast module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("net.udp.multicast module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.multicast" {
|
||||
t.Fatalf("net.udp.multicast module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPMulticast(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{
|
||||
"ip": "localhost",
|
||||
},
|
||||
errorString: "net.udp.multicast port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"ip": "localhost",
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.multicast port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "no ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"ip": 123,
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "net.udp.multicast ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["net.udp.multicast"]
|
||||
if !ok {
|
||||
t.Fatalf("net.udp.multicast module not registered")
|
||||
}
|
||||
|
||||
moduleInstance, err := registration.New(config.ModuleConfig{
|
||||
Id: "test",
|
||||
Type: "net.udp.multicast",
|
||||
Params: test.params,
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.multicast got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.multicast expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.multicast got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
113
internal/module/test/udp-server_test.go
Normal file
113
internal/module/test/udp-server_test.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package module_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/module"
|
||||
)
|
||||
|
||||
func TestUDPServerFromRegistry(t *testing.T) {
|
||||
registration, ok := module.ModuleRegistry["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: map[string]any{
|
||||
"port": 8000,
|
||||
},
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
t.Fatalf("failed to create udp.server module: %s", err)
|
||||
}
|
||||
|
||||
if moduleInstance.Id() != "test" {
|
||||
t.Fatalf("udp.server module has wrong id: %s", moduleInstance.Id())
|
||||
}
|
||||
|
||||
if moduleInstance.Type() != "net.udp.server" {
|
||||
t.Fatalf("net.udp.server module has wrong type: %s", moduleInstance.Type())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadUDPServer(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
params map[string]any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "no port param",
|
||||
params: map[string]any{},
|
||||
errorString: "net.udp.server port error: not found",
|
||||
},
|
||||
{
|
||||
name: "non-number port param",
|
||||
params: map[string]any{
|
||||
"port": "8000",
|
||||
},
|
||||
errorString: "net.udp.server port error: not a number",
|
||||
},
|
||||
{
|
||||
name: "non-string ip param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"ip": 123,
|
||||
},
|
||||
errorString: "net.udp.server ip error: not a string",
|
||||
},
|
||||
{
|
||||
name: "non-number bufferSize param",
|
||||
params: map[string]any{
|
||||
"port": 8000,
|
||||
"bufferSize": "1024",
|
||||
},
|
||||
errorString: "net.udp.server bufferSize error: not a number",
|
||||
},
|
||||
{
|
||||
name: "invalid addr",
|
||||
params: map[string]any{
|
||||
"ip": "127.0.0.",
|
||||
"port": 8000,
|
||||
},
|
||||
errorString: "lookup 127.0.0.: no such host",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
|
||||
registration, ok := module.ModuleRegistry["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 {
|
||||
if test.errorString != err.Error() {
|
||||
t.Fatalf("net.udp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
err = moduleInstance.Start(t.Context())
|
||||
|
||||
if err == nil {
|
||||
t.Fatalf("net.udp.server expected to fail")
|
||||
}
|
||||
|
||||
if err.Error() != test.errorString {
|
||||
t.Fatalf("net.udp.server got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
93
internal/module/time-interval.go
Normal file
93
internal/module/time-interval.go
Normal file
@@ -0,0 +1,93 @@
|
||||
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"
|
||||
)
|
||||
|
||||
type TimeInterval struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router common.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",
|
||||
Type: "integer",
|
||||
Description: "Interval duration in milliseconds",
|
||||
},
|
||||
},
|
||||
Required: []string{"duration"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationInt, err := params.GetInt("duration")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("time.interval duration error: %w", err)
|
||||
}
|
||||
return &TimeInterval{Duration: uint32(durationInt), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Id() string {
|
||||
return i.config.Id
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Type() string {
|
||||
return i.config.Type
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Start(ctx context.Context) error {
|
||||
i.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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 {
|
||||
select {
|
||||
case <-i.ctx.Done():
|
||||
i.logger.Debug("done")
|
||||
return nil
|
||||
case <-ticker.C:
|
||||
if i.router != nil {
|
||||
i.router.HandleInput(i.ctx, i.Id(), time.Now())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (i *TimeInterval) Stop() {
|
||||
i.cancel()
|
||||
}
|
||||
92
internal/module/time-timer.go
Normal file
92
internal/module/time-timer.go
Normal file
@@ -0,0 +1,92 @@
|
||||
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"
|
||||
)
|
||||
|
||||
type TimeTimer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router common.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",
|
||||
Type: "integer",
|
||||
Description: "Interval duration in milliseconds",
|
||||
},
|
||||
},
|
||||
Required: []string{"duration"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
|
||||
durationNum, err := params.GetInt("duration")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("time.timer duration error: %w", err)
|
||||
}
|
||||
|
||||
return &TimeTimer{Duration: uint32(durationNum), config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Id() string {
|
||||
return t.config.Id
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Type() string {
|
||||
return t.config.Type
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Start(ctx context.Context) error {
|
||||
t.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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))
|
||||
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.router != nil {
|
||||
t.router.HandleInput(t.ctx, t.Id(), time)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *TimeTimer) Stop() {
|
||||
t.cancel()
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
"github.com/jwetzell/showbridge-go/internal/route"
|
||||
)
|
||||
|
||||
type Timer struct {
|
||||
config config.ModuleConfig
|
||||
Duration uint32
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
timer *time.Timer
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "gen.timer",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
|
||||
duration, ok := params["duration"]
|
||||
if !ok {
|
||||
return nil, errors.New("gen.timer requires a duration parameter")
|
||||
}
|
||||
|
||||
durationNum, ok := duration.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("gen.timer duration must be a number")
|
||||
}
|
||||
|
||||
return &Timer{Duration: uint32(durationNum), config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (t *Timer) Id() string {
|
||||
return t.config.Id
|
||||
}
|
||||
|
||||
func (t *Timer) Type() string {
|
||||
return t.config.Type
|
||||
}
|
||||
|
||||
func (t *Timer) Run() error {
|
||||
t.timer = time.NewTimer(time.Millisecond * time.Duration(t.Duration))
|
||||
defer t.timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.ctx.Done():
|
||||
t.timer.Stop()
|
||||
t.logger.Debug("router context done in module")
|
||||
return nil
|
||||
case time := <-t.timer.C:
|
||||
if t.router != nil {
|
||||
t.router.HandleInput(t.Id(), time)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Timer) Output(payload any) error {
|
||||
t.timer.Reset(time.Millisecond * time.Duration(t.Duration))
|
||||
return nil
|
||||
}
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"log/slog"
|
||||
"net"
|
||||
|
||||
"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 UDPClient struct {
|
||||
@@ -17,44 +18,49 @@ type UDPClient struct {
|
||||
Port uint16
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.client",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
Title: "UDP Client",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"host": {
|
||||
Title: "Host",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"host", "port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ModuleConfig) (common.Module, error) {
|
||||
params := config.Params
|
||||
host, ok := params["host"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.client requires a host parameter")
|
||||
hostString, err := params.GetString("host")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client host error: %w", err)
|
||||
}
|
||||
|
||||
hostString, ok := host.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.client host must be a string")
|
||||
}
|
||||
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.client requires a port parameter")
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.client port must be a number")
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.client port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", hostString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &UDPClient{Addr: addr, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &UDPClient{Addr: addr, config: config, logger: CreateLogger(config)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -73,7 +79,17 @@ func (uc *UDPClient) SetupConn() error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Run() error {
|
||||
func (uc *UDPClient) Start(ctx context.Context) error {
|
||||
uc.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
err := uc.SetupConn()
|
||||
if err != nil {
|
||||
@@ -81,16 +97,16 @@ func (uc *UDPClient) Run() error {
|
||||
}
|
||||
|
||||
<-uc.ctx.Done()
|
||||
uc.logger.Debug("router context done in module")
|
||||
uc.logger.Debug("done")
|
||||
if uc.conn != nil {
|
||||
uc.conn.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Output(payload any) error {
|
||||
func (uc *UDPClient) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.client is only able to output bytes")
|
||||
}
|
||||
@@ -105,3 +121,7 @@ func (uc *UDPClient) Output(payload any) error {
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (uc *UDPClient) Stop() {
|
||||
uc.cancel()
|
||||
}
|
||||
|
||||
@@ -8,52 +8,59 @@ import (
|
||||
"net"
|
||||
"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 UDPMulticast struct {
|
||||
config config.ModuleConfig
|
||||
conn *net.UDPConn
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
Addr *net.UDPAddr
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.multicast",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
ip, ok := params["ip"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.multicast requires an ip parameter")
|
||||
Title: "UDP Multicast",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Type: "string",
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
},
|
||||
Required: []string{"ip", "port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.multicast ip error: %w", err)
|
||||
}
|
||||
|
||||
ipString, ok := ip.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.multicast ip must be a string")
|
||||
}
|
||||
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.multicast requires a port parameter")
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.multicast port must be a number")
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.multicast port error: %w", err)
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UDPMulticast{config: config, Addr: addr, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &UDPMulticast{config: moduleConfig, Addr: addr, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -66,7 +73,17 @@ func (um *UDPMulticast) Type() string {
|
||||
return um.config.Type
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Run() error {
|
||||
func (um *UDPMulticast) Start(ctx context.Context) error {
|
||||
um.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
client, err := net.ListenMulticastUDP("udp", nil, um.Addr)
|
||||
if err != nil {
|
||||
@@ -81,7 +98,7 @@ func (um *UDPMulticast) Run() error {
|
||||
select {
|
||||
case <-um.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
um.logger.Debug("router context done in module")
|
||||
um.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
um.conn.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
@@ -99,18 +116,18 @@ func (um *UDPMulticast) Run() error {
|
||||
message := buffer[:numBytes]
|
||||
|
||||
if um.router != nil {
|
||||
um.router.HandleInput(um.Id(), message)
|
||||
um.router.HandleInput(um.ctx, um.Id(), message)
|
||||
} else {
|
||||
um.logger.Error("net.udp.multicast has no router")
|
||||
um.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Output(payload any) error {
|
||||
func (um *UDPMulticast) Output(ctx context.Context, payload any) error {
|
||||
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
if !ok {
|
||||
return errors.New("net.udp.multicast can only output bytes")
|
||||
}
|
||||
@@ -122,3 +139,7 @@ func (um *UDPMulticast) Output(payload any) error {
|
||||
_, err := um.conn.Write(payloadBytes)
|
||||
return err
|
||||
}
|
||||
|
||||
func (um *UDPMulticast) Stop() {
|
||||
um.cancel()
|
||||
}
|
||||
|
||||
@@ -2,15 +2,16 @@ package module
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net"
|
||||
"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 {
|
||||
@@ -18,57 +19,70 @@ type UDPServer struct {
|
||||
BufferSize int
|
||||
config config.ModuleConfig
|
||||
ctx context.Context
|
||||
router route.RouteIO
|
||||
router common.RouteIO
|
||||
logger *slog.Logger
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterModule(ModuleRegistration{
|
||||
Type: "net.udp.server",
|
||||
New: func(ctx context.Context, config config.ModuleConfig, router route.RouteIO) (Module, error) {
|
||||
params := config.Params
|
||||
port, ok := params["port"]
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.server requires a port parameter")
|
||||
Title: "UDP Server",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"ip": {
|
||||
Title: "IP",
|
||||
Type: "string",
|
||||
Default: json.RawMessage(`"0.0.0.0"`),
|
||||
},
|
||||
"port": {
|
||||
Title: "Port",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1024),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
},
|
||||
"bufferSize": {
|
||||
Title: "Buffer Size",
|
||||
Type: "integer",
|
||||
Minimum: jsonschema.Ptr[float64](1),
|
||||
Maximum: jsonschema.Ptr[float64](65535),
|
||||
Default: json.RawMessage("2048"),
|
||||
},
|
||||
},
|
||||
Required: []string{"port"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ModuleConfig) (common.Module, error) {
|
||||
params := moduleConfig.Params
|
||||
portNum, err := params.GetInt("port")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("net.udp.server port error: %w", err)
|
||||
}
|
||||
|
||||
portNum, ok := port.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.server port must be a number")
|
||||
ipString, err := params.GetString("ip")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
ipString = "0.0.0.0"
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.udp.server ip error: %w", err)
|
||||
}
|
||||
|
||||
ipString := "0.0.0.0"
|
||||
|
||||
ip, ok := params["ip"]
|
||||
if ok {
|
||||
|
||||
specificIpString, ok := ip.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.server ip must be a string")
|
||||
}
|
||||
ipString = specificIpString
|
||||
}
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", ipString, uint16(portNum)))
|
||||
if err != nil {
|
||||
log.Fatalf("error resolving UDP address: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
bufferSizeNum := 2048
|
||||
bufferSize, ok := params["bufferSize"]
|
||||
|
||||
if ok {
|
||||
bufferSizeFloat, ok := bufferSize.(float64)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("net.udp.server bufferSize must be a number")
|
||||
bufferSizeNum, err := params.GetInt("bufferSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bufferSizeNum = 2048
|
||||
} else {
|
||||
return nil, fmt.Errorf("net.udp.server bufferSize error: %w", err)
|
||||
}
|
||||
bufferSizeNum = int(bufferSizeFloat)
|
||||
}
|
||||
|
||||
return &UDPServer{Addr: addr, BufferSize: bufferSizeNum, config: config, ctx: ctx, router: router, logger: slog.Default().With("component", "module", "id", config.Id)}, nil
|
||||
return &UDPServer{Addr: addr, BufferSize: bufferSizeNum, config: moduleConfig, logger: CreateLogger(moduleConfig)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -78,10 +92,20 @@ func (us *UDPServer) Id() string {
|
||||
}
|
||||
|
||||
func (us *UDPServer) Type() string {
|
||||
return us.config.Id
|
||||
return us.config.Type
|
||||
}
|
||||
|
||||
func (us *UDPServer) Run() error {
|
||||
func (us *UDPServer) Start(ctx context.Context) error {
|
||||
us.logger.Debug("running")
|
||||
router, ok := ctx.Value(common.RouterContextKey).(common.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
|
||||
|
||||
listener, err := net.ListenUDP("udp", us.Addr)
|
||||
if err != nil {
|
||||
@@ -95,12 +119,12 @@ func (us *UDPServer) Run() error {
|
||||
select {
|
||||
case <-us.ctx.Done():
|
||||
// TODO(jwetzell): cleanup?
|
||||
us.logger.Debug("router context done in module")
|
||||
us.logger.Debug("done")
|
||||
return nil
|
||||
default:
|
||||
listener.SetDeadline(time.Now().Add(time.Millisecond * 200))
|
||||
|
||||
numBytes, _, err := listener.ReadFromUDP(buffer)
|
||||
numBytes, senderAddr, err := listener.ReadFromUDP(buffer)
|
||||
if err != nil {
|
||||
//NOTE(jwetzell) we hit deadline
|
||||
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
|
||||
@@ -110,15 +134,20 @@ func (us *UDPServer) Run() error {
|
||||
}
|
||||
message := buffer[:numBytes]
|
||||
if us.router != nil {
|
||||
us.router.HandleInput(us.Id(), message)
|
||||
senderCtx := context.WithValue(us.ctx, common.SenderContextKey, senderAddr)
|
||||
us.router.HandleInput(senderCtx, us.Id(), message)
|
||||
} else {
|
||||
us.logger.Error("net.udp.server has no router")
|
||||
us.logger.Error("input received but no router is configured")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (us *UDPServer) Output(payload any) error {
|
||||
func (us *UDPServer) Output(ctx context.Context, payload any) error {
|
||||
return errors.New("net.udp.server output is not implemented")
|
||||
}
|
||||
|
||||
func (us *UDPServer) Stop() {
|
||||
us.cancel()
|
||||
}
|
||||
|
||||
49
internal/processor/artnet-packet-decode.go
Normal file
49
internal/processor/artnet-packet-decode.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("artnet.packet.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := artnet.Decode(payloadBytes)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (apd *ArtNetPacketDecode) Type() string {
|
||||
return apd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.decode",
|
||||
Title: "Decode ArtNet Packet",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketDecode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
48
internal/processor/artnet-packet-encode.go
Normal file
48
internal/processor/artnet-packet-encode.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jwetzell/artnet-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
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)
|
||||
|
||||
if !ok {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("artnet.packet.encode processor only accepts an ArtNetPacket")
|
||||
}
|
||||
|
||||
payloadBytes, err := payloadPacket.MarshalBinary()
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
wrappedPayload.Payload = payloadBytes
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (ape *ArtNetPacketEncode) Type() string {
|
||||
return ape.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "artnet.packet.encode",
|
||||
Title: "Encode ArtNet Packet",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &ArtNetPacketEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
131
internal/processor/db-query.go
Normal file
131
internal/processor/db-query.go
Normal file
@@ -0,0 +1,131 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"text/template"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type DbQuery struct {
|
||||
config config.ProcessorConfig
|
||||
ModuleId string
|
||||
Query *template.Template
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (dq *DbQuery) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
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)
|
||||
}
|
||||
|
||||
db := dbModule.Database()
|
||||
if db == nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, fmt.Errorf("db.query module with id %s returned nil database", dq.ModuleId)
|
||||
}
|
||||
|
||||
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 := db.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)
|
||||
}
|
||||
|
||||
results := make([]map[string]any, 0)
|
||||
|
||||
for rows.Next() {
|
||||
columnValues := make([]interface{}, len(columns))
|
||||
|
||||
for i := range columnValues {
|
||||
columnValues[i] = new(interface{})
|
||||
}
|
||||
|
||||
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].(*interface{})
|
||||
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
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "db.query",
|
||||
Title: "Query Database",
|
||||
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
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -13,9 +14,12 @@ type DebugLog struct {
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Process(ctx context.Context, payload any) (any, error) {
|
||||
dl.logger.Debug("debug.log", "payload", payload, "payloadType", fmt.Sprintf("%T", payload))
|
||||
return payload, nil
|
||||
func (dl *DebugLog) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadString := fmt.Sprintf("%+v", payload)
|
||||
payloadType := fmt.Sprintf("%T", payload)
|
||||
dl.logger.Debug("", "payload", payloadString, "payloadType", payloadType)
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (dl *DebugLog) Type() string {
|
||||
@@ -25,8 +29,9 @@ func (dl *DebugLog) Type() string {
|
||||
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")}, nil
|
||||
return &DebugLog{config: config, logger: slog.Default().With("component", "processor", "type", config.Type)}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
40
internal/processor/filter-change.go
Normal file
40
internal/processor/filter-change.go
Normal file
@@ -0,0 +1,40 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"reflect"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.change",
|
||||
Title: "Filter On Change",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FilterChange{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
80
internal/processor/filter-expr.go
Normal file
80
internal/processor/filter-expr.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"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 (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
|
||||
}
|
||||
|
||||
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",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"expression"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
expressionString, err := params.GetString("expression")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("filter.expr expression error: %w", err)
|
||||
}
|
||||
|
||||
program, err := expr.Compile(expressionString)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &FilterExpr{config: config, Program: program}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
73
internal/processor/filter-regex.go
Normal file
73
internal/processor/filter-regex.go
Normal file
@@ -0,0 +1,73 @@
|
||||
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"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "filter.regex",
|
||||
Title: "Filter by Regex",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"pattern": {
|
||||
Title: "Pattern",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"pattern"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
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
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -2,9 +2,13 @@ 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"
|
||||
)
|
||||
|
||||
@@ -13,18 +17,22 @@ type FloatParse struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadString, ok := payload.(string)
|
||||
func (fp *FloatParse) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadString, ok := common.GetAnyAs[string](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse processor only accepts a string")
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("float.parse processor only accepts a string")
|
||||
}
|
||||
|
||||
payloadFloat, err := strconv.ParseFloat(payloadString, fp.BitSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
return payloadFloat, nil
|
||||
wrappedPayload.Payload = payloadFloat
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fp *FloatParse) Type() string {
|
||||
@@ -34,20 +42,31 @@ func (fp *FloatParse) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.parse",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
bitSizeNum := 64
|
||||
bitSize, ok := params["bitSize"]
|
||||
if ok {
|
||||
bitSizeFloat, ok := bitSize.(float64)
|
||||
Title: "Parse Float",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"bitSize": {
|
||||
Title: "Bit Size",
|
||||
Type: "integer",
|
||||
Enum: []any{32, 64},
|
||||
Default: json.RawMessage("64"),
|
||||
},
|
||||
},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(moduleConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := moduleConfig.Params
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("float.parse bitSize must be a number")
|
||||
bitSizeNum, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeNum = 64
|
||||
} else {
|
||||
return nil, fmt.Errorf("float.parse bitSize error: %w", err)
|
||||
}
|
||||
|
||||
bitSizeNum = int(bitSizeFloat)
|
||||
}
|
||||
return &FloatParse{config: config, BitSize: bitSizeNum}, nil
|
||||
return &FloatParse{config: moduleConfig, BitSize: bitSizeNum}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
package processor_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/processor"
|
||||
)
|
||||
|
||||
func TestGoodFloatParse(t *testing.T) {
|
||||
floatParser := processor.FloatParse{}
|
||||
tests := []struct {
|
||||
processor processor.Processor
|
||||
name string
|
||||
payload any
|
||||
expected float64
|
||||
}{
|
||||
{
|
||||
name: "positive number",
|
||||
payload: "12345.67",
|
||||
expected: 12345.67,
|
||||
},
|
||||
{
|
||||
name: "negative number",
|
||||
payload: "-12345.67",
|
||||
expected: -12345.67,
|
||||
},
|
||||
{
|
||||
name: "zero",
|
||||
payload: "0",
|
||||
expected: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := floatParser.Process(t.Context(), test.payload)
|
||||
|
||||
gotFloat, ok := got.(float64)
|
||||
if !ok {
|
||||
t.Errorf("float.parse returned a %T payload: %s", got, got)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("float.parse failed: %s", err)
|
||||
}
|
||||
if gotFloat != test.expected {
|
||||
t.Errorf("float.parse got %f, expected %f", gotFloat, test.expected)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBadFloatParse(t *testing.T) {
|
||||
floatParser := processor.FloatParse{}
|
||||
tests := []struct {
|
||||
processor processor.Processor
|
||||
name string
|
||||
payload any
|
||||
errorString string
|
||||
}{
|
||||
{
|
||||
name: "non-string input",
|
||||
payload: []byte{0x01},
|
||||
errorString: "float.parse processor only accepts a string",
|
||||
},
|
||||
{
|
||||
name: "not float string",
|
||||
payload: "abcd",
|
||||
errorString: "strconv.ParseFloat: parsing \"abcd\": invalid syntax",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := floatParser.Process(t.Context(), test.payload)
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("float.parse expected to fail but succeeded, got: %v", got)
|
||||
|
||||
}
|
||||
if err.Error() != test.errorString {
|
||||
t.Errorf("float.parse got error '%s', expected '%s'", err.Error(), test.errorString)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
99
internal/processor/float-random.go
Normal file
99
internal/processor/float-random.go
Normal file
@@ -0,0 +1,99 @@
|
||||
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, 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
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "float.random",
|
||||
Title: "Random Float",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"bitSize": {
|
||||
Title: "Bit Size",
|
||||
Type: "integer",
|
||||
Enum: []any{32, 64},
|
||||
Default: json.RawMessage("32"),
|
||||
},
|
||||
"min": {
|
||||
Title: "Minimum",
|
||||
Type: "number",
|
||||
},
|
||||
"max": {
|
||||
Title: "Maximum",
|
||||
Type: "number",
|
||||
},
|
||||
},
|
||||
Required: []string{"min", "max"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(processorConfig config.ProcessorConfig) (Processor, error) {
|
||||
params := processorConfig.Params
|
||||
|
||||
bitSizeInt, err := params.GetInt("bitSize")
|
||||
if err != nil {
|
||||
if errors.Is(err, config.ErrParamNotFound) {
|
||||
bitSizeInt = 32
|
||||
} else {
|
||||
return nil, fmt.Errorf("float.random bitSize error: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if bitSizeInt != 32 && bitSizeInt != 64 {
|
||||
return nil, errors.New("float.random bitSize error: must be 32 or 64")
|
||||
}
|
||||
|
||||
minFloat, err := params.GetFloat64("min")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random min error: %w", err)
|
||||
}
|
||||
|
||||
maxFloat, err := params.GetFloat64("max")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("float.random max error: %w", err)
|
||||
}
|
||||
|
||||
if maxFloat < minFloat {
|
||||
return nil, errors.New("float.random max must be greater than min")
|
||||
}
|
||||
|
||||
return &FloatRandom{config: processorConfig, Min: minFloat, Max: maxFloat, BitSize: bitSizeInt}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -3,11 +3,13 @@ package processor
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -24,13 +26,16 @@ type FreeDCreate struct {
|
||||
Focus *template.Template
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
func (fc *FreeDCreate) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
|
||||
templateData := wrappedPayload
|
||||
|
||||
var idBuffer bytes.Buffer
|
||||
err := fc.Id.Execute(&idBuffer, payload)
|
||||
err := fc.Id.Execute(&idBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
idString := idBuffer.String()
|
||||
@@ -38,14 +43,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
idNum, err := strconv.ParseUint(idString, 10, 8)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var panBuffer bytes.Buffer
|
||||
err = fc.Pan.Execute(&panBuffer, payload)
|
||||
err = fc.Pan.Execute(&panBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
panString := panBuffer.String()
|
||||
@@ -53,14 +60,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
panNum, err := strconv.ParseFloat(panString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var tiltBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&tiltBuffer, payload)
|
||||
err = fc.Tilt.Execute(&tiltBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
tiltString := tiltBuffer.String()
|
||||
@@ -68,14 +77,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
tiltNum, err := strconv.ParseFloat(tiltString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var rollBuffer bytes.Buffer
|
||||
err = fc.Tilt.Execute(&rollBuffer, payload)
|
||||
err = fc.Roll.Execute(&rollBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
rollString := rollBuffer.String()
|
||||
@@ -83,14 +94,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
rollNum, err := strconv.ParseFloat(rollString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posXBuffer bytes.Buffer
|
||||
err = fc.PosX.Execute(&posXBuffer, payload)
|
||||
err = fc.PosX.Execute(&posXBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posXString := posXBuffer.String()
|
||||
@@ -98,14 +111,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
posXNum, err := strconv.ParseFloat(posXString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posYBuffer bytes.Buffer
|
||||
err = fc.PosY.Execute(&posYBuffer, payload)
|
||||
err = fc.PosY.Execute(&posYBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posYString := posYBuffer.String()
|
||||
@@ -113,14 +128,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
posYNum, err := strconv.ParseFloat(posYString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var posZBuffer bytes.Buffer
|
||||
err = fc.PosZ.Execute(&posZBuffer, payload)
|
||||
err = fc.PosZ.Execute(&posZBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
posZString := posZBuffer.String()
|
||||
@@ -128,14 +145,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
posZNum, err := strconv.ParseFloat(posZString, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var zoomBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&zoomBuffer, payload)
|
||||
err = fc.Zoom.Execute(&zoomBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
zoomString := zoomBuffer.String()
|
||||
@@ -143,14 +162,16 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
zoomNum, err := strconv.ParseInt(zoomString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
var focusBuffer bytes.Buffer
|
||||
err = fc.Zoom.Execute(&focusBuffer, payload)
|
||||
err = fc.Focus.Execute(&focusBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
focusString := focusBuffer.String()
|
||||
@@ -158,7 +179,8 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
focusNum, err := strconv.ParseInt(focusString, 10, 32)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
payloadMessage := freeD.FreeDPosition{
|
||||
@@ -173,7 +195,9 @@ func (fc *FreeDCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
Focus: int32(focusNum),
|
||||
}
|
||||
|
||||
return payloadMessage, nil
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fc *FreeDCreate) Type() string {
|
||||
@@ -183,20 +207,67 @@ func (fc *FreeDCreate) Type() string {
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.create",
|
||||
Title: "Create FreeD",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"id": {
|
||||
Title: "Camera ID",
|
||||
Type: "string",
|
||||
},
|
||||
"pan": {
|
||||
Title: "Pan",
|
||||
Type: "string",
|
||||
},
|
||||
"tilt": {
|
||||
Title: "Tilt",
|
||||
Type: "string",
|
||||
},
|
||||
"roll": {
|
||||
Title: "Roll",
|
||||
Type: "string",
|
||||
},
|
||||
"posX": {
|
||||
Title: "Position X",
|
||||
Type: "string",
|
||||
},
|
||||
"posY": {
|
||||
Title: "Position Y",
|
||||
Type: "string",
|
||||
},
|
||||
"posZ": {
|
||||
Title: "Position Z",
|
||||
Type: "string",
|
||||
},
|
||||
"zoom": {
|
||||
Title: "Zoom",
|
||||
Type: "string",
|
||||
},
|
||||
"focus": {
|
||||
Title: "Focus",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{
|
||||
"id",
|
||||
"pan",
|
||||
"tilt",
|
||||
"roll",
|
||||
"posX",
|
||||
"posY",
|
||||
"posZ",
|
||||
"zoom",
|
||||
"focus",
|
||||
},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
|
||||
// TODO(jwetzell): make some params optional
|
||||
params := config.Params
|
||||
id, ok := params["id"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires an id parameter")
|
||||
}
|
||||
|
||||
idString, ok := id.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create id must be a string")
|
||||
idString, err := params.GetString("id")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create id error: %w", err)
|
||||
}
|
||||
|
||||
idTemplate, err := template.New("id").Parse(idString)
|
||||
@@ -205,44 +276,31 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
pan, ok := params["pan"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a pan parameter")
|
||||
}
|
||||
|
||||
panString, ok := pan.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create pan must be a string")
|
||||
panString, err := params.GetString("pan")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create pan error: %w", err)
|
||||
}
|
||||
|
||||
panTemplate, err := template.New("pan").Parse(panString)
|
||||
|
||||
tilt, ok := params["tilt"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a tilt parameter")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tiltString, ok := tilt.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create tilt must be a string")
|
||||
tiltString, err := params.GetString("tilt")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create tilt error: %w", err)
|
||||
}
|
||||
|
||||
tiltTemplate, err := template.New("tilt").Parse(tiltString)
|
||||
|
||||
roll, ok := params["roll"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a roll parameter")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rollString, ok := roll.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create roll must be a string")
|
||||
rollString, err := params.GetString("roll")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create roll error: %w", err)
|
||||
}
|
||||
|
||||
rollTemplate, err := template.New("roll").Parse(rollString)
|
||||
@@ -251,16 +309,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posX, ok := params["posX"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a posX parameter")
|
||||
}
|
||||
|
||||
posXString, ok := posX.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create posX must be a string")
|
||||
posXString, err := params.GetString("posX")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posX error: %w", err)
|
||||
}
|
||||
|
||||
posXTemplate, err := template.New("posX").Parse(posXString)
|
||||
@@ -269,16 +320,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posY, ok := params["posY"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a posY parameter")
|
||||
}
|
||||
|
||||
posYString, ok := posY.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create posY must be a string")
|
||||
posYString, err := params.GetString("posY")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posY error: %w", err)
|
||||
}
|
||||
|
||||
posYTemplate, err := template.New("posY").Parse(posYString)
|
||||
@@ -287,16 +331,9 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
posZ, ok := params["posZ"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a posZ parameter")
|
||||
}
|
||||
|
||||
posZString, ok := posZ.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create posZ must be a string")
|
||||
posZString, err := params.GetString("posZ")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create posZ error: %w", err)
|
||||
}
|
||||
|
||||
posZTemplate, err := template.New("posZ").Parse(posZString)
|
||||
@@ -305,33 +342,26 @@ func init() {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
zoom, ok := params["zoom"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a zoom parameter")
|
||||
}
|
||||
|
||||
zoomString, ok := zoom.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create zoom must be a string")
|
||||
zoomString, err := params.GetString("zoom")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("freed.create zoom error: %w", err)
|
||||
}
|
||||
|
||||
zoomTemplate, err := template.New("zoom").Parse(zoomString)
|
||||
|
||||
focus, ok := params["focus"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create requires a focus parameter")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
focusString, ok := focus.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.create focus must be a string")
|
||||
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,
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,27 +13,32 @@ type FreeDDecode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadBytes, ok := payload.([]byte)
|
||||
func (fd *FreeDDecode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadBytes, ok := common.GetAnyAsByteSlice(payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a []byte")
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("freed.decode processor only accepts a []byte")
|
||||
}
|
||||
|
||||
payloadMessage, err := freeD.Decode(payloadBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
return payloadMessage, nil
|
||||
wrappedPayload.Payload = payloadMessage
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fdd *FreeDDecode) Type() string {
|
||||
return fdd.config.Type
|
||||
func (fd *FreeDDecode) Type() string {
|
||||
return fd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.decode",
|
||||
Title: "Decode FreeD",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FreeDDecode{config: config}, nil
|
||||
},
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
|
||||
freeD "github.com/jwetzell/free-d-go"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
@@ -12,24 +13,29 @@ type FreeDEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadPosition, ok := payload.(freeD.FreeDPosition)
|
||||
func (fe *FreeDEncode) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
payload := wrappedPayload.Payload
|
||||
payloadPosition, ok := common.GetAnyAs[freeD.FreeDPosition](payload)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("freed.decode processor only accepts a FreeDEncode")
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, errors.New("freed.encode processor only accepts a FreeDPosition")
|
||||
}
|
||||
|
||||
payloadBytes := freeD.Encode(payloadPosition)
|
||||
return payloadBytes, nil
|
||||
|
||||
wrappedPayload.Payload = payloadBytes
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (fde *FreeDEncode) Type() string {
|
||||
return fde.config.Type
|
||||
func (fe *FreeDEncode) Type() string {
|
||||
return fe.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "freed.encode",
|
||||
Title: "Encode FreeD",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &FreeDEncode{config: config}, nil
|
||||
},
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"text/template"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestCreate struct {
|
||||
config config.ProcessorConfig
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hrc *HTTPRequestCreate) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hrc.URL.Execute(&urlBuffer, payload)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hrc.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func (hrc *HTTPRequestCreate) Type() string {
|
||||
return hrc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.create",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
method, ok := params["method"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.create requires a method parameter")
|
||||
}
|
||||
|
||||
methodString, ok := method.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.create url must be a string")
|
||||
}
|
||||
|
||||
url, ok := params["url"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.create requires a url parameter")
|
||||
}
|
||||
|
||||
urlString, ok := url.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.create url must be a string")
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &HTTPRequestCreate{config: config, URL: urlTemplate, Method: methodString}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
117
internal/processor/http-request-do.go
Normal file
117
internal/processor/http-request-do.go
Normal file
@@ -0,0 +1,117 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestDo struct {
|
||||
config config.ProcessorConfig
|
||||
client *http.Client
|
||||
Method string
|
||||
URL *template.Template
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
|
||||
templateData := wrappedPayload
|
||||
|
||||
var urlBuffer bytes.Buffer
|
||||
err := hrd.URL.Execute(&urlBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
urlString := urlBuffer.String()
|
||||
|
||||
//TODO(jwetzell): support body
|
||||
request, err := http.NewRequest(hrd.Method, urlString, bytes.NewBuffer([]byte{}))
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
response, err := hrd.client.Do(request)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(response.Body)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
|
||||
//TODO(jwetzell): support headers, etc
|
||||
wrappedPayload.Payload = HTTPResponse{
|
||||
Status: response.StatusCode,
|
||||
Body: body,
|
||||
}
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (hrd *HTTPRequestDo) Type() string {
|
||||
return hrd.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.do",
|
||||
Title: "Do HTTP Request",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"method": {
|
||||
Title: "HTTP Method",
|
||||
Type: "string",
|
||||
Enum: []any{"GET", "POST", "PUT", "PATCH", "DELETE"},
|
||||
},
|
||||
"url": {
|
||||
Title: "URL",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"method", "url"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
methodString, err := params.GetString("method")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do method error: %w", err)
|
||||
}
|
||||
|
||||
urlString, err := params.GetString("url")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.request.do url error: %w", err)
|
||||
}
|
||||
|
||||
urlTemplate, err := template.New("url").Parse(urlString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
return &HTTPRequestDo{config: config, URL: urlTemplate, Method: methodString, client: client}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestEncode struct {
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Process(ctx context.Context, payload any) (any, error) {
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.encode processor only accepts an http.Request")
|
||||
}
|
||||
|
||||
bytes, err := io.ReadAll(payloadRequest.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes, nil
|
||||
}
|
||||
|
||||
func (hre *HTTPRequestEncode) Type() string {
|
||||
return hre.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.encode",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
return &HTTPRequestEncode{config: config}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"regexp"
|
||||
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPRequestFilter struct {
|
||||
config config.ProcessorConfig
|
||||
Path *regexp.Regexp
|
||||
Method string
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Process(ctx context.Context, payload any) (any, error) {
|
||||
|
||||
payloadRequest, ok := payload.(*http.Request)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.filter can only operate on http.Request payloads")
|
||||
}
|
||||
|
||||
if hrf.Method != "" {
|
||||
if payloadRequest.Method != hrf.Method {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
if !hrf.Path.MatchString(payloadRequest.URL.Path) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return payloadRequest, nil
|
||||
}
|
||||
|
||||
func (hrf *HTTPRequestFilter) Type() string {
|
||||
return hrf.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.request.filter",
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
path, ok := params["path"]
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.filter requires a path parameter")
|
||||
}
|
||||
|
||||
pathString, ok := path.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.filter path must be a string")
|
||||
}
|
||||
|
||||
pathRegexp, err := regexp.Compile(fmt.Sprintf("^%s$", pathString))
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
method, ok := params["method"]
|
||||
|
||||
if ok {
|
||||
methodString, ok := method.(string)
|
||||
|
||||
if !ok {
|
||||
return nil, errors.New("http.request.filter method must be a string")
|
||||
}
|
||||
return &HTTPRequestFilter{config: config, Path: pathRegexp, Method: methodString}, nil
|
||||
}
|
||||
|
||||
return &HTTPRequestFilter{config: config, Path: pathRegexp}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
88
internal/processor/http-response-create.go
Normal file
88
internal/processor/http-response-create.go
Normal file
@@ -0,0 +1,88 @@
|
||||
package processor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"text/template"
|
||||
|
||||
"github.com/google/jsonschema-go/jsonschema"
|
||||
"github.com/jwetzell/showbridge-go/internal/common"
|
||||
"github.com/jwetzell/showbridge-go/internal/config"
|
||||
)
|
||||
|
||||
type HTTPResponseCreate struct {
|
||||
Status int
|
||||
BodyTmpl *template.Template
|
||||
config config.ProcessorConfig
|
||||
}
|
||||
|
||||
type HTTPResponse struct {
|
||||
Status int
|
||||
Body []byte
|
||||
}
|
||||
|
||||
func (hrc *HTTPResponseCreate) Process(ctx context.Context, wrappedPayload common.WrappedPayload) (common.WrappedPayload, error) {
|
||||
templateData := wrappedPayload
|
||||
|
||||
var bodyBuffer bytes.Buffer
|
||||
err := hrc.BodyTmpl.Execute(&bodyBuffer, templateData)
|
||||
|
||||
if err != nil {
|
||||
wrappedPayload.End = true
|
||||
return wrappedPayload, err
|
||||
}
|
||||
wrappedPayload.Payload = HTTPResponse{
|
||||
Status: hrc.Status,
|
||||
Body: bodyBuffer.Bytes(),
|
||||
}
|
||||
return wrappedPayload, nil
|
||||
}
|
||||
|
||||
func (hrc *HTTPResponseCreate) Type() string {
|
||||
return hrc.config.Type
|
||||
}
|
||||
|
||||
func init() {
|
||||
RegisterProcessor(ProcessorRegistration{
|
||||
Type: "http.response.create",
|
||||
Title: "Create HTTP Response",
|
||||
ParamsSchema: &jsonschema.Schema{
|
||||
Type: "object",
|
||||
Properties: map[string]*jsonschema.Schema{
|
||||
"status": {
|
||||
Title: "Status Code",
|
||||
Type: "integer",
|
||||
},
|
||||
"body": {
|
||||
Title: "Body",
|
||||
Type: "string",
|
||||
},
|
||||
},
|
||||
Required: []string{"status", "body"},
|
||||
AdditionalProperties: nil,
|
||||
},
|
||||
New: func(config config.ProcessorConfig) (Processor, error) {
|
||||
params := config.Params
|
||||
|
||||
statusNum, err := params.GetInt("status")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.response.create status error: %w", err)
|
||||
}
|
||||
|
||||
bodyTemplateString, err := params.GetString("bodyTemplate")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("http.response.create bodyTemplate error: %w", err)
|
||||
}
|
||||
|
||||
bodyTemplate, err := template.New("body").Parse(bodyTemplateString)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// TODO(jwetzell): support other body kind (direct bytes from input, from file?)
|
||||
return &HTTPResponseCreate{config: config, Status: int(statusNum), BodyTmpl: bodyTemplate}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user