diff --git a/trace/mtr_raw.go b/trace/mtr_raw.go index 23dd26b..c29d96f 100644 --- a/trace/mtr_raw.go +++ b/trace/mtr_raw.go @@ -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. diff --git a/trace/mtr_raw_test.go b/trace/mtr_raw_test.go index bd45ea6..ddf945b 100644 --- a/trace/mtr_raw_test.go +++ b/trace/mtr_raw_test.go @@ -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{