//go:build windows package control import ( "bufio" "context" "encoding/json" "fmt" "sync" "testing" "time" "github.com/Microsoft/go-winio" ) // TestSessionsAreScopedPerConnection checks that each control connection gets // its own session, that every call on one connection carries the same one, // and that the end of a connection is reported with the channels it used. func TestSessionsAreScopedPerConnection(t *testing.T) { pipe := fmt.Sprintf(`\\.\pipe\reims-go-control-test-%d`, time.Now().UnixNano()) var mu sync.Mutex seen := map[string]int{} ended := make(chan []Target, 4) endedSessions := make(chan string, 4) server, err := ListenWithOptions(pipe, func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) { mu.Lock() seen[SessionFrom(ctx)]++ mu.Unlock() return json.RawMessage(`{"ok":true}`), nil }, Options{OnSessionEnd: func(session string, targets []Target) { endedSessions <- session ended <- targets }}) if err != nil { t.Fatal(err) } defer server.Close() call := func(n int) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() conn, err := winio.DialPipeContext(ctx, pipe) if err != nil { t.Fatal(err) } encoder := json.NewEncoder(conn) reader := bufio.NewScanner(conn) for i := range n { if err := encoder.Encode(Request{PluginID: "p", Channel: "mcp", Message: json.RawMessage(`{"id":1}`), RequestID: json.RawMessage(fmt.Sprint(i))}); err != nil { t.Fatal(err) } if !reader.Scan() { t.Fatal("没有收到响应") } } if err := encoder.Encode(Request{CloseInput: true}); err != nil { t.Fatal(err) } _ = conn.Close() } call(2) call(1) sessions := map[string]bool{} for range 2 { select { case targets := <-ended: if len(targets) != 1 || targets[0] != (Target{PluginID: "p", Channel: "mcp"}) { t.Fatalf("连接结束时报告的通道 = %+v", targets) } sessions[<-endedSessions] = true case <-time.After(5 * time.Second): t.Fatal("连接结束后没有回调") } } mu.Lock() defer mu.Unlock() if len(seen) != 2 || len(sessions) != 2 { t.Fatalf("两条连接应各有一个会话:calls=%v ended=%v", seen, sessions) } for session, count := range seen { if session == "" || !sessions[session] { t.Fatalf("会话 %q 未被报告结束", session) } if count != 1 && count != 2 { t.Fatalf("会话 %q 调用次数异常:%d", session, count) } } }