mirror of
https://github.com/hanzoai/compute.git
synced 2026-10-30 14:50:41 +00:00
Modules declare go 1.27.1 and the build images follow. go fix applied the modernizers; omitzero is not applied, since it changes what the JSON says. Co-authored-by: Hanzo Dev <[email protected]>
118 lines
2.3 KiB
Go
118 lines
2.3 KiB
Go
// Copyright 2024 Hanzo Industries Inc. All Rights Reserved.
|
|
//
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
// you may not use this file except in compliance with the License.
|
|
// You may obtain a copy of the License at
|
|
//
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
//
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
// See the License for the specific language governing permissions and
|
|
// limitations under the License.
|
|
|
|
package guacamole
|
|
|
|
import (
|
|
"sync"
|
|
|
|
"github.com/zap-proto/zip/wsx"
|
|
)
|
|
|
|
type Session struct {
|
|
Id string
|
|
Protocol string
|
|
Mode string
|
|
WebSocket *wsx.Conn
|
|
GuacdTunnel *Tunnel
|
|
Observer *Manager
|
|
mutex sync.Mutex
|
|
|
|
Uptime int64
|
|
Hostname string
|
|
}
|
|
|
|
func (s *Session) WriteString(str string) error {
|
|
if s.WebSocket == nil {
|
|
return nil
|
|
}
|
|
defer s.mutex.Unlock()
|
|
s.mutex.Lock()
|
|
message := []byte(str)
|
|
return s.WebSocket.WriteMessage(wsx.TextMessage, message)
|
|
}
|
|
|
|
func (s *Session) Close() {
|
|
if s.GuacdTunnel != nil {
|
|
_ = s.GuacdTunnel.Close()
|
|
}
|
|
|
|
if s.WebSocket != nil {
|
|
_ = s.WebSocket.Close()
|
|
}
|
|
}
|
|
|
|
type Manager struct {
|
|
id string
|
|
sessions sync.Map
|
|
}
|
|
|
|
func NewManager() *Manager {
|
|
return &Manager{}
|
|
}
|
|
|
|
func NewObserver(id string) *Manager {
|
|
return &Manager{
|
|
id: id,
|
|
}
|
|
}
|
|
|
|
func (m *Manager) Get(id string) *Session {
|
|
value, ok := m.sessions.Load(id)
|
|
if ok {
|
|
return value.(*Session)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (m *Manager) Add(s *Session) {
|
|
m.sessions.Store(s.Id, s)
|
|
}
|
|
|
|
func (m *Manager) Delete(id string) {
|
|
session := m.Get(id)
|
|
if session != nil {
|
|
session.Close()
|
|
if session.Observer != nil {
|
|
session.Observer.Clear()
|
|
}
|
|
}
|
|
m.sessions.Delete(id)
|
|
}
|
|
|
|
func (m *Manager) Clear() {
|
|
m.sessions.Range(func(key, value any) bool {
|
|
if session, ok := value.(*Session); ok {
|
|
session.Close()
|
|
}
|
|
m.sessions.Delete(key)
|
|
return true
|
|
})
|
|
}
|
|
|
|
func (m *Manager) Range(f func(key string, value *Session)) {
|
|
m.sessions.Range(func(key, value any) bool {
|
|
if session, ok := value.(*Session); ok {
|
|
f(key.(string), session)
|
|
}
|
|
return true
|
|
})
|
|
}
|
|
|
|
var GlobalSessionManager *Manager
|
|
|
|
func init() {
|
|
GlobalSessionManager = NewManager()
|
|
}
|