Files
webterm/go/webterm/twoway.go
T
GitHub Copilot fd6c1c4e0d feat: complete Go port with go-te terminal emulator
Full Go implementation under go/ replacing Python pyte with go-te:
- HTTP server with WebSocket protocol, SSE, screenshot SVG rendering
- PTY terminal sessions and Docker exec sessions
- Docker watcher (label-based container discovery + event stream)
- CPU stats collection with sparkline SVG rendering
- Session manager with TwoWayMap routing and replay buffers
- C1 normalization, DA filtering, identity generation, theme palettes

Audit fixes for 9 concurrency/correctness issues:
- HTTP transport leak: shared client pool for Docker socket calls
- WebSocket concurrent writes: all writes routed through send channel
- Closed channel panic: atomic.Bool guard on enqueueWSData
- GetFirstRunningSession: use UnsafeForward under SessionManager lock
- NewSession TOCTOU: re-check routeKey after re-acquiring lock
- waitErr data race: protect with mutex in both session types
- Replay buffer fragmentation: copy to new slice on eviction
- go-te dirty tracking: check screen.Dirty before incrementing counter
- Identity modulo bias: rejection sampling for uniform distribution

All Go tests pass (including -race). Python baseline unchanged (397 tests).

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-02-14 16:18:23 +00:00

73 lines
1.4 KiB
Go

package webterm
import (
"fmt"
"sync"
)
type TwoWayMap[K comparable, V comparable] struct {
mu sync.RWMutex
forward map[K]V
reverse map[V]K
}
func NewTwoWayMap[K comparable, V comparable]() *TwoWayMap[K, V] {
return &TwoWayMap[K, V]{
forward: map[K]V{},
reverse: map[V]K{},
}
}
func (m *TwoWayMap[K, V]) Set(key K, value V) error {
m.mu.Lock()
defer m.mu.Unlock()
if old, ok := m.forward[key]; ok && old != value {
delete(m.reverse, old)
}
if existingKey, ok := m.reverse[value]; ok && existingKey != key {
return fmt.Errorf("value already mapped")
}
m.forward[key] = value
m.reverse[value] = key
return nil
}
func (m *TwoWayMap[K, V]) DeleteKey(key K) {
m.mu.Lock()
defer m.mu.Unlock()
if value, ok := m.forward[key]; ok {
delete(m.forward, key)
delete(m.reverse, value)
}
}
func (m *TwoWayMap[K, V]) Get(key K) (V, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
v, ok := m.forward[key]
return v, ok
}
func (m *TwoWayMap[K, V]) GetKey(value V) (K, bool) {
m.mu.RLock()
defer m.mu.RUnlock()
k, ok := m.reverse[value]
return k, ok
}
func (m *TwoWayMap[K, V]) Keys() []K {
m.mu.RLock()
defer m.mu.RUnlock()
keys := make([]K, 0, len(m.forward))
for key := range m.forward {
keys = append(keys, key)
}
return keys
}
// UnsafeForward returns the forward map directly. Caller must hold external synchronization.
func (m *TwoWayMap[K, V]) UnsafeForward() map[K]V {
return m.forward
}