v0.3: WebRTC P2P via Pion (Go) + RTCPeerConnection (browser)

Server: unchanged shape, just added a "signal" message type to the
existing /api/send + /api/stream bus. Now carries both "clipboard"
(payload) and "signal" (offer/answer/ICE) over the same envelope.

Client: -rtc flag turns the Go listener into a Pion peer. Posts an SDP
offer at startup, accepts the browser's answer through the signaling
bus, exchanges ICE, then receives clipboard text over a DataChannel
named "tether". On message: writes to OS clipboard same as SSE path.

Web UI: acts as the answerer. Listens for "signal" SSE events, replies
to offers, exchanges ICE. When DataChannel opens, the send button uses
RTCDataChannel.send() instead of POST /api/send — data no longer
traverses the server after pairing. Pill in the header flips
sse → negotiating → rtc to make this visible.

Toolchain: bumped go.mod to go 1.26, switched to pion/webrtc v4 and
prometheus/client_golang v1.23.x.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Claude Opus 4.7
2026-05-21 00:37:31 -05:00
parent 80539ae60c
commit 98dc2ca2a6
5 changed files with 421 additions and 301 deletions

View File

@@ -1,7 +1,10 @@
// tether-server: HTTP+SSE relay for phone↔client clipboard sync.
// tether-server v0.3: HTTP+SSE relay with extensible message envelope.
//
// v0.1: SSE-only relay with broadcast bus.
// v0.2 (this): /metrics endpoint + signaling stubs (mailbox for WebRTC SDP/ICE).
// The same /api/send + /api/stream pipeline carries TWO message kinds:
// - "clipboard" — the user-facing payload (text)
// - "signal" — WebRTC SDP/ICE for peer negotiation
//
// Peers filter by .Type on the client side. Server is neutral relay.
package main
import (
@@ -23,10 +26,14 @@ import (
//go:embed web/index.html
var webFS embed.FS
// Message envelope. Type defaults to "clipboard" for backward compat.
type Message struct {
Text string `json:"text"`
Source string `json:"source,omitempty"`
TS int64 `json:"ts"`
Type string `json:"type,omitempty"` // "clipboard" | "signal"
Text string `json:"text,omitempty"` // clipboard text
Signal json.RawMessage `json:"signal,omitempty"` // {kind:offer|answer|ice, ...}
From string `json:"from,omitempty"` // sender peer id (for signal filtering)
Source string `json:"source,omitempty"` // human-readable label
TS int64 `json:"ts"`
}
type bus struct {
@@ -38,13 +45,16 @@ type bus struct {
func newBus() *bus { return &bus{clients: map[chan Message]string{}} }
func (b *bus) subscribe(label string) chan Message {
ch := make(chan Message, 16)
ch := make(chan Message, 32)
b.mu.Lock()
b.clients[ch] = label
// only replay clipboard messages — signals are time-sensitive
for _, m := range b.history {
select {
case ch <- m:
default:
if m.Type == "" || m.Type == "clipboard" {
select {
case ch <- m:
default:
}
}
}
b.mu.Unlock()
@@ -63,9 +73,11 @@ func (b *bus) unsubscribe(ch chan Message) {
func (b *bus) publish(m Message) {
b.mu.Lock()
defer b.mu.Unlock()
b.history = append(b.history, m)
if len(b.history) > 10 {
b.history = b.history[len(b.history)-10:]
if m.Type == "" || m.Type == "clipboard" {
b.history = append(b.history, m)
if len(b.history) > 10 {
b.history = b.history[len(b.history)-10:]
}
}
for ch := range b.clients {
select {
@@ -75,16 +87,15 @@ func (b *bus) publish(m Message) {
}
}
// Prometheus metrics --------------------------------------------------------
// Prometheus metrics
var (
messages = promauto.NewCounterVec(prometheus.CounterOpts{
Name: "tether_messages_total",
Help: "Total messages published to the broadcast bus, by source label.",
}, []string{"source"})
Help: "Total messages published to the broadcast bus, by source and type.",
}, []string{"source", "type"})
bytesIn = promauto.NewCounter(prometheus.CounterOpts{
Name: "tether_message_bytes_total",
Help: "Total bytes of message text published.",
Help: "Total bytes of clipboard text published.",
})
subscribers = promauto.NewGauge(prometheus.GaugeOpts{
Name: "tether_active_subscribers",
@@ -93,46 +104,15 @@ var (
publishLatency = promauto.NewHistogram(prometheus.HistogramOpts{
Name: "tether_publish_duration_seconds",
Help: "Latency of the publish() fan-out, including channel sends.",
Buckets: prometheus.ExponentialBuckets(0.0001, 4, 8), // 0.1ms..1.6s
Buckets: prometheus.ExponentialBuckets(0.0001, 4, 8),
})
)
// Signaling mailbox (v0.3 WebRTC scaffolding) --------------------------------
// Peers POST offers/answers/ICE candidates into a per-room mailbox, peers GET
// to drain. Pure relay — no SDP parsing, no peer state on server.
type signalBox struct {
mu sync.Mutex
rooms map[string][]json.RawMessage
}
func newSignalBox() *signalBox { return &signalBox{rooms: map[string][]json.RawMessage{}} }
func (s *signalBox) post(room string, msg json.RawMessage) {
s.mu.Lock()
defer s.mu.Unlock()
s.rooms[room] = append(s.rooms[room], msg)
if len(s.rooms[room]) > 64 {
s.rooms[room] = s.rooms[room][len(s.rooms[room])-64:]
}
}
func (s *signalBox) drain(room string) []json.RawMessage {
s.mu.Lock()
defer s.mu.Unlock()
out := s.rooms[room]
delete(s.rooms, room)
return out
}
// ---------------------------------------------------------------------------
func main() {
addr := flag.String("addr", ":8765", "listen address")
flag.Parse()
b := newBus()
sig := newSignalBox()
sub, _ := fs.Sub(webFS, "web")
mux := http.NewServeMux()
@@ -149,6 +129,9 @@ func main() {
http.Error(w, "bad json", http.StatusBadRequest)
return
}
if m.Type == "" {
m.Type = "clipboard"
}
if m.Source == "" {
m.Source = r.Header.Get("X-Tether-Source")
if m.Source == "" {
@@ -160,9 +143,13 @@ func main() {
t0 := time.Now()
b.publish(m)
publishLatency.Observe(time.Since(t0).Seconds())
messages.WithLabelValues(m.Source).Inc()
bytesIn.Add(float64(len(m.Text)))
log.Printf("publish: %s len=%d", m.Source, len(m.Text))
messages.WithLabelValues(m.Source, m.Type).Inc()
if m.Type == "clipboard" {
bytesIn.Add(float64(len(m.Text)))
log.Printf("publish clipboard: %s len=%d", m.Source, len(m.Text))
} else {
log.Printf("publish %s: from=%s", m.Type, m.From)
}
w.WriteHeader(http.StatusNoContent)
})
@@ -195,7 +182,11 @@ func main() {
return
case m := <-ch:
bs, _ := json.Marshal(m)
fmt.Fprintf(w, "event: clipboard\ndata: %s\n\n", bs)
eventName := m.Type
if eventName == "" {
eventName = "clipboard"
}
fmt.Fprintf(w, "event: %s\ndata: %s\n\n", eventName, bs)
fl.Flush()
case <-ka.C:
fmt.Fprintf(w, ": keepalive\n\n")
@@ -204,35 +195,6 @@ func main() {
}
})
// WebRTC signaling: POST to add a message, GET to drain.
// /api/signal/<room> is a dumb relay — peers exchange SDP + ICE via this.
mux.HandleFunc("/api/signal/", func(w http.ResponseWriter, r *http.Request) {
room := r.URL.Path[len("/api/signal/"):]
if room == "" {
http.Error(w, "missing room", http.StatusBadRequest)
return
}
switch r.Method {
case http.MethodPost:
body, _ := func() (json.RawMessage, error) {
var raw json.RawMessage
err := json.NewDecoder(r.Body).Decode(&raw)
return raw, err
}()
sig.post(room, body)
w.WriteHeader(http.StatusNoContent)
case http.MethodGet:
out := sig.drain(room)
if out == nil {
out = []json.RawMessage{}
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(out)
default:
http.Error(w, "POST or GET", http.StatusMethodNotAllowed)
}
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})