docs(mtr): 明确回调取消与资源清理约定

This commit is contained in:
tsosunchia committed 2026-09-05 19:01:32 +08:00
1 parent e6cf2cedd1
commit d0e27e625a
2 files changed
+56

No files matched your search

+5
View File
@@ -27,6 +27,11 @@ type MTRRawOptions struct {
MaxPerHop int
// RunRound optionally overrides the traceroute call for each round.
// It is mainly for callers that need per-round locking or global-state setup.
// The callback must observe cfg.Context, including during blocking I/O or lock
// acquisition, and return promptly after cancellation. Before returning it
// must release its per-round resources and stop any workers it started.
// RunMTRRaw waits for this cleanup even when canceled; it cannot forcibly
// terminate a callback that ignores the supplied session context.
// Legacy round-based mode only.
RunRound func(method Method, cfg Config) (*Result, error)
// OnPathEnd is called when the semantic path edge changes. nil reopens it.
+51
View File
@@ -2,8 +2,10 @@ package trace
import (
"context"
"errors"
"net"
"testing"
"testing/synctest"
"time"
"github.com/nxtrace/NTrace-core/ipgeo"
@@ -161,6 +163,55 @@ func TestRunMTRRaw_ContextCancelStopsLoop(t *testing.T) {
}
}
func TestRunMTRRaw_RunRoundCancellationWaitsForCleanup(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
canceled := make(chan struct{})
releaseCleanup := make(chan struct{})
cleanupDone := make(chan struct{})
done := make(chan struct{})
var runErr error
go func() {
runErr = RunMTRRaw(ctx, ICMPTrace, Config{Context: context.Background()}, MTRRawOptions{
RunRound: func(_ Method, cfg Config) (*Result, error) {
defer close(cleanupDone)
<-cfg.Context.Done()
close(canceled)
<-releaseCleanup
return nil, cfg.Context.Err()
},
}, nil)
close(done)
}()
synctest.Wait()
cancel()
synctest.Wait()
select {
case <-canceled:
default:
t.Error("RunRound did not observe cancellation through cfg.Context")
}
select {
case <-done:
t.Errorf("RunMTRRaw returned before RunRound cleanup: %v", runErr)
default:
}
close(releaseCleanup)
<-done
if !errors.Is(runErr, context.Canceled) {
t.Fatalf("RunMTRRaw error = %v, want context.Canceled", runErr)
}
select {
case <-cleanupDone:
default:
t.Fatal("RunMTRRaw returned without waiting for RunRound cleanup")
}
})
}
func TestRunMTRRaw_UsesRunRoundOverride(t *testing.T) {
calls := 0
err := RunMTRRaw(context.Background(), ICMPTrace, Config{}, MTRRawOptions{