-
Notifications
You must be signed in to change notification settings - Fork 85
/
Copy pathwsconnection.go
45 lines (36 loc) · 1.08 KB
/
wsconnection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package server
import (
"context"
"net"
"sync"
"sync/atomic"
"github.com/gorilla/websocket"
"github.com/open-telemetry/opamp-go/internal"
"github.com/open-telemetry/opamp-go/protobufs"
"github.com/open-telemetry/opamp-go/server/types"
)
// wsConnection represents a persistent OpAMP connection over a WebSocket.
type wsConnection struct {
// The websocket library does not allow multiple concurrent write operations,
// so ensure that we only have a single operation in progress at a time.
// For more: https://pkg.go.dev/github.com/gorilla/websocket#hdr-Concurrency
connMutex *sync.Mutex
wsConn *websocket.Conn
closed *atomic.Bool
}
var _ types.Connection = (*wsConnection)(nil)
func (c wsConnection) Connection() net.Conn {
return c.wsConn.UnderlyingConn()
}
func (c wsConnection) Send(_ context.Context, message *protobufs.ServerToAgent) error {
c.connMutex.Lock()
defer c.connMutex.Unlock()
return internal.WriteWSMessage(c.wsConn, message)
}
func (c wsConnection) Disconnect() error {
if c.closed.Load() {
return nil
}
c.closed.Store(true)
return c.wsConn.Close()
}