发布网络质量探测 1.1.2:新增说明、选址源码并更新 README

署名:言灸
This commit is contained in:
YanJiu committed 2026-11-20 18:59:20 +08:00
1 parent 7cc4e042bd
commit 4c6472a504
4 files changed
+686 -3

No files matched your search

+368
View File
@@ -0,0 +1,368 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
package main
import (
"context"
"errors"
"fmt"
"net"
"sort"
"strings"
"time"
)
const appVersion = "1.1.2"
// dialState is shared by the job runner and the prober. Both hold a copy of
// jobSpec, so the mutable address choice has to live behind a pointer.
type dialState struct {
picker *endpointPicker
used net.IP
fallback string
skipped int
}
type endpointPicker struct {
ips []net.IP
index int
misses int
locked bool
sticky int
}
func newEndpointPicker(ips []net.IP) *endpointPicker {
return &endpointPicker{ips: append([]net.IP(nil), ips...), sticky: 3}
}
func (p *endpointPicker) current() net.IP {
if p == nil || len(p.ips) == 0 {
return nil
}
return p.ips[p.index]
}
func (p *endpointPicker) lock(ip net.IP) {
for i, cand := range p.ips {
if cand.Equal(ip) {
p.index = i
p.locked = true
p.misses = 0
return
}
}
}
// record matches the client EndpointPicker: one miss rotates until some
// address has answered; after that, sticky misses are required.
func (p *endpointPicker) record(responded bool) bool {
if responded {
p.locked = true
p.misses = 0
return false
}
p.misses++
limit := 1
if p.locked {
limit = p.sticky
}
if len(p.ips) < 2 || p.misses < limit {
return false
}
p.misses = 0
p.locked = false
p.index = (p.index + 1) % len(p.ips)
return true
}
func (s jobSpec) candidates() []net.IP {
if s.state != nil && s.state.picker != nil && len(s.state.picker.ips) > 0 {
return s.state.picker.ips
}
if s.IP != nil {
return []net.IP{s.IP}
}
return nil
}
func (s jobSpec) dialIP() net.IP {
if s.state != nil && s.state.picker != nil {
if ip := s.state.picker.current(); ip != nil {
return ip
}
}
if s.IP != nil {
return s.IP
}
return nil
}
func familyOf(ip net.IP) string {
if ip == nil {
return ""
}
if ip.To4() != nil {
return "IPv4"
}
return "IPv6"
}
func copyDetail(in map[string]string) map[string]string {
out := make(map[string]string, len(in)+2)
for k, v := range in {
out[k] = v
}
return out
}
func stampIP(o Outcome, ip net.IP) Outcome {
if ip == nil {
return o
}
o.Detail = copyDetail(o.Detail)
o.Detail["address"] = ip.String()
o.Detail["family"] = familyOf(ip)
return o
}
// decorate attaches the address actually dialed. Candidate-connect failures
// that were skipped in favor of a working address are copied onto this one
// outcome and then cleared, so they are not repeated on later probes.
func (s jobSpec) decorate(o Outcome) Outcome {
if s.state == nil {
if s.IP != nil {
return stampIP(o, s.IP)
}
return o
}
if s.state.used != nil {
o = stampIP(o, s.state.used)
}
if s.state.fallback != "" {
o.Detail = copyDetail(o.Detail)
o.Detail["fallback"] = s.state.fallback
s.state.fallback = ""
}
if s.state.skipped > 0 {
o.SelectionSkipped += s.state.skipped
s.state.skipped = 0
}
return o
}
func selectionResponded(status string) bool {
switch status {
case statusOK, statusProtocol, statusRefused:
return true
default:
return false
}
}
func datagramProfile(profile string) bool {
switch profile {
case "nq-udp", "udp-generic", "custom-udp", "dns", "minecraft-bedrock":
return true
default:
return false
}
}
type selectionLedger struct {
candidates int
measuring bool
held []Outcome
}
func (l *selectionLedger) take(o Outcome, responded bool) (commit []Outcome, skipped int) {
if l.candidates <= 1 {
if responded {
l.measuring = true
}
return []Outcome{o}, 0
}
if l.measuring {
return []Outcome{o}, 0
}
if responded {
skipped = len(l.held)
if skipped > 0 {
o.Detail = copyDetail(o.Detail)
o.Detail["fallback"] = fallbackFromHeld(l.held, o)
o.SelectionSkipped += skipped
}
l.held = nil
l.measuring = true
return []Outcome{o}, skipped
}
l.held = append(l.held, o)
if len(l.held) >= l.candidates {
commit = append([]Outcome(nil), l.held...)
l.held = nil
return commit, 0
}
return nil, 0
}
func fallbackFromHeld(held []Outcome, success Outcome) string {
parts := make([]string, 0, len(held))
for _, o := range held {
addr := ""
fam := ""
if o.Detail != nil {
addr = o.Detail["address"]
fam = o.Detail["family"]
}
where := "未知地址"
if addr != "" {
where = addr
if fam != "" {
where = addr + "(" + fam + ")"
}
}
why := o.Note
if why == "" {
why = "没有成功"
}
parts = append(parts, where+":"+why)
}
used := ""
usedFam := ""
if success.Detail != nil {
used = success.Detail["address"]
usedFam = success.Detail["family"]
}
usedText := "另一个地址"
if used != "" {
usedText = used
if usedFam != "" {
usedText = used + "(" + usedFam + ")"
}
}
return "候选未成功:" + strings.Join(parts, ";") + "。已改用 " + usedText + "。这些失败没有计入正式丢包或失败率。"
}
type dialFunc func(context.Context, net.IP) (net.Conn, error)
// dialFirst tries each address with its own timeout. A failure is described
// and not returned as a separate measured attempt. If a later address
// connects, the skipped notes are returned for the diagnostic. If every
// address fails, err is the last error. A cancelled parent context does not
// become a measured timeout.
func dialFirst(ctx context.Context, ips []net.IP, timeout time.Duration, dial dialFunc) (net.Conn, net.IP, []string, error) {
if len(ips) == 0 {
return nil, nil, nil, errors.New("no address")
}
if timeout <= 0 {
timeout = 1500 * time.Millisecond
}
var skipped []string
var last error
for _, ip := range ips {
if err := ctx.Err(); err != nil {
return nil, nil, skipped, err
}
dialCtx, cancel := context.WithTimeout(ctx, timeout)
conn, err := dial(dialCtx, ip)
cancel()
if err == nil {
return conn, ip, skipped, nil
}
if errors.Is(err, context.Canceled) && ctx.Err() != nil {
return nil, nil, skipped, ctx.Err()
}
skipped = append(skipped, fmt.Sprintf("%s %s %s", familyOf(ip), ip.String(), classifyDial(err).Note))
last = err
}
if last == nil {
last = errors.New("连接失败")
}
return nil, nil, skipped, last
}
func dialSpecTCP(ctx context.Context, spec *jobSpec) (net.Conn, error) {
ips := spec.candidates()
start := 0
if spec.state != nil && spec.state.picker != nil {
start = spec.state.picker.index
}
rotated := make([]net.IP, 0, len(ips))
for n := 0; n < len(ips); n++ {
rotated = append(rotated, ips[(start+n)%len(ips)])
}
conn, ip, skipped, err := dialFirst(ctx, rotated, spec.Timeout, func(ctx context.Context, ip net.IP) (net.Conn, error) {
return dialTCP(ctx, ip, spec.Port)
})
if spec.state != nil {
spec.state.used = nil
spec.state.fallback = ""
spec.state.skipped = 0
}
if err != nil {
if spec.state != nil && len(skipped) > 0 && !errors.Is(err, context.Canceled) {
spec.state.fallback = "已尝试 " + strings.Join(skipped, ";") + "。没有地址连通,这次记为失败。"
}
return nil, err
}
if spec.state != nil {
if spec.state.picker != nil {
spec.state.picker.lock(ip)
}
spec.state.used = append(net.IP(nil), ip...)
if len(skipped) > 0 {
spec.state.skipped = len(skipped)
spec.state.fallback = "候选未连通:" + strings.Join(skipped, ";") + "。已改用 " + ip.String() + "(" + familyOf(ip) + ")。这些失败没有计入正式丢包或失败率。"
}
}
return conn, nil
}
func ensureUDP(conn *net.UDPConn, spec jobSpec) (*net.UDPConn, error) {
want := spec.dialIP()
if want == nil {
return nil, errors.New("no address")
}
if conn != nil {
if ra, ok := conn.RemoteAddr().(*net.UDPAddr); ok && ra.IP.Equal(want) {
return conn, nil
}
_ = conn.Close()
}
return dialUDP(want, spec.Port)
}
// nearestRank95 is ceil(0.95*n) in integer arithmetic.
func nearestRank95(n int) int {
if n <= 1 {
return 1
}
rank := (95*n + 99) / 100
if rank < 1 {
return 1
}
if rank > n {
return n
}
return rank
}
func latencyOf(samples []float64) (min, mean, median, p95, max float64, ok bool) {
if len(samples) == 0 {
return 0, 0, 0, 0, 0, false
}
sorted := append([]float64(nil), samples...)
sort.Float64s(sorted)
var sum float64
for _, v := range sorted {
sum += v
}
n := len(sorted)
if n%2 == 1 {
median = sorted[n/2]
} else {
median = (sorted[n/2-1] + sorted[n/2]) / 2
}
rank := nearestRank95(n)
return sorted[0], sum / float64(n), median, sorted[rank-1], sorted[n-1], true
}
+266
View File
@@ -0,0 +1,266 @@
package main
import (
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestSelectionLedgerDoesNotCountFallback(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
miss := Outcome{
Status: statusTimeout,
Kind: kindProbe,
Note: "未收到回显",
Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"},
}
commit, skipped := ledger.take(miss, false)
if commit != nil || skipped != 0 {
t.Fatalf("held failure was counted: %+v %d", commit, skipped)
}
ok := Outcome{
Status: statusOK,
Kind: kindProbe,
HasRtt: true,
Rtt: 5 * time.Millisecond,
Note: "收到回显",
Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"},
}
commit, skipped = ledger.take(ok, true)
if skipped != 1 || len(commit) != 1 || commit[0].SelectionSkipped != 1 {
t.Fatalf("success %+v skipped %d", commit, skipped)
}
if commit[0].Detail["fallback"] == "" || !containsAll(commit[0].Detail["fallback"], "2001:db8::1", "203.0.113.5", "没有计入") {
t.Fatalf("fallback %q", commit[0].Detail["fallback"])
}
book := &sampleBook{profile: "nq-udp"}
book.add(commit[0])
summary := book.summary()
if summary.Sent != 1 || summary.OK != 1 || summary.Timeout != 0 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 0 {
t.Fatalf("summary %+v", summary)
}
if summary.SelectionSkipped != 1 || summary.MinRttMs == nil || *summary.MinRttMs != 5 || summary.P95RttMs == nil || *summary.P95RttMs != 5 {
t.Fatalf("stats %+v", summary)
}
}
func TestSelectionLedgerCommitsTotalFailure(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
first := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "2001:db8::1", "family": "IPv6"}}
second := Outcome{Status: statusTimeout, Kind: kindProbe, Detail: map[string]string{"address": "203.0.113.5", "family": "IPv4"}}
if commit, _ := ledger.take(first, false); commit != nil {
t.Fatal("first failure committed early")
}
commit, _ := ledger.take(second, false)
if len(commit) != 2 {
t.Fatalf("commit %+v", commit)
}
book := &sampleBook{profile: "nq-udp"}
for _, outcome := range commit {
book.add(outcome)
}
summary := book.summary()
if summary.OK != 0 || summary.Sent != 2 || summary.ProbeLossPct == nil || *summary.ProbeLossPct != 100 {
t.Fatalf("summary %+v", summary)
}
}
func TestMeasuredTimeoutStillCounts(t *testing.T) {
ledger := &selectionLedger{candidates: 2}
ok := Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond}
if commit, _ := ledger.take(ok, true); len(commit) != 1 {
t.Fatal(commit)
}
miss := Outcome{Status: statusTimeout, Kind: kindProbe}
commit, _ := ledger.take(miss, false)
if len(commit) != 1 || commit[0].Status != statusTimeout {
t.Fatalf("post-selection miss hidden: %+v", commit)
}
book := &sampleBook{profile: "nq-udp"}
book.add(ok)
book.add(commit[0])
summary := book.summary()
if summary.ProbeLossPct == nil || *summary.ProbeLossPct != 50 || summary.Sent != 2 {
t.Fatalf("summary %+v", summary)
}
}
func TestLatencyRanks(t *testing.T) {
if nearestRank95(1) != 1 || nearestRank95(2) != 2 || nearestRank95(4) != 4 || nearestRank95(5) != 5 || nearestRank95(20) != 19 {
t.Fatalf("ranks %d %d %d %d %d", nearestRank95(1), nearestRank95(2), nearestRank95(4), nearestRank95(5), nearestRank95(20))
}
min, mean, median, p95, max, ok := latencyOf([]float64{1, 2, 3, 4})
if !ok || min != 1 || mean != 2.5 || median != 2.5 || p95 != 4 || max != 4 {
t.Fatalf("four %v %v %v %v %v", min, mean, median, p95, max)
}
_, _, median, p95, _, ok = latencyOf([]float64{1, 2, 3, 4, 10})
if !ok || median != 3 || p95 != 10 {
t.Fatalf("five median %v p95 %v", median, p95)
}
_, _, _, _, _, ok = latencyOf(nil)
if ok {
t.Fatal("empty latency")
}
book := &sampleBook{profile: "nq-udp"}
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: time.Millisecond})
book.add(Outcome{Status: statusOK, Kind: kindProbe, HasRtt: true, Rtt: 4 * time.Millisecond})
summary := book.summary()
if summary.MinRttMs == nil || *summary.MinRttMs != 1 || summary.MaxRttMs == nil || *summary.MaxRttMs != 4 || summary.MedianRttMs == nil || *summary.MedianRttMs != 2.5 {
t.Fatalf("aliased latency %+v", summary)
}
}
func TestDialFirstSkipsFailedCandidate(t *testing.T) {
good, bad := net.Pipe()
defer good.Close()
defer bad.Close()
v6 := net.ParseIP("2001:db8::1")
v4 := net.ParseIP("203.0.113.5")
calls := 0
conn, used, skipped, err := dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(ctx context.Context, ip net.IP) (net.Conn, error) {
calls++
if ip.Equal(v6) {
return nil, errors.New("network unreachable")
}
return good, nil
})
if err != nil || !used.Equal(v4) || len(skipped) != 1 || calls != 2 {
t.Fatalf("used %v skipped %v err %v calls %d", used, skipped, err, calls)
}
_ = conn.Close()
_, _, skipped, err = dialFirst(context.Background(), []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
return nil, context.DeadlineExceeded
})
if err == nil || len(skipped) != 2 {
t.Fatalf("all-fail err %v skipped %v", err, skipped)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, _, _, err = dialFirst(ctx, []net.IP{v6, v4}, time.Second, func(context.Context, net.IP) (net.Conn, error) {
t.Fatal("dialled after cancel")
return nil, nil
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("cancel err %v", err)
}
}
func TestResolveTargetsKeepsOrder(t *testing.T) {
resolver := stubResolver{[]net.IP{net.ParseIP("2001:db8::1"), net.ParseIP("203.0.113.5")}}
ips, err := resolveTargets(context.Background(), resolver, "example.com", false, nil)
if err != nil || len(ips) != 2 || ips[0].String() != "2001:db8::1" || ips[1].String() != "203.0.113.5" {
t.Fatalf("ips %v err %v", ips, err)
}
first, err := targetOK(context.Background(), resolver, "example.com", false, nil)
if err != nil || first.String() != "2001:db8::1" {
t.Fatalf("first %v err %v", first, err)
}
}
func TestStopDoesNotRecordInFlight(t *testing.T) {
blackhole, err := net.ListenUDP("udp", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
if err != nil {
t.Fatal(err)
}
defer blackhole.Close()
node := newNode("", true, nil, testLimits())
srv := httptest.NewServer(node.Handler())
defer srv.Close()
id := createJob(t, srv.URL, "", map[string]any{
"target": "127.0.0.1", "port": blackhole.LocalAddr().(*net.UDPAddr).Port,
"profile": "nq-udp", "intervalMs": 200, "timeoutMs": 4000, "durationSec": 5, "packetSize": 80,
})
time.Sleep(50 * time.Millisecond)
req, err := http.NewRequest(http.MethodDelete, srv.URL+"/v1/jobs/"+id, nil)
if err != nil {
t.Fatal(err)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
res.Body.Close()
time.Sleep(100 * time.Millisecond)
snapReq, err := http.NewRequest(http.MethodGet, srv.URL+"/v1/jobs/"+id, nil)
if err != nil {
t.Fatal(err)
}
snapRes, err := http.DefaultClient.Do(snapReq)
if err != nil {
t.Fatal(err)
}
defer snapRes.Body.Close()
if snapRes.StatusCode == http.StatusNotFound {
return
}
body, _ := io.ReadAll(snapRes.Body)
var msg sampleMsg
if err := json.Unmarshal(body, &msg); err != nil {
t.Fatal(err)
}
if msg.Summary.Sent > 0 || msg.Status == statusTimeout || msg.Status == statusUnknown {
t.Fatalf("cancelled probe counted %s", body)
}
}
func TestNodeUDPFallbackIsNotLoss(t *testing.T) {
drop, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.ParseIP("127.0.0.2")})
if err != nil {
t.Skipf("127.0.0.2 unavailable: %v", err)
}
defer drop.Close()
go func() {
buf := make([]byte, 2048)
for {
if _, _, err := drop.ReadFromUDP(buf); err != nil {
return
}
}
}()
port := drop.LocalAddr().(*net.UDPAddr).Port
echo, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1), Port: port})
if err != nil {
t.Skipf("paired echo: %v", err)
}
defer echo.Close()
reflector := &Server{}
go reflector.ServeUDP(echo)
defer reflector.Close()
node := newNode("", true, nil, testLimits())
node.Resolver = stubResolver{[]net.IP{net.ParseIP("127.0.0.2"), net.ParseIP("127.0.0.1")}}
srv := httptest.NewServer(node.Handler())
defer srv.Close()
id := createJob(t, srv.URL, "", map[string]any{
"target": "example.test", "port": port, "profile": "nq-udp",
"intervalMs": 200, "timeoutMs": 300, "durationSec": 5, "packetSize": 80,
})
sample := readOneSample(t, srv.URL, "", id)
if sample.Status != statusOK || sample.Detail["address"] != "127.0.0.1" || sample.Detail["family"] != "IPv4" {
t.Fatalf("sample %+v", sample)
}
if sample.Summary.Sent != 1 || sample.Summary.Timeout != 0 || sample.Summary.ProbeLossPct == nil || *sample.Summary.ProbeLossPct != 0 || sample.Summary.SelectionSkipped != 1 {
t.Fatalf("loss polluted %+v", sample.Summary)
}
if !strings.Contains(sample.Detail["fallback"], "127.0.0.2") || !strings.Contains(sample.Detail["fallback"], "没有计入") {
t.Fatalf("fallback %q", sample.Detail["fallback"])
}
}
func containsAll(text string, parts ...string) bool {
for _, part := range parts {
if !strings.Contains(text, part) {
return false
}
}
return true
}