MCPcopy Create free account
hub / github.com/0xUnixIO/pulse / statStream

Method statStream

internal/panel/handler.go:371–462  ·  view source on GitHub ↗

statStream 是 /v1/stat/stream 的 SSE 处理器(无需认证)。 连接时立即推送 event:init(完整 stat 数据),之后每 2s 推送 event:metrics(实时网速), 每 60s 重推 event:init(刷新 uptime bars 等慢变数据)。

(w http.ResponseWriter, r *http.Request)

Source from the content-addressed store, hash-verified

369// 连接时立即推送 event:init(完整 stat 数据),之后每 2s 推送 event:metrics(实时网速),
370// 每 60s 重推 event:init(刷新 uptime bars 等慢变数据)。
371func (h *Handler) statStream(w http.ResponseWriter, r *http.Request) {
372 flusher, ok := w.(http.Flusher)
373 if !ok {
374 http.Error(w, "streaming not supported", http.StatusInternalServerError)
375 return
376 }
377 w.Header().Set("Content-Type", "text/event-stream")
378 w.Header().Set("Cache-Control", "no-cache")
379 w.Header().Set("Connection", "keep-alive")
380
381 sendInit := func() {
382 payload, err := h.buildStatPayload()
383 if err != nil {
384 return
385 }
386 data, err := json.Marshal(payload)
387 if err != nil {
388 return
389 }
390 fmt.Fprintf(w, "event: init\ndata: %s\n\n", data)
391 flusher.Flush()
392 }
393
394 type nodeMetric struct {
395 NodeID string `json:"node_id"`
396 UploadSpeed int64 `json:"upload_speed"`
397 DownloadSpeed int64 `json:"download_speed"`
398 Connections int `json:"connections"`
399 Running bool `json:"running"`
400 }
401
402 sendMetrics := func() {
403 nodeList, err := h.nodeStore.List()
404 if err != nil {
405 return
406 }
407 results := make([]nodeMetric, 0, len(nodeList))
408 var mu sync.Mutex
409 var wg sync.WaitGroup
410 for _, n := range nodeList {
411 wg.Add(1)
412 go func(n nodes.Node) {
413 defer wg.Done()
414 client, err := h.dial(n.ID)
415 if err != nil {
416 return
417 }
418 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
419 defer cancel()
420 stats, err := client.Usage(ctx, false)
421 if err != nil {
422 return
423 }
424 mu.Lock()
425 results = append(results, nodeMetric{
426 NodeID: n.ID,
427 UploadSpeed: stats.UploadSpeed,
428 DownloadSpeed: stats.DownloadSpeed,

Callers

nothing calls this directly

Calls 9

buildStatPayloadMethod · 0.95
FlushMethod · 0.80
AddMethod · 0.80
dialMethod · 0.80
ListMethod · 0.65
DoneMethod · 0.65
UsageMethod · 0.65
StopMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected