chore: bootstrap api-go scaffold
This commit is contained in:
1 parent
aa26549bd1
commit
907164f972
18 files changed
+1919
No files matched your search
@@ -0,0 +1,92 @@
|
||||
// Package sse is a small fan-out hub for Server-Sent Events.
|
||||
package sse
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Event is one SSE message. ID is omitted when zero.
|
||||
type Event struct {
|
||||
Name string
|
||||
ID int
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Hub fans events out to every subscribed client and emits a heartbeat.
|
||||
type Hub struct {
|
||||
heartbeat time.Duration
|
||||
|
||||
mu sync.RWMutex
|
||||
clients map[chan Event]struct{}
|
||||
}
|
||||
|
||||
// NewHub returns a hub that pings every heartbeat (15 s in production).
|
||||
func NewHub(heartbeat time.Duration) *Hub {
|
||||
if heartbeat <= 0 {
|
||||
heartbeat = 15 * time.Second
|
||||
}
|
||||
return &Hub{
|
||||
heartbeat: heartbeat,
|
||||
clients: make(map[chan Event]struct{}),
|
||||
}
|
||||
}
|
||||
|
||||
// Run emits heartbeats until ctx is cancelled.
|
||||
func (h *Hub) Run(ctx context.Context) {
|
||||
ticker := time.NewTicker(h.heartbeat)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
data, _ := json.Marshal(map[string]string{"t": time.Now().UTC().Truncate(time.Second).Format(time.RFC3339)})
|
||||
h.send(Event{Name: "ping", Data: data})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Subscribe registers a client. The returned cancel function must be called
|
||||
// when the request ends. The channel is never closed; cancelling drops it.
|
||||
func (h *Hub) Subscribe() (<-chan Event, func()) {
|
||||
ch := make(chan Event, 16)
|
||||
h.mu.Lock()
|
||||
h.clients[ch] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
|
||||
var once sync.Once
|
||||
cancel := func() {
|
||||
once.Do(func() {
|
||||
h.mu.Lock()
|
||||
delete(h.clients, ch)
|
||||
h.mu.Unlock()
|
||||
})
|
||||
}
|
||||
return ch, cancel
|
||||
}
|
||||
|
||||
// Broadcast queues an event for every client. Slow clients drop the event
|
||||
// rather than blocking the broadcaster; scenario state is versioned and can
|
||||
// always be re-read with GET /api/scenario.
|
||||
func (h *Hub) Broadcast(event Event) { h.send(event) }
|
||||
|
||||
func (h *Hub) send(event Event) {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
for ch := range h.clients {
|
||||
select {
|
||||
case ch <- event:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Clients reports the number of subscribed clients.
|
||||
func (h *Hub) Clients() int {
|
||||
h.mu.RLock()
|
||||
defer h.mu.RUnlock()
|
||||
return len(h.clients)
|
||||
}
|
||||
Reference in new issue
Block a user