17 Commits

Author SHA1 Message Date
Adrian Zuercher
b21101958d add write ping before pinghandler starts 2025-07-27 09:05:53 +02:00
Adrian Zuercher
c3a3060129 improve websocket ping and remodel for rename datapoint 2025-07-25 18:26:36 +02:00
Adrian Zuercher
a23f82e9fe Merge branch 'main' of https://github.com/tecamino/tecamino-dbm
This is a neccesary pull merge
2025-07-23 09:15:01 +02:00
Adrian Zuercher
c37dd87a37 new respond to send all create change delete different bug fixes 2025-07-23 09:10:56 +02:00
Adrian Zuercher
8be5c80a22 add broadcast to all client and modify lingpong handler 2025-07-23 09:09:14 +02:00
zuadi
47a065aaf9 Update build.yml add flags to make smaller executable 2025-07-13 20:10:05 +02:00
Adrian Zuercher
5e1e4b9daf make new model for stringSlices allowOrigin helper 2025-07-13 20:01:13 +02:00
Adrian Zuercher
0f06128ce8 new send datapoint type and one fix typo 2025-07-11 17:47:12 +02:00
Adrian Zuercher
be07dc8749 add new argument for remote port 2025-07-11 17:46:32 +02:00
Adrian Zuercher
e75d7c8b03 add automatic localhost and local ip to allow origin 2025-06-29 21:18:15 +02:00
Adrian Zürcher
59c7705ca1 fix concurrent write new sendPong channel 2025-06-22 08:58:14 +02:00
Adrian Zürcher
91ea59ed6e improvement websocket according to gorilla example 2025-06-22 07:46:24 +02:00
Adrian Zürcher
659cbe4072 modify websocketserver to broker with callback functions 2025-06-19 19:22:23 +02:00
Adrian Zürcher
9605b50198 add new argument for allow origins and query without path and only uuid 2025-05-28 22:05:47 +02:00
Adrian Zürcher
c57c22f93a add new parameter hasChild and set with connection id 2025-05-28 22:04:40 +02:00
Adrian Zürcher
60b3f77e29 change user write so cert can be created without root 2025-05-28 22:03:29 +02:00
Adrian Zürcher
1c4b8a5995 fix pointer error aguments 2025-05-28 22:02:36 +02:00
29 changed files with 956 additions and 515 deletions

View File

@@ -36,9 +36,9 @@ jobs:
run: | run: |
mkdir -p build mkdir -p build
if [ "${{ matrix.goos }}" == "windows" ]; then if [ "${{ matrix.goos }}" == "windows" ]; then
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }}.exe main.go
else else
GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }} main.go GOOS=${{ matrix.goos }} GOARCH=${{ matrix.goarch }} go build -ldflags="-s -w" -trimpath -o build/tecamino-dbm-${{ matrix.goos }}-${{ matrix.goarch }} main.go
fi fi
- name: Upload artifacts - name: Upload artifacts

3
.gitignore vendored
View File

@@ -1,3 +1,6 @@
.DS_Store .DS_Store
*.dbm *.dbm
*.log *.log
# local executables
dbm-arm64

View File

@@ -9,30 +9,55 @@ import (
// DBM cli arguments // DBM cli arguments
type Args struct { type Args struct {
Port models.Port Ip string
Cert cert.Cert Port models.Port
RootDir string Cert cert.Cert
DBMFile string AllowOrigins []string
Debug bool RootDir string
DBMFile string
Debug bool
} }
// initialte cli arguments // initialte cli arguments
func Init() *Args { func Init() *Args {
var allowOrigins models.StringSlice
flag.Var(&allowOrigins, "allowOrigin", "Allowed origin (can repeat this flag)")
ip := flag.String("ip", "0.0.0.0", "local ip address")
organization := flag.String("org", "tecamino", "name of organization for certificate")
certFile := flag.String("certFile", "./cert/cert.pem", "path of certfile")
keyFile := flag.String("keyFile", "./cert/key.pem", "path of keyfile")
portHttp := flag.Uint("http-port", 8100, "json server communication for http/ws")
portHttps := flag.Uint("https-port", 8101, "json server communication for http/wss")
remotePort := flag.Uint("remotePort", 9500, "remote Port of gui user interface")
rootDir := flag.String("workingDir", "./", "working directory")
dbmFile := flag.String("dbm", "/test/test", "dbm file name")
debug := flag.Bool("debug", false, "debug flag")
flag.Parse()
a := Args{ a := Args{
Ip: *ip,
Cert: cert.Cert{ Cert: cert.Cert{
Organization: *flag.String("org", "tecamino", "name of organization for certificate"), Organization: *organization,
CertFile: *flag.String("certFile", "./cert/cert.pem", "path of certfile"), CertFile: *certFile,
KeyFile: *flag.String("keyFile", "./cert/key.pem", "path of keyfile"), KeyFile: *keyFile,
}, },
Port: models.Port{ Port: models.Port{
Http: *flag.Uint("http-port", 8100, "json server communication for http/ws"), Http: *portHttp,
Https: *flag.Uint("https-port", 8101, "json server communication for http/wss"), Https: *portHttps,
Remote: *remotePort,
}, },
RootDir: *flag.String("workingDir", "./", "working directory"), RootDir: *rootDir,
DBMFile: *flag.String("dbm", "/test/test", "dbm file name"), DBMFile: *dbmFile,
Debug: *flag.Bool("debug", false, "debug flag"), Debug: *debug,
} }
flag.Parse()
if len(allowOrigins) == 0 {
allowOrigins = models.StringSlice{"http://localhost:9500"}
}
a.AllowOrigins = allowOrigins
return &a return &a
} }

View File

@@ -63,7 +63,7 @@ func (c *Cert) GenerateSelfSignedCert() error {
} }
if _, err := os.Stat(path.Dir(c.CertFile)); os.IsNotExist(err) { if _, err := os.Stat(path.Dir(c.CertFile)); os.IsNotExist(err) {
os.MkdirAll(path.Dir(c.CertFile), 0666) os.MkdirAll(path.Dir(c.CertFile), 0700)
} }
certOut, err := os.Create(c.CertFile) certOut, err := os.Create(c.CertFile)
@@ -73,8 +73,13 @@ func (c *Cert) GenerateSelfSignedCert() error {
defer certOut.Close() defer certOut.Close()
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certDER}) pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certDER})
// Set permission to 0600 (read/write by owner only)
if err := os.Chmod(c.CertFile, 0600); err != nil {
return err
}
if _, err := os.Stat(path.Dir(c.KeyFile)); os.IsNotExist(err) { if _, err := os.Stat(path.Dir(c.KeyFile)); os.IsNotExist(err) {
os.MkdirAll(path.Dir(c.KeyFile), 0666) os.MkdirAll(path.Dir(c.KeyFile), 0700)
} }
keyOut, err := os.Create(c.KeyFile) keyOut, err := os.Create(c.KeyFile)
@@ -85,5 +90,10 @@ func (c *Cert) GenerateSelfSignedCert() error {
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
// Set permission to 0600 (read/write by owner only)
if err := os.Chmod(c.KeyFile, 0600); err != nil {
return err
}
return nil return nil
} }

View File

@@ -11,13 +11,13 @@ import (
"github.com/tecamino/tecamino-dbm/args" "github.com/tecamino/tecamino-dbm/args"
"github.com/tecamino/tecamino-dbm/models" "github.com/tecamino/tecamino-dbm/models"
serverModels "github.com/tecamino/tecamino-dbm/server/models" ws "github.com/tecamino/tecamino-dbm/websocket"
"github.com/tecamino/tecamino-logger/logging" "github.com/tecamino/tecamino-logger/logging"
) )
type DBMHandler struct { type DBMHandler struct {
DBM *models.DBM DBM *models.DBM
Conns *serverModels.Connections Conns *ws.ClientHandler
sync.RWMutex sync.RWMutex
Log *logging.Logger Log *logging.Logger
arg *args.Args arg *args.Args
@@ -43,7 +43,7 @@ func NewDbmHandler(a *args.Args) (*DBMHandler, error) {
logger.Info("main", "start dma handler") logger.Info("main", "start dma handler")
//initialize connection map //initialize connection map
conns := serverModels.NewConnections() conns := ws.NewConnectionHandler()
// Initialize dtabase manager handler // Initialize dtabase manager handler
dmaHandler := DBMHandler{ dmaHandler := DBMHandler{
@@ -74,8 +74,8 @@ func NewDbmHandler(a *args.Args) (*DBMHandler, error) {
var line int var line int
for scanner.Scan() { for scanner.Scan() {
line++ line++
dp := models.Datapoint{} dp := &models.Datapoint{}
if err = json.Unmarshal(scanner.Bytes(), &dp); err != nil { if err = json.Unmarshal(scanner.Bytes(), dp); err != nil {
dmaHandler.Log.Error("dmbHandler.NewDmbHandler", "error in line "+fmt.Sprint(line)+" "+scanner.Text()) dmaHandler.Log.Error("dmbHandler.NewDmbHandler", "error in line "+fmt.Sprint(line)+" "+scanner.Text())
dmaHandler.Log.Error("dmbHandler.NewDmbHandler", err.Error()) dmaHandler.Log.Error("dmbHandler.NewDmbHandler", err.Error())

View File

@@ -24,11 +24,12 @@ func (d *DBMHandler) Get(req *json_dataModels.Request, id string) {
for _, dp := range d.DBM.QueryDatapoints(depth, get.Uuid, get.Path) { for _, dp := range d.DBM.QueryDatapoints(depth, get.Uuid, get.Path) {
resp.AddGet(json_dataModels.Get{ resp.AddGet(json_dataModels.Get{
Uuid: dp.Uuid, Uuid: dp.Uuid,
Path: dp.Path, Path: dp.Path,
Type: dp.Type, Type: dp.Type,
Value: dp.Value, Value: dp.Value,
Rights: dp.ReadWrite, HasChild: dp.Datapoints != nil,
Rights: dp.ReadWrite,
}) })
} }
} }

View File

@@ -1,6 +1,7 @@
package dbm package dbm
import ( import (
"fmt"
"net/http" "net/http"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -20,29 +21,35 @@ func (d *DBMHandler) Json_Data(c *gin.Context) {
return return
} }
respond := json_dataModels.NewResponse() resp := json_dataModels.NewResponse()
if payload.Get != nil { if len(payload.Get) > 0 {
var depth uint = 1 var depth uint = 1
for _, get := range payload.Get { for _, get := range payload.Get {
if get.Query != nil { if get.Query != nil {
depth = get.Query.Depth depth = get.Query.Depth
} }
for _, res := range d.DBM.QueryDatapoints(depth, get.Uuid, get.Path) { for _, res := range d.DBM.QueryDatapoints(depth, get.Uuid, get.Path) {
respond.AddGet(json_dataModels.Get{ resp.AddGet(json_dataModels.Get{
Uuid: res.Uuid, Uuid: res.Uuid,
Path: res.Path, Path: res.Path,
Type: res.Type, Type: res.Type,
Value: res.Value, Value: res.Value,
Rights: res.ReadWrite, Drivers: &res.Drivers,
Drivers: &res.Drivers, HasChild: res.Datapoints != nil,
Rights: res.ReadWrite,
}) })
} }
} }
} }
if payload.Set != nil { if len(payload.Set) > 0 {
respond.Set, err = d.DBM.CreateDatapoints(payload.Set...) resp.Set, err = d.DBM.CreateDatapoints(payload.Set...)
for i, o := range resp.Set {
fmt.Println(1000, i, o)
fmt.Println(1001, o.HasChild)
}
if err != nil { if err != nil {
r := json_data.NewResponse() r := json_data.NewResponse()
r.SetError() r.SetError()
@@ -52,7 +59,7 @@ func (d *DBMHandler) Json_Data(c *gin.Context) {
} }
} }
c.JSON(200, respond) c.JSON(200, resp)
} }
func (d *DBMHandler) Delete(c *gin.Context) { func (d *DBMHandler) Delete(c *gin.Context) {
@@ -67,9 +74,7 @@ func (d *DBMHandler) Delete(c *gin.Context) {
} }
response := json_data.NewResponse() response := json_data.NewResponse()
if payload.Set != nil { if payload.Set != nil {
response.Set, err = d.DBM.RemoveDatapoint(payload.Set...) response.Set, err = d.DBM.RemoveDatapoint(payload.Set...)
if err != nil { if err != nil {
r := json_data.NewResponse() r := json_data.NewResponse()

View File

@@ -1,10 +1,12 @@
package dbm package dbm
import ( import (
"fmt"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
func (d *DBMHandler) Set(req *json_dataModels.Request) { func (d *DBMHandler) Set(req *json_dataModels.Request, id string) {
if req == nil { if req == nil {
return return
} else if len(req.Set) == 0 { } else if len(req.Set) == 0 {
@@ -13,9 +15,32 @@ func (d *DBMHandler) Set(req *json_dataModels.Request) {
d.RLock() d.RLock()
defer d.RUnlock() defer d.RUnlock()
resp := json_dataModels.NewResponse()
resp.Id = req.Id
for _, set := range req.Set { for _, set := range req.Set {
for _, dp := range d.DBM.QueryDatapoints(1, set.Uuid, set.Path) { dps := d.DBM.QueryDatapoints(1, set.Uuid, set.Path)
dp.UpdateValue(d.Conns, set.Value)
if len(dps) == 0 {
resp.SetError()
if resp.Message == "" {
resp.SetMessage(fmt.Sprintf("datapoint %s not found", set.Path))
}
continue
}
for _, dp := range dps {
dp.UpdateValue(set.Value)
resp.AddSet(json_dataModels.Set{
Uuid: dp.Uuid,
Path: dp.Path,
Value: dp.Value,
})
} }
} }
if err := d.Conns.SendResponse(id, resp); err != nil {
d.Log.Error("get.Set", err.Error())
}
} }

View File

@@ -1,6 +1,8 @@
package dbm package dbm
import ( import (
"fmt"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
@@ -18,23 +20,41 @@ func (d *DBMHandler) Subscribe(req *json_dataModels.Request, id string) {
resp.Id = req.Id resp.Id = req.Id
for _, sub := range req.Subscribe { for _, sub := range req.Subscribe {
for _, dp := range d.DBM.QueryDatapoints(sub.Depth, sub.Uuid, sub.Path) { dps := d.DBM.QueryDatapoints(sub.Depth, sub.Uuid, sub.Path)
if len(dps) == 0 {
resp.SetError()
if resp.Message == "" {
resp.SetMessage(fmt.Sprintf("datapoint %s not found", sub.Path))
}
continue
}
for _, dp := range dps {
if sub.Driver != "" { if sub.Driver != "" {
if dp.Drivers == nil || dp.Drivers[sub.Driver] == nil { if dp.Drivers == nil || dp.Drivers[sub.Driver] == nil {
continue continue
} }
} }
dp.AddSubscribtion(id, sub)
client := d.DBM.Conns.GetClient(id)
if client == nil {
d.Log.Warning("subscribe", "id "+id+" not found")
continue
}
dp.AddSubscribtion(client, sub)
resp.AddSubscription(json_dataModels.Subscription{ resp.AddSubscription(json_dataModels.Subscription{
Uuid: dp.Uuid, Uuid: dp.Uuid,
Path: dp.Path, Path: dp.Path,
Value: dp.Value, Value: dp.Value,
Driver: sub.Driver, HasChild: dp.Datapoints != nil,
Drivers: &dp.Drivers, Rights: dp.ReadWrite.GetRights(),
Driver: sub.Driver,
Drivers: &dp.Drivers,
}) })
} }
} }
if err := d.Conns.SendResponse(id, resp); err != nil { if err := d.Conns.SendResponse(id, resp); err != nil {
d.Log.Error("subscribe.Subscribe", err.Error()) d.Log.Error("subscribe.Subscribe", err.Error())
} }
@@ -55,10 +75,17 @@ func (d *DBMHandler) Unsubscribe(req *json_dataModels.Request, id string) {
for _, sub := range req.Unsubscribe { for _, sub := range req.Unsubscribe {
for _, dp := range d.DBM.QueryDatapoints(sub.Depth, sub.Uuid, sub.Path) { for _, dp := range d.DBM.QueryDatapoints(sub.Depth, sub.Uuid, sub.Path) {
if _, ok := dp.Subscriptions[id]; !ok {
client := d.DBM.Conns.GetClient(id)
if client == nil {
d.Log.Warning("subscribe", "id "+id+" not found")
continue continue
} }
dp.RemoveSubscribtion(id)
if _, ok := dp.Subscriptions[client]; !ok {
continue
}
dp.RemoveSubscribtion(client)
resp.AddUnsubscription(json_dataModels.Subscription{ resp.AddUnsubscription(json_dataModels.Subscription{
Uuid: dp.Uuid, Uuid: dp.Uuid,
Path: dp.Path, Path: dp.Path,

View File

@@ -2,11 +2,7 @@ package dbm
import ( import (
"encoding/json" "encoding/json"
"errors"
"fmt"
"io"
"github.com/coder/websocket"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/auth" "github.com/tecamino/tecamino-dbm/auth"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "github.com/tecamino/tecamino-json_data/models"
@@ -26,76 +22,40 @@ func (d *DBMHandler) WebSocket(c *gin.Context) {
} }
d.Log.Debug("dbmHandler.webSocket.Websocket", "authorization id token: "+id) d.Log.Debug("dbmHandler.webSocket.Websocket", "authorization id token: "+id)
err = d.Conns.ConnectRecievingWsConnection(id, c) client, err := d.Conns.ConnectNewClient(id, c)
defer d.Conns.RemoveClient(id)
if err != nil { if err != nil {
d.Log.Error("dbmHandler.webSocket.Websocket", "error connecting recieving websocket conection: "+err.Error()) d.Log.Error("dbmHandler.webSocket.Websocket", err)
return return
} }
defer d.Conns.DisconnectWsConnection(id, websocket.StatusInternalError, "Internal error")
//Read loop client.OnMessage = func(data []byte) {
for { request, err := d.readJsonData(data)
request, err := d.readJsonData(id)
if err != nil { if err != nil {
d.Log.Error("websocket.WebSocket", err.Error()) d.Log.Error("dbmHandler.webSocket.Websocket", "read json: "+err.Error())
break
} }
// Sets // Sets
d.Get(request, id) d.Get(request, id)
// Sets // Sets
d.Set(request) d.Set(request, id)
// Subscribe // Subscribe
d.Subscribe(request, id) d.Subscribe(request, id)
// Unsubscribe // Unsubscribe
d.Unsubscribe(request, id) d.Unsubscribe(request, id)
}
request.Get = make([]json_dataModels.Get, 0) client.OnWarning = func(s string) {
request.Set = make([]json_dataModels.Set, 0) d.Log.Warning("dbmHandler.webSocket.Websocket", "warning on websocket connection: "+s)
request.Subscribe = make([]json_dataModels.Subscription, 0) }
request.Unsubscribe = make([]json_dataModels.Subscription, 0)
request = nil client.OnError = func(err error) {
d.Log.Error("dbmHandler.webSocket.Websocket", "error on websocket connection: "+err.Error())
} }
} }
func (d *DBMHandler) readJsonData(id string) (request *json_dataModels.Request, err error) { func (d *DBMHandler) readJsonData(data []byte) (request *json_dataModels.Request, err error) {
err = json.Unmarshal(data, &request)
client, ok := d.Conns.Clients[id]
if !ok {
return request, errors.New("client id not found")
}
_, reader, err := client.Conn.Reader(client.Ctx)
if err != nil {
d.Log.Info("webSocket.readJsonData", fmt.Sprintf("WebSocket reader: %v\n", err))
return request, nil
}
b, err := io.ReadAll(reader)
if err != nil {
code := websocket.CloseStatus(err)
switch code {
case websocket.StatusNormalClosure,
websocket.StatusGoingAway,
websocket.StatusNoStatusRcvd:
d.Log.Info("webSocket.readJsonData", fmt.Sprintf("WebSocket closed: %v (code: %v)\n", err, code))
return
default:
d.Log.Error("webSocket.readJsonData", fmt.Sprintf("WebSocket read error: %v (code: %v)\n", err, code))
return
}
}
if err := json.Unmarshal(b, &request); err != nil {
return request, err
}
return return
} }

36
go.mod
View File

@@ -3,41 +3,41 @@ module github.com/tecamino/tecamino-dbm
go 1.24.0 go 1.24.0
require ( require (
github.com/coder/websocket v1.8.13 github.com/gin-contrib/cors v1.7.5
github.com/gin-gonic/gin v1.10.0 github.com/gin-gonic/gin v1.10.0
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/tecamino/tecamino-json_data v0.0.13 github.com/gorilla/websocket v1.5.3
github.com/tecamino/tecamino-json_data v0.0.21
github.com/tecamino/tecamino-logger v0.2.0 github.com/tecamino/tecamino-logger v0.2.0
) )
require ( require (
github.com/bytedance/sonic v1.11.6 // indirect github.com/bytedance/sonic v1.13.2 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect github.com/bytedance/sonic/loader v0.2.4 // indirect
github.com/cloudwego/base64x v0.1.4 // indirect github.com/cloudwego/base64x v0.1.5 // indirect
github.com/cloudwego/iasm v0.2.0 // indirect github.com/gabriel-vasile/mimetype v1.4.8 // indirect
github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v1.0.0 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.20.0 // indirect github.com/go-playground/validator/v10 v10.26.0 // indirect
github.com/goccy/go-json v0.10.2 // indirect github.com/goccy/go-json v0.10.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.7 // indirect github.com/klauspost/cpuid/v2 v2.2.10 // indirect
github.com/leodido/go-urn v1.4.0 // indirect github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-isatty v0.0.20 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.12 // indirect github.com/ugorji/go/codec v1.2.12 // indirect
go.uber.org/multierr v1.10.0 // indirect go.uber.org/multierr v1.10.0 // indirect
go.uber.org/zap v1.27.0 // indirect go.uber.org/zap v1.27.0 // indirect
golang.org/x/arch v0.8.0 // indirect golang.org/x/arch v0.15.0 // indirect
golang.org/x/crypto v0.23.0 // indirect golang.org/x/crypto v0.36.0 // indirect
golang.org/x/net v0.25.0 // indirect golang.org/x/net v0.38.0 // indirect
golang.org/x/sys v0.20.0 // indirect golang.org/x/sys v0.31.0 // indirect
golang.org/x/text v0.15.0 // indirect golang.org/x/text v0.23.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect google.golang.org/protobuf v1.36.6 // indirect
gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
) )

86
go.sum
View File

@@ -1,20 +1,20 @@
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0= github.com/bytedance/sonic v1.13.2 h1:8/H1FempDZqC4VqjptGo14QQlJx8VdZJegxs6wwfqpQ=
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= github.com/bytedance/sonic v1.13.2/go.mod h1:o68xyaF9u2gvVBuGHPlUVCy+ZfmNNO5ETf1+KgkJhz4=
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= github.com/bytedance/sonic/loader v0.2.4 h1:ZWCw4stuXUsn1/+zQDqeE7JKP+QO47tz7QCNan80NzY=
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= github.com/bytedance/sonic/loader v0.2.4/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= github.com/cloudwego/base64x v0.1.5 h1:XPciSp1xaq2VCSt6lF0phncD4koWyULpl5bUxbfCyP4=
github.com/cloudwego/base64x v0.1.5/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
github.com/coder/websocket v1.8.13 h1:f3QZdXy7uGVz+4uCJy2nTZyM0yTBj8yANEHhqlXZ9FE=
github.com/coder/websocket v1.8.13/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 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/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= github.com/gabriel-vasile/mimetype v1.4.8 h1:FfZ3gj38NjllZIeJAmMhr+qKL8Wu+nOoI3GqacKw1NM=
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gabriel-vasile/mimetype v1.4.8/go.mod h1:ByKUIKGjh1ODkGM1asKUbQZOLGrPjydw3hYPU2YU9t8=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/cors v1.7.5 h1:cXC9SmofOrRg0w9PigwGlHG3ztswH6bqq4vJVXnvYMk=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-contrib/cors v1.7.5/go.mod h1:4q3yi7xBEDDWKapjT2o1V7mScKDDr8k+jZ0fSquGoy0=
github.com/gin-contrib/sse v1.0.0 h1:y3bT1mUWUxDpW4JLQg/HnTqV4rozuW4tC9eFKTxYI9E=
github.com/gin-contrib/sse v1.0.0/go.mod h1:zNuFdwarAygJBht0NTKiSi3jRf6RbqeILZ9Sp6Slhe0=
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
@@ -23,21 +23,27 @@ github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/o
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= github.com/go-playground/validator/v10 v10.26.0 h1:SP05Nqhjcvz81uJaRfEV0YBSSSGMc/iMaVtFbr3Sw2k=
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= github.com/go-playground/validator/v10 v10.26.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= 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/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/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE=
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/klauspost/cpuid/v2 v2.2.10/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
@@ -47,10 +53,12 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M=
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
@@ -61,10 +69,10 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/tecamino/tecamino-json_data v0.0.13 h1:hugbmCgXXh0F7YQAEbbJYHkSdq1caejD7SajDiMs42I= github.com/tecamino/tecamino-json_data v0.0.21 h1:ZRN9wyn+p6J1T4b0e9xf1HStVaAy4wb+3yZ9xn5LFc0=
github.com/tecamino/tecamino-json_data v0.0.13/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY= github.com/tecamino/tecamino-json_data v0.0.21/go.mod h1:LLlyD7Wwqplb2BP4PeO86EokEcTRidlW5MwgPd1T2JY=
github.com/tecamino/tecamino-logger v0.2.0 h1:NPH/Gg9qRhmVoW8b39i1eXu/LEftHc74nyISpcRG+XU= github.com/tecamino/tecamino-logger v0.2.0 h1:NPH/Gg9qRhmVoW8b39i1eXu/LEftHc74nyISpcRG+XU=
github.com/tecamino/tecamino-logger v0.2.0/go.mod h1:0M1E9Uei/qw3e3WA1x3lBo1eP3H5oeYE7GjYrMahnj8= github.com/tecamino/tecamino-logger v0.2.0/go.mod h1:0M1E9Uei/qw3e3WA1x3lBo1eP3H5oeYE7GjYrMahnj8=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
@@ -77,29 +85,27 @@ go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.15.0 h1:QtOrQd0bTUnhNVNndMpLHNWrDmYzZ2KDqSrEymqInZw=
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= golang.org/x/arch v0.15.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34=
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= golang.org/x/net v0.38.0 h1:vRMAPTMaeGqVhG5QyLJHqNDwecKTomGeqbnfZyKlBI8=
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= golang.org/x/net v0.38.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= google.golang.org/protobuf v1.36.6 h1:z1NpPI8ku2WgiWnf+t9wTPsn6eP1L7ksHUlkfLvd9xY=
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= google.golang.org/protobuf v1.36.6/go.mod h1:jduwjTPXsFjZGTmRluh+L6NjiWu7pchiJ2/5YcXBHnY=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 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=
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

14
main.go
View File

@@ -6,7 +6,7 @@ import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/args" "github.com/tecamino/tecamino-dbm/args"
"github.com/tecamino/tecamino-dbm/dbm" "github.com/tecamino/tecamino-dbm/dbm"
"github.com/tecamino/tecamino-dbm/server" ws "github.com/tecamino/tecamino-dbm/websocket"
) )
func main() { func main() {
@@ -18,12 +18,12 @@ func main() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
//save database after exeutabe ends //save database after executabe ends
defer dbmHandler.SaveDb() defer dbmHandler.SaveDb()
//initialize new server //initialize new server
dbmHandler.Log.Debug("main", "initialize new server instance") dbmHandler.Log.Debug("main", "initialize new server instance")
s := server.NewServer() s := ws.NewServer(a.AllowOrigins, a.Port.Remote)
//set routes //set routes
dbmHandler.Log.Debug("main", "setting routes") dbmHandler.Log.Debug("main", "setting routes")
@@ -37,16 +37,16 @@ func main() {
// start http server // start http server
go func() { go func() {
dbmHandler.Log.Info("main", fmt.Sprintf("http listen on %d", a.Port.Http)) dbmHandler.Log.Info("main", fmt.Sprintf("http listen on ip: %s port: %d", a.Ip, a.Port.Http))
if err := s.ServeHttp(a.Port.Http); err != nil { if err := s.ServeHttp(a.Ip, a.Port.Http); err != nil {
dbmHandler.Log.Error("main", "error http server "+err.Error()) dbmHandler.Log.Error("main", "error http server "+err.Error())
panic(err) panic(err)
} }
}() }()
// start https server // start https server
dbmHandler.Log.Info("main", fmt.Sprintf("https listen on %d", a.Port.Https)) dbmHandler.Log.Info("main", fmt.Sprintf("https listen on ip: %s port: %d", a.Ip, a.Port.Https))
if err := s.ServeHttps(a.Port.Https, a.Cert); err != nil { if err := s.ServeHttps(a.Ip, a.Port.Https, a.Cert); err != nil {
dbmHandler.Log.Error("main", "error http server "+err.Error()) dbmHandler.Log.Error("main", "error http server "+err.Error())
panic(err) panic(err)
} }

View File

@@ -1,6 +1,7 @@
package models package models
import ( import (
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"regexp" "regexp"
@@ -8,8 +9,9 @@ import (
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
serverModels "github.com/tecamino/tecamino-dbm/server/models"
"github.com/tecamino/tecamino-dbm/utils" "github.com/tecamino/tecamino-dbm/utils"
ws "github.com/tecamino/tecamino-dbm/websocket"
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
json_data "github.com/tecamino/tecamino-json_data" json_data "github.com/tecamino/tecamino-json_data"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "github.com/tecamino/tecamino-json_data/models"
) )
@@ -21,16 +23,17 @@ const (
) )
type Datapoint struct { type Datapoint struct {
Datapoints map[string]*Datapoint `json:"-"`
Uuid uuid.UUID `json:"uuid"` Uuid uuid.UUID `json:"uuid"`
Path string `json:"path"`
Value any `json:"value,omitempty"` Value any `json:"value,omitempty"`
Path string `json:"path"`
CreateDateTime int64 `json:"createDateTime,omitempty"` CreateDateTime int64 `json:"createDateTime,omitempty"`
UpdateDateTime int64 `json:"updateDateTime,omitempty"` UpdateDateTime int64 `json:"updateDateTime,omitempty"`
Type json_dataModels.Type `json:"type"` Datapoints map[string]*Datapoint `json:"-"`
ReadWrite json_dataModels.Rights `json:"readWrite"`
Drivers json_dataModels.Drivers `json:"drivers,omitempty"` Drivers json_dataModels.Drivers `json:"drivers,omitempty"`
Subscriptions Subscriptions `json:"-"` Subscriptions Subscriptions `json:"-"`
Type json_dataModels.Type `json:"type"`
ReadWrite json_dataModels.Rights `json:"readWrite"`
HasChild bool `json:"-"`
} }
func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) { func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) {
@@ -53,8 +56,8 @@ func (d *Datapoint) Set(path string, set json_dataModels.Set) (bool, error) {
changed = true changed = true
d.Value = d.Type.ConvertValue(set.Value) d.Value = d.Type.ConvertValue(set.Value)
} }
} }
if set.Rights != "" { if set.Rights != "" {
changed = true changed = true
d.ReadWrite = set.Rights.GetRights() d.ReadWrite = set.Rights.GetRights()
@@ -87,14 +90,15 @@ func (d *Datapoint) GetValueUint64() uint64 {
return utils.Uint64From(d.Value) return utils.Uint64From(d.Value)
} }
func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...json_dataModels.Set) (created []json_dataModels.Set, uuids Uuids, err error) { func (d *Datapoint) CreateDatapoints(uuids *Uuids, sets ...json_dataModels.Set) (created []json_dataModels.Set, err error) {
if len(sets) == 0 { if len(sets) == 0 {
return return
} }
uuids = make(Uuids, 1) publishes := []json_dataModels.Publish{}
for _, dp := range sets { for _, dp := range sets {
parts := strings.Split(dp.Path, ":") parts := strings.Split(dp.Path, ":")
current := d current := d
@@ -102,52 +106,66 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
if current.Datapoints == nil { if current.Datapoints == nil {
current.Datapoints = make(map[string]*Datapoint) current.Datapoints = make(map[string]*Datapoint)
} }
if i == len(parts)-1 { if i == len(parts)-1 {
// Leaf node: create or update datapoint // Leaf node: create or update datapoint
if existing, ok := current.Datapoints[part]; ok { if existing, ok := current.Datapoints[part]; ok {
publish, err := existing.Set("", dp)
_, err := existing.Set("", dp)
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
created = append(created, json_dataModels.Set{ created = append(created, json_dataModels.Set{
Uuid: existing.Uuid, Uuid: existing.Uuid,
Path: existing.Path, Path: existing.Path,
Type: existing.Type, Type: existing.Type,
Value: existing.Value, Value: existing.Value,
Rights: existing.ReadWrite, Rights: existing.ReadWrite,
Drivers: &existing.Drivers, Drivers: &existing.Drivers,
Updated: true, Updated: true,
HasChild: existing.HasChild,
}) })
if publish { existing.Publish(OnChange)
existing.Publish(conns, OnChange)
}
} else { } else {
ndp := Datapoint{ var uid uuid.UUID = uuid.New()
Uuid: uuid.New(), if dp.Uuid != uuid.Nil {
uid = dp.Uuid
}
ndp := &Datapoint{
Uuid: uid,
CreateDateTime: time.Now().UnixMilli(), CreateDateTime: time.Now().UnixMilli(),
Subscriptions: InitSubscribtion(), Subscriptions: InitSubscribtion(),
} }
// Create new // Create new
current.Datapoints[part] = &ndp current.Datapoints[part] = ndp
publish, err := ndp.Set(strings.Join(parts, ":"), dp)
_, err := ndp.Set(strings.Join(parts, ":"), dp)
if err != nil { if err != nil {
return nil, nil, err return nil, err
} }
//add uuid to flat map for faster lookup
uuids.AddDatapoint(current, ndp)
created = append(created, json_dataModels.Set{ created = append(created, json_dataModels.Set{
Uuid: ndp.Uuid, Uuid: ndp.Uuid,
Path: ndp.Path, Path: ndp.Path,
Type: ndp.Type, Type: ndp.Type,
Value: ndp.Value, Value: ndp.Value,
Rights: ndp.ReadWrite, Rights: ndp.ReadWrite,
Driver: dp.Driver, Driver: dp.Driver,
HasChild: ndp.HasChild,
})
publishes = append(publishes, json_dataModels.Publish{
Event: OnCreate,
Uuid: ndp.Uuid,
Path: ndp.Path,
Type: ndp.Type,
Value: ndp.Value,
}) })
if publish {
current.Publish(conns, OnChange)
}
//add uuid to flat map for faster lookuo
uuids[ndp.Uuid] = &ndp
} }
} }
@@ -164,34 +182,51 @@ func (d *Datapoint) CreateDatapoints(conns *serverModels.Connections, sets ...js
Subscriptions: InitSubscribtion(), Subscriptions: InitSubscribtion(),
} }
//add uuid to flat map for faster lookup
uuids.AddDatapoint(current, newDp)
created = append(created, json_dataModels.Set{ created = append(created, json_dataModels.Set{
Uuid: newDp.Uuid, Uuid: newDp.Uuid,
Path: newDp.Path, Path: newDp.Path,
Type: newDp.Type, Type: newDp.Type,
Value: newDp.Value, Value: newDp.Value,
Rights: newDp.ReadWrite, Rights: newDp.ReadWrite,
HasChild: newDp.HasChild,
}) })
if dp.Rights != "" { if dp.Rights != "" {
newDp.ReadWrite = dp.Rights.GetRights() newDp.ReadWrite = dp.Rights.GetRights()
} }
publishes = append(publishes, json_dataModels.Publish{
Event: OnCreate,
Uuid: newDp.Uuid,
Path: newDp.Path,
Type: newDp.Type,
Value: newDp.Value,
})
current.Datapoints[part] = newDp current.Datapoints[part] = newDp
current = newDp current = newDp
//add uuid to flat map for faster lookuo
uuids[newDp.Uuid] = newDp
} }
} }
} }
r := json_data.NewResponse()
r.Publish = append(r.Publish, publishes...)
b, err := json.Marshal(r)
if err != nil {
return created, err
}
ws.SendBroadcast(b)
return return
} }
func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoint, path string) (uuids Uuids, err error) { func (d *Datapoint) ImportDatapoint(uuids *Uuids, dp *Datapoint, path string) (err error) {
parts := strings.Split(dp.Path, ":") parts := strings.Split(dp.Path, ":")
uuids = make(Uuids, 1)
current := d current := d
for i, part := range parts { for i, part := range parts {
if current.Datapoints == nil { if current.Datapoints == nil {
@@ -205,19 +240,20 @@ func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoin
existing.Value = dp.Type.ConvertValue(dp.Value) existing.Value = dp.Type.ConvertValue(dp.Value)
existing.ReadWrite = dp.ReadWrite.GetRights() existing.ReadWrite = dp.ReadWrite.GetRights()
existing.UpdateDateTime = time.Now().UnixMilli() existing.UpdateDateTime = time.Now().UnixMilli()
dp.Publish(conns, OnChange) dp.Publish(OnChange)
} else { } else {
dp.Path = strings.Join(parts, ":") dp.Path = strings.Join(parts, ":")
dp.ReadWrite = dp.ReadWrite.GetRights() dp.ReadWrite = dp.ReadWrite.GetRights()
dp.UpdateDateTime = time.Now().UnixMilli() dp.UpdateDateTime = time.Now().UnixMilli()
dp.Subscriptions = InitSubscribtion() dp.Subscriptions = InitSubscribtion()
current.Datapoints[part] = &dp current.Datapoints[part] = dp
//add uuid to flat map for faster lookuo //add uuid to flat map for faster lookup
uuids[dp.Uuid] = &dp uuids.AddDatapoint(current, dp)
dp.Publish(conns, OnChange)
dp.Publish(OnChange)
} }
return uuids, nil return nil
} }
// Traverse or create intermediate nodes // Traverse or create intermediate nodes
@@ -233,14 +269,14 @@ func (d *Datapoint) ImportDatapoint(conns *serverModels.Connections, dp Datapoin
newDp.ReadWrite = newDp.ReadWrite.GetRights() newDp.ReadWrite = newDp.ReadWrite.GetRights()
current.Datapoints[part] = newDp current.Datapoints[part] = newDp
current = newDp current = newDp
//add uuid to flat map for faster lookuo //add uuid to flat map for faster lookup
uuids[newDp.Uuid] = newDp uuids.AddDatapoint(current, newDp)
} }
} }
return uuids, nil return nil
} }
func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value any, path string) error { func (d *Datapoint) UpdateDatapointValue(value any, path string) error {
paths := strings.Split(path, ":") paths := strings.Split(path, ":")
@@ -253,7 +289,7 @@ func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value
if i == len(paths)-1 { if i == len(paths)-1 {
dp.Value = dp.Type.ConvertValue(value) dp.Value = dp.Type.ConvertValue(value)
dp.UpdateDateTime = time.Now().UnixMilli() dp.UpdateDateTime = time.Now().UnixMilli()
dp.Publish(conns, OnChange) dp.Publish(OnChange)
return nil return nil
} }
current = dp current = dp
@@ -261,57 +297,91 @@ func (d *Datapoint) UpdateDatapointValue(conns *serverModels.Connections, value
return nil return nil
} }
func (d *Datapoint) UpdateValue(conns *serverModels.Connections, value any) error { func (d *Datapoint) UpdateValue(value any) error {
d.Value = d.Type.ConvertValue(value) d.Value = d.Type.ConvertValue(value)
d.UpdateDateTime = time.Now().UnixMilli() d.UpdateDateTime = time.Now().UnixMilli()
d.Publish(conns, OnChange) d.Publish(OnChange)
return nil return nil
} }
func (d *Datapoint) RemoveDatapoint(conns *serverModels.Connections, set json_dataModels.Set) (json_dataModels.Set, error) { func (d *Datapoint) RemoveDatapoint(set json_dataModels.Set) (sets []json_dataModels.Set, err error) {
parts := strings.Split(set.Path, ":") parts := strings.Split(set.Path, ":")
if len(parts) < 1 { if len(parts) < 1 {
return json_dataModels.Set{}, fmt.Errorf("invalid path: '%s'", set.Path) return sets, fmt.Errorf("invalid path: '%s'", set.Path)
} }
publishes := []json_dataModels.Publish{}
current := d current := d
for i := range len(parts) - 1 { for i := 0; i < len(parts)-1; i++ {
next, ok := current.Datapoints[parts[i]] next, ok := current.Datapoints[parts[i]]
if !ok { if !ok {
return json_dataModels.Set{}, fmt.Errorf("path not found: '%s'", strings.Join(parts[:i+1], ":")) return sets, fmt.Errorf("path not found: '%s'", strings.Join(parts[:i+1], ":"))
} }
current = next current = next
} }
toDelete := parts[len(parts)-1] toDelete := parts[len(parts)-1]
if dp, ok := current.Datapoints[toDelete]; ok { if dp, ok := current.Datapoints[toDelete]; ok {
dp.Publish(conns, OnDelete) s, p := removeChildren(dp)
sets = append(sets, s...)
publishes = append(publishes, p...)
publishes = append(publishes, json_dataModels.Publish{
Event: OnDelete,
Uuid: dp.Uuid,
Path: dp.Path,
})
sets = append(sets, json_dataModels.Set{
Uuid: dp.Uuid,
Path: dp.Path,
})
delete(current.Datapoints, toDelete) delete(current.Datapoints, toDelete)
return json_dataModels.Set{
Uuid: set.Uuid, r := json_data.NewResponse()
Path: set.Path, r.Publish = append(r.Publish, publishes...)
}, nil
b, err := json.Marshal(r)
if err != nil {
return sets, err
}
ws.SendBroadcast(b)
return sets, nil
} }
return json_dataModels.Set{}, fmt.Errorf("datapoint '%s' not found", set.Path) return sets, fmt.Errorf("datapoint '%s' not found", set.Path)
}
// removes all children and grandchlidren of datapoint
func removeChildren(dp *Datapoint) (sets []json_dataModels.Set, pubs []json_dataModels.Publish) {
for name, d := range dp.Datapoints {
s, p := removeChildren(d)
sets = append(sets, s...)
pubs = append(pubs, p...)
sets = append(sets, json_dataModels.Set{
Uuid: d.Uuid,
Path: d.Path,
})
delete(d.Datapoints, name)
}
return sets, pubs
} }
func (d *Datapoint) GetAllDatapoints(depth uint) (dps Datapoints) { func (d *Datapoint) GetAllDatapoints(depth uint) (dps Datapoints) {
dps = append(dps, d)
if depth == 1 {
return
} else if depth > 0 {
depth--
}
var dfs func(dp *Datapoint, currentDepth uint) var dfs func(dp *Datapoint, currentDepth uint)
dfs = func(dp *Datapoint, currentDepth uint) { dfs = func(dp *Datapoint, currentDepth uint) {
if depth == 1 { switch depth {
return case 0:
} else if depth == 0 {
// Return all descendants // Return all descendants
for _, child := range dp.Datapoints { case currentDepth:
dps = append(dps, child)
dfs(child, currentDepth+1)
}
return
}
if currentDepth == depth-1 {
return return
} }
@@ -320,7 +390,7 @@ func (d *Datapoint) GetAllDatapoints(depth uint) (dps Datapoints) {
dfs(child, currentDepth+1) dfs(child, currentDepth+1)
} }
} }
dps = append(dps, d)
dfs(d, 0) dfs(d, 0)
dps.SortSlice() dps.SortSlice()
return return
@@ -331,8 +401,7 @@ func (d *Datapoint) QueryDatapoints(depth uint, path string) (dps Datapoints) {
var dfs func(current *Datapoint, index int) var dfs func(current *Datapoint, index int)
dfs = func(current *Datapoint, index int) { dfs = func(current *Datapoint, index int) {
if index == len(parts) || path == "" {
if index == len(parts) {
dps = append(dps, current.GetAllDatapoints(depth)...) dps = append(dps, current.GetAllDatapoints(depth)...)
return return
} }
@@ -355,17 +424,17 @@ func (d *Datapoint) QueryDatapoints(depth uint, path string) (dps Datapoints) {
return return
} }
func (d *Datapoint) AddSubscribtion(id string, sub json_dataModels.Subscription) { func (d *Datapoint) AddSubscribtion(conn *wsModels.Client, sub json_dataModels.Subscription) {
if d.Subscriptions == nil { if d.Subscriptions == nil {
return return
} }
if s, ok := d.Subscriptions[id]; ok { if s, ok := d.Subscriptions[conn]; ok {
s.OnCreate = sub.OnCreate s.OnCreate = sub.OnCreate
s.OnChange = sub.OnChange s.OnChange = sub.OnChange
s.OnDelete = sub.OnDelete s.OnDelete = sub.OnDelete
} else { } else {
d.Subscriptions[id] = &Subscription{ d.Subscriptions[conn] = &Subscription{
OnCreate: sub.OnCreate, OnCreate: sub.OnCreate,
OnChange: sub.OnChange, OnChange: sub.OnChange,
OnDelete: sub.OnDelete, OnDelete: sub.OnDelete,
@@ -373,35 +442,59 @@ func (d *Datapoint) AddSubscribtion(id string, sub json_dataModels.Subscription)
} }
} }
func (d *Datapoint) RemoveSubscribtion(id string) { func (d *Datapoint) RenamePaths(oldPath string) {
if _, ok := d.Subscriptions[id]; !ok { visited := make(map[*Datapoint]bool)
if len(d.Datapoints) == 0 {
return return
} }
delete(d.Subscriptions, id)
for _, dp := range d.Datapoints {
dp.Path = strings.Replace(dp.Path, oldPath, d.Path, 1)
dp.renameSubPaths(oldPath, d.Path, visited)
}
} }
func (d *Datapoint) Publish(conns *serverModels.Connections, eventType string) error { func (d *Datapoint) renameSubPaths(oldPath, newPath string, visited map[*Datapoint]bool) {
if conns.Clients == nil { if visited[d] {
return nil return
} }
conns.RLock() visited[d] = true
defer conns.RUnlock()
for id := range d.Subscriptions { if len(d.Datapoints) == 0 {
if _, ok := conns.Clients[id]; !ok { return
delete(d.Subscriptions, id) }
} else {
r := json_data.NewResponse()
r.AddUPublish(json_dataModels.Publish{
Event: eventType,
Uuid: d.Uuid,
Path: d.Path,
Value: d.Value,
})
if err := conns.SendResponse(id, r); err != nil { for _, dp := range d.Datapoints {
return err dp.Path = strings.Replace(dp.Path, oldPath, newPath, 1)
} dp.renameSubPaths(oldPath, newPath, visited)
}
}
func (d *Datapoint) RemoveSubscribtion(client *wsModels.Client) {
delete(d.Subscriptions, client)
}
func (d *Datapoint) Publish(eventType string) error {
r := json_data.NewResponse()
r.AddPublish(json_dataModels.Publish{
Event: eventType,
Uuid: d.Uuid,
Path: d.Path,
Type: d.Type,
Value: d.Value,
})
b, err := json.Marshal(r)
if err != nil {
return err
}
switch eventType {
case OnCreate, OnDelete:
ws.SendBroadcast(b)
default:
for client := range d.Subscriptions {
client.SendResponse(b)
} }
} }
return nil return nil

View File

@@ -5,30 +5,27 @@ import (
"runtime" "runtime"
"time" "time"
"maps"
"github.com/google/uuid" "github.com/google/uuid"
serverModels "github.com/tecamino/tecamino-dbm/server/models"
"github.com/tecamino/tecamino-dbm/utils" "github.com/tecamino/tecamino-dbm/utils"
ws "github.com/tecamino/tecamino-dbm/websocket"
json_dataModels "github.com/tecamino/tecamino-json_data/models" json_dataModels "github.com/tecamino/tecamino-json_data/models"
"github.com/tecamino/tecamino-logger/logging" "github.com/tecamino/tecamino-logger/logging"
) )
type DBM struct { type DBM struct {
Datapoints Datapoint Datapoints Datapoint
Uuids Uuids Uuids *Uuids
Conns *serverModels.Connections Conns *ws.ClientHandler
Log *logging.Logger Log *logging.Logger
} }
var SystemDatapoints uuid.UUID var SystemDatapoints uuid.UUID
func NewDBM(conns *serverModels.Connections, log *logging.Logger) *DBM { func NewDBM(conns *ws.ClientHandler, log *logging.Logger) *DBM {
return &DBM{ return &DBM{
Datapoints: Datapoint{}, Uuids: &Uuids{},
Uuids: make(Uuids), Conns: conns,
Conns: conns, Log: log,
Log: log,
} }
} }
@@ -37,11 +34,7 @@ func (d *DBM) CreateDatapoints(sets ...json_dataModels.Set) ([]json_dataModels.S
return nil, nil return nil, nil
} }
dps, uuids, err := d.Datapoints.CreateDatapoints(d.Conns, sets...) dps, err := d.Datapoints.CreateDatapoints(d.Uuids, sets...)
//save uuid in seperate map for fast look up
maps.Copy(d.Uuids, uuids)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -57,13 +50,12 @@ func (d *DBM) CreateDatapoints(sets ...json_dataModels.Set) ([]json_dataModels.S
return dps, nil return dps, nil
} }
func (d *DBM) ImportDatapoints(dps ...Datapoint) error { func (d *DBM) ImportDatapoints(dps ...*Datapoint) error {
for _, dp := range dps { for _, dp := range dps {
uuids, err := d.Datapoints.ImportDatapoint(d.Conns, dp, dp.Path) err := d.Datapoints.ImportDatapoint(d.Uuids, dp, dp.Path)
if err != nil { if err != nil {
return err return err
} }
maps.Copy(d.Uuids, uuids)
d.ModifyCountedDatapoints(1, false) d.ModifyCountedDatapoints(1, false)
} }
@@ -72,44 +64,48 @@ func (d *DBM) ImportDatapoints(dps ...Datapoint) error {
func (d *DBM) UpdateDatapointValue(value any, uid uuid.UUID, path ...string) error { func (d *DBM) UpdateDatapointValue(value any, uid uuid.UUID, path ...string) error {
if uid != uuid.Nil { if uid != uuid.Nil {
if _, ok := d.Uuids[uid]; !ok { dp := d.Uuids.GetDatapoint(uid)
if dp == nil {
return fmt.Errorf("uuid %s not found", uid.String()) return fmt.Errorf("uuid %s not found", uid.String())
} }
dp := d.Uuids[uid]
dp.Value = dp.Type.ConvertValue(value) dp.Value = dp.Type.ConvertValue(value)
dp.UpdateDateTime = time.Now().UnixMilli() dp.UpdateDateTime = time.Now().UnixMilli()
dp.Publish(d.Conns, OnChange) dp.Publish(OnChange)
} }
if len(path) > 1 { if len(path) > 1 {
return fmt.Errorf("only one path allowed") return fmt.Errorf("only one path allowed")
} }
return d.Datapoints.UpdateDatapointValue(d.Conns, value, path[0]) return d.Datapoints.UpdateDatapointValue(value, path[0])
} }
func (d *DBM) RemoveDatapoint(sets ...json_dataModels.Set) ([]json_dataModels.Set, error) { func (d *DBM) RemoveDatapoint(sets ...json_dataModels.Set) (lsRemoved []json_dataModels.Set, err error) {
var lsRemoved []json_dataModels.Set
for _, set := range sets { for _, set := range sets {
removed, err := d.Datapoints.RemoveDatapoint(d.Conns, set) if set.Path == "" {
if err != nil { if dp := d.Uuids.GetDatapoint(set.Uuid); dp != nil {
return lsRemoved, err set.Path = dp.Path
}
} }
lsRemoved = append(lsRemoved, removed)
d.ModifyCountedDatapoints(1, true)
}
return lsRemoved, nil lsRemoved, err = d.Datapoints.RemoveDatapoint(set)
if err != nil {
return
}
d.ModifyCountedDatapoints(uint64(len(lsRemoved)), true)
}
return
} }
func (d *DBM) QueryDatapoints(depth uint, uid uuid.UUID, key ...string) []*Datapoint { func (d *DBM) QueryDatapoints(depth uint, uid uuid.UUID, key ...string) []*Datapoint {
if uid != uuid.Nil { if uid != uuid.Nil {
if _, ok := d.Uuids[uid]; !ok { dp := d.Uuids.GetDatapoint(uid)
if dp == nil {
return nil return nil
} else if depth == 1 {
return []*Datapoint{dp}
} }
dp := d.Uuids[uid] return append([]*Datapoint{}, dp.QueryDatapoints(depth, key[0])...)
dps := []*Datapoint{dp}
return append(dps, dp.QueryDatapoints(depth, key[0])...)
} }
return d.Datapoints.QueryDatapoints(depth, key[0]) return d.Datapoints.QueryDatapoints(depth, key[0])
} }
@@ -135,7 +131,6 @@ func (d *DBM) ModifyCountedDatapoints(count uint64, countDown bool) {
func (d *DBM) GoSystemTime() error { func (d *DBM) GoSystemTime() error {
path := "System:Time" path := "System:Time"
var tOld int64
typ := json_dataModels.STR typ := json_dataModels.STR
rights := json_dataModels.Read rights := json_dataModels.Read
@@ -146,15 +141,12 @@ func (d *DBM) GoSystemTime() error {
} }
go func() { go func() {
for { ticker := time.NewTicker(time.Second)
t := time.Now().UnixMilli() for range ticker.C {
if tOld != t { if er := d.UpdateDatapointValue(time.Now().Format("2006-01-02 15:04:05"), uuid.Nil, path); er != nil {
if er := d.UpdateDatapointValue(time.UnixMilli(t).Format("2006-01-02 15:04:05"), uuid.Nil, path); er != nil { d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
}
tOld = t
} }
time.Sleep(time.Second)
} }
}() }()
return nil return nil
@@ -162,8 +154,6 @@ func (d *DBM) GoSystemTime() error {
func (d *DBM) GoSystemMemory() error { func (d *DBM) GoSystemMemory() error {
path := "System:UsedMemory" path := "System:UsedMemory"
var m runtime.MemStats
var mOld uint64
typ := json_dataModels.STR typ := json_dataModels.STR
rights := json_dataModels.Read rights := json_dataModels.Read
@@ -175,13 +165,11 @@ func (d *DBM) GoSystemMemory() error {
go func() { go func() {
for { for {
var m runtime.MemStats
runtime.ReadMemStats(&m) runtime.ReadMemStats(&m)
if m.Sys != mOld { mem := fmt.Sprintf("%.2f MB", float64(m.Alloc)/1024/1024)
mem := fmt.Sprintf("%.2f MB", float64(m.Sys)/1024/1024) if er := d.UpdateDatapointValue(mem, uuid.Nil, path); er != nil {
if er := d.UpdateDatapointValue(mem, uuid.Nil, path); er != nil { d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
d.Log.Error("dmb.Handler.AddSystemDps.UpdateDatapointValue", er.Error())
}
mOld = m.Sys
} }
time.Sleep(time.Second) time.Sleep(time.Second)
} }

View File

@@ -1,6 +1,7 @@
package models package models
type Port struct { type Port struct {
Http uint Http uint
Https uint Https uint
Remote uint
} }

14
models/stringSlices.go Normal file
View File

@@ -0,0 +1,14 @@
package models
import "strings"
type StringSlice []string
func (s *StringSlice) String() string {
return strings.Join(*s, ",")
}
func (s *StringSlice) Set(value string) error {
*s = append(*s, value)
return nil
}

View File

@@ -1,6 +1,8 @@
package models package models
type Subscriptions map[string]*Subscription import wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
type Subscriptions map[*wsModels.Client]*Subscription
type Subscription struct { type Subscription struct {
OnCreate bool OnCreate bool

View File

@@ -1,5 +1,52 @@
package models package models
import "github.com/google/uuid" import (
"fmt"
"github.com/google/uuid"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
)
type Uuids map[uuid.UUID]*Datapoint type Uuids map[uuid.UUID]*Datapoint
func NewUuids() *Uuids {
return &Uuids{}
}
func (u *Uuids) AddDatapoint(parentDp, newDp *Datapoint) {
if odp, ok := (*u)[newDp.Uuid]; ok {
if odp.Path == newDp.Path {
return
}
newDp.Datapoints = odp.Datapoints
newDp.HasChild = len(odp.Datapoints) > 0
odp.Datapoints = map[string]*Datapoint{}
newDp.RenamePaths(odp.Path)
rmDps, _ := parentDp.RemoveDatapoint(json_dataModels.Set{Path: odp.Path})
datapoints := u.GetDatapointByPath("System:Datapoints")
datapoints.UpdateValue(datapoints.Value.(uint64) - uint64(len(rmDps)))
fmt.Println(11, newDp.HasChild)
}
(*u)[newDp.Uuid] = newDp
}
func (u *Uuids) GetDatapoint(uuid uuid.UUID) *Datapoint {
if dp, ok := (*u)[uuid]; ok {
return dp
}
return nil
}
func (u *Uuids) GetDatapointByPath(path string) *Datapoint {
for _, dp := range *u {
if dp.Path == path {
return dp
}
}
return nil
}
func (u *Uuids) RemoveDatapoint(uuid uuid.UUID) {
delete(*u, uuid)
}

View File

@@ -1,58 +0,0 @@
package models
import (
"context"
"fmt"
"github.com/coder/websocket"
"github.com/gin-gonic/gin"
)
var Origins []string = []string{"*"}
type Clients map[string]*Client
type Client struct {
Ctx context.Context `json:"-"`
Cancel context.CancelFunc `json:"-"`
Connected bool `json:"connected"`
Conn *websocket.Conn `json:"-"`
}
func NewClients() Clients {
return make(Clients)
}
// Connect a recieving websocket connection
func (cl *Clients) ConnectRecievingWsConnection(id string, c *gin.Context) error {
if _, exists := (*cl)[id]; exists {
return nil
}
conn, err := websocket.Accept(c.Writer, c.Request, &websocket.AcceptOptions{
OriginPatterns: Origins,
})
if err != nil {
return fmt.Errorf("error accept websocket client: %s", err)
}
ctx, cancel := context.WithCancel(context.Background())
(*cl)[id] = &Client{
Connected: true,
Ctx: ctx,
Cancel: cancel,
Conn: conn,
}
return nil
}
func (c *Clients) RemoveClient(id string) {
delete(*c, id)
}
func (c *Clients) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
(*c)[id].Connected = false
(*c)[id].Conn.Close(code, reason)
(*c)[id].Cancel()
}

View File

@@ -1,67 +0,0 @@
package models
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/coder/websocket"
"github.com/gin-gonic/gin"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
)
// serves as connection handler of websocket
type Connections struct {
sync.RWMutex
Clients Clients
}
// initaiates new conections with client map
func NewConnections() *Connections {
return &Connections{
Clients: NewClients(),
}
}
// Connect a recieving websocket connection
func (c *Connections) ConnectRecievingWsConnection(id string, ctx *gin.Context) error {
return c.Clients.ConnectRecievingWsConnection(id, ctx)
}
func (c *Connections) RemoveClient(id string) {
c.Clients.RemoveClient(id)
}
func (c *Connections) DisconnectWsConnection(id string, code websocket.StatusCode, reason string) {
c.Clients.DisconnectWsConnection(id, code, reason)
}
// sends json response to client
func (c *Connections) SendResponse(id string, r *json_dataModels.Response) error {
client, ok := c.Clients[id]
if !ok {
return fmt.Errorf("client not found for id %s", id)
}
b, err := json.Marshal(r)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
w, err := client.Conn.Writer(ctx, websocket.MessageText)
if err != nil {
return err
}
defer w.Close()
_, err = w.Write(b)
if err != nil {
return err
}
return nil
}

View File

@@ -1,38 +0,0 @@
package server
import (
"fmt"
"sync"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/cert"
"github.com/tecamino/tecamino-logger/logging"
)
// server model for database manager websocket
type Server struct {
Routes *gin.Engine
sync.RWMutex
Logger *logging.Logger
}
// initalizes new dbm server
func NewServer() *Server {
return &Server{
Routes: gin.Default(),
}
}
// serve dbm as http
func (s *Server) ServeHttp(port uint) error {
return s.Routes.Run(fmt.Sprintf(":%d", port))
}
// serve dbm as http
func (s *Server) ServeHttps(port uint, cert cert.Cert) error {
// generate self signed tls certificate
if err := cert.GenerateSelfSignedCert(); err != nil {
return err
}
return s.Routes.RunTLS(fmt.Sprintf(":%d", port), cert.CertFile, cert.KeyFile)
}

View File

@@ -12,8 +12,8 @@ import (
"github.com/tecamino/tecamino-dbm/cert" "github.com/tecamino/tecamino-dbm/cert"
"github.com/tecamino/tecamino-dbm/dbm" "github.com/tecamino/tecamino-dbm/dbm"
"github.com/tecamino/tecamino-dbm/models" "github.com/tecamino/tecamino-dbm/models"
"github.com/tecamino/tecamino-dbm/server"
"github.com/tecamino/tecamino-dbm/utils" "github.com/tecamino/tecamino-dbm/utils"
ws "github.com/tecamino/tecamino-dbm/websocket"
) )
func TestCreateDps(t *testing.T) { func TestCreateDps(t *testing.T) {
@@ -142,7 +142,7 @@ func TestUpdateDps(t *testing.T) {
func TestServer(t *testing.T) { func TestServer(t *testing.T) {
fmt.Println("start") fmt.Println("start")
server := server.NewServer() server := ws.NewServer([]string{".*"}, 9500)
t.Fatal(server.ServeHttp(8100)) t.Fatal(server.ServeHttp("http://localhost", 8100))
} }

View File

@@ -1,5 +1,10 @@
package utils package utils
import (
"fmt"
"net"
)
func ListofA2ZZ() (list []string) { func ListofA2ZZ() (list []string) {
for i := 'A'; i <= 'Z'; i++ { for i := 'A'; i <= 'Z'; i++ {
list = append(list, string(i)) list = append(list, string(i))
@@ -9,12 +14,21 @@ func ListofA2ZZ() (list []string) {
list = append(list, string(i)+string(j)) list = append(list, string(i)+string(j))
} }
} }
// for i := 'A'; i <= 'Z'; i++ {
// for j := 'A'; j <= 'Z'; j++ {
// for k := 'A'; k <= 'Z'; k++ {
// list = append(list, string(i)+string(j)+string(k))
// }
// }
// }
return return
} }
func GetLocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
if ipNet, ok := addr.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
if ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
}
return "", fmt.Errorf("no local IP address found")
}

View File

@@ -0,0 +1,77 @@
package websocket
import (
"encoding/json"
"fmt"
"sync"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/websocket/models"
wsModels "github.com/tecamino/tecamino-dbm/websocket/models"
json_dataModels "github.com/tecamino/tecamino-json_data/models"
)
// serves as connection handler of websocket
type ClientHandler struct {
sync.RWMutex
Clients models.Clients
}
func SendBroadcast(msg []byte) {
for _, c := range models.Broadcast {
c.SendResponse(msg)
}
}
// initaiates new conections with client map
func NewConnectionHandler() *ClientHandler {
return &ClientHandler{
Clients: make(models.Clients),
}
}
// Connect a recieving websocket connection
func (cH *ClientHandler) ConnectNewClient(id string, c *gin.Context) (client *models.Client, err error) {
if _, exists := cH.Clients[id]; exists {
return cH.Clients[id], nil
}
client, err = models.ConnectNewClient(id, c)
client.OnClose = func(code int, reason string) {
fmt.Println(23, "closing", id)
delete(cH.Clients, id)
}
if err != nil {
return nil, err
}
cH.Lock()
cH.Clients[id] = client
cH.Unlock()
return client, nil
}
// get client client
func (c *ClientHandler) GetClient(id string) *wsModels.Client {
if client, ok := c.Clients[id]; ok {
return client
}
return nil
}
// sends json response to client
func (c *ClientHandler) SendResponse(id string, r *json_dataModels.Response) error {
client, ok := c.Clients[id]
if !ok {
return fmt.Errorf("client not found for id %s", id)
}
b, err := json.Marshal(*r)
if err != nil {
return err
}
client.SendResponse(b)
return nil
}

222
websocket/models/client.go Normal file
View File

@@ -0,0 +1,222 @@
package models
import (
"fmt"
"log"
"net/http"
"slices"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var Origins []string = []string{"*"}
var Broadcast Clients = make(Clients)
const (
// Time allowed to write a message to the peer.
writeWait = 30 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 40 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
)
type Client struct {
Id string
Connected bool `json:"connected"`
conn *websocket.Conn `json:"-"`
OnOpen func()
OnMessage func(data []byte)
OnClose func(code int, reason string)
OnError func(err error)
OnWarning func(warn string)
OnPing func()
OnPong func()
send chan []byte
unregister chan []byte
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
if len(Origins) == 0 {
return false
} else if Origins[0] == "*" {
return true
}
return slices.Contains(Origins, r.Header.Get("Origin"))
},
EnableCompression: false,
}
func ConnectNewClient(id string, c *gin.Context) (*Client, error) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return nil, fmt.Errorf("websocket upgrade error: %w", err)
}
client := &Client{
Id: id,
Connected: true,
conn: conn,
send: make(chan []byte, 512),
unregister: make(chan []byte, 256),
}
Broadcast[client.Id] = client
conn.SetPingHandler(func(appData string) error {
if client.OnPing != nil {
client.OnPing()
}
conn.SetWriteDeadline(time.Now().Add(writeWait))
conn.SetReadDeadline(time.Now().Add(writeWait))
if err := client.conn.WriteControl(websocket.PongMessage, []byte(appData), time.Now().Add(pongWait)); err != nil {
client.OnError(err)
}
return nil
})
conn.SetPongHandler(func(appData string) error {
conn.SetReadDeadline(time.Now().Add(pongWait))
if client.OnPong != nil {
client.OnPong()
}
return nil
})
// Start reading messages from client
go client.Read()
go client.Write()
go client.PingInterval(pingPeriod)
return client, nil
}
func (c *Client) Read() {
if c.OnOpen != nil {
c.OnOpen()
}
c.conn.SetReadDeadline(time.Now().Add(writeWait))
for c.Connected {
msgType, msg, err := c.conn.ReadMessage()
if err != nil {
c.handleError(fmt.Errorf("read error (id:%s): %w", c.Id, err))
return
}
switch msgType {
case websocket.CloseMessage:
c.Close(websocket.CloseNormalClosure, "Client closed")
return
case websocket.TextMessage:
if c.OnMessage != nil {
c.OnMessage(msg)
} else {
log.Printf("Received message but no handler set (id:%s): %s", c.Id, string(msg))
}
default:
log.Printf("Unhandled message type %d (id:%s)", msgType, c.Id)
}
}
}
func (c *Client) Write() {
defer c.conn.Close()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// The hub closed the channel.
if err := c.conn.WriteMessage(websocket.CloseMessage, []byte("ping")); err != nil {
c.handleError(err)
return
}
c.handleError(fmt.Errorf("server %s closed channel", c.Id))
return
} else {
if err := c.conn.WriteMessage(websocket.TextMessage, message); err != nil {
c.handleError(err)
return
}
}
case message := <-c.unregister:
c.conn.WriteMessage(websocket.CloseMessage, message)
c.Connected = false
close(c.send)
delete(Broadcast, c.Id)
close(c.unregister)
return
}
}
}
func (c *Client) PingInterval(interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
if err := c.conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(pongWait)); err != nil {
c.OnError(err)
return
}
for range ticker.C {
if c.OnPing != nil {
c.OnPing()
}
if err := c.conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(pongWait)); err != nil {
c.OnError(err)
return
}
}
}
func (c *Client) SendResponse(data []byte) {
if !c.Connected {
return
}
select {
case c.send <- data:
// sent successfully
default:
// channel full, drop or log
if c.OnWarning != nil {
c.OnWarning("Dropping message: channel full")
}
}
}
func (c *Client) Close(code int, reason string) error {
closeMsg := websocket.FormatCloseMessage(code, reason)
select {
case c.unregister <- closeMsg: // Attempt to send
default: // If the channel is full, this runs
return fmt.Errorf("attempt close client socket failed")
}
if c.OnClose != nil {
c.OnClose(code, reason)
}
return nil
}
func (c *Client) handleError(err error) {
if c.OnError != nil {
c.OnError(err)
}
if err := c.Close(websocket.CloseInternalServerErr, err.Error()); err != nil {
if c.OnError != nil {
c.OnError(err)
} else {
fmt.Println("error: ", err)
}
}
}

View File

@@ -0,0 +1,3 @@
package models
type Clients map[string]*Client

View File

@@ -0,0 +1,21 @@
package models
import "encoding/json"
type WSMessage struct {
Type string `json:"type"`
}
func GetPongByteSlice() []byte {
b, err := json.Marshal(WSMessage{
Type: "pong",
})
if err != nil {
return []byte{}
}
return b
}
func (w WSMessage) IsPing() bool {
return w.Type == "ping"
}

60
websocket/server.go Normal file
View File

@@ -0,0 +1,60 @@
package websocket
import (
"fmt"
"log"
"sync"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/tecamino/tecamino-dbm/cert"
"github.com/tecamino/tecamino-dbm/utils"
"github.com/tecamino/tecamino-logger/logging"
)
// server model for database manager websocket
type Server struct {
Routes *gin.Engine
sync.RWMutex
Logger *logging.Logger
}
// initalizes new dbm server
func NewServer(allowOrigins []string, port uint) *Server {
r := gin.Default()
allowOrigins = append(allowOrigins, fmt.Sprintf("http://localhost:%d", port))
localIP, err := utils.GetLocalIP()
if err != nil {
log.Printf("get local ip : %s", err.Error())
} else {
allowOrigins = append(allowOrigins, fmt.Sprintf("http://%s:%d", localIP, port))
}
r.Use(cors.New(cors.Config{
AllowOrigins: allowOrigins,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
return &Server{
Routes: r,
}
}
// serve dbm as http
func (s *Server) ServeHttp(ip string, port uint) error {
return s.Routes.Run(fmt.Sprintf("%s:%d", ip, port))
}
// serve dbm as http
func (s *Server) ServeHttps(ip string, port uint, cert cert.Cert) error {
// generate self signed tls certificate
if err := cert.GenerateSelfSignedCert(); err != nil {
return err
}
return s.Routes.RunTLS(fmt.Sprintf("%s:%d", ip, port), cert.CertFile, cert.KeyFile)
}