package stdio import ( "bufio" "encoding/json" "fmt" "io" "sync" "testing" "time" ) // Design 47 H2 ยง782: one bundle's state calls through its one runtime channel are safe at once: gets, puts, pages, // watches and bus-state calls from many goroutines, the runtime answering each, under the race detector. func TestOneRuntimeChannelServesConcurrentStateCalls(t *testing.T) { inR, inW := io.Pipe() outR, outW := io.Pipe() t.Cleanup(func() { _ = inW.Close(); _ = outR.Close() }) const many = 16 go func() { _ = ServeOn("", []Tool{{Name: "many", Run: func(map[string]any) (any, error) { var wg sync.WaitGroup errs := make(chan error, many*6) for i := range many { wg.Add(1) go func() { defer wg.Done() s, key := State("servers"), fmt.Sprintf("k%d", i) _, err := s.Put(key, i) errs <- err _, err = s.Get(key) errs <- err _, err = s.Page("", 1000, time.Second) errs <- err errs <- s.Watch(key, func(StateChange) error { return nil }) _, err = BusState("mesh/objects.info", map[string]any{"objects": "o"}) errs <- err _, err = s.Info() errs <- err }() } wg.Wait() close(errs) for err := range errs { if err != nil { return nil, err } } return "done", nil }}}, inR, outW) }() var wmu sync.Mutex send := func(m map[string]any) { b, _ := json.Marshal(m) wmu.Lock() defer wmu.Unlock() _, _ = inW.Write(append(b, '\n')) } send(map[string]any{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": map[string]any{"name": "many"}}) lines := bufio.NewScanner(outR) answered := make(chan map[string]any, 1) go func() { n := 1000 for lines.Scan() { var m map[string]any _ = json.Unmarshal(lines.Bytes(), &m) method, _ := m["method"].(string) switch { case m["id"] == float64(1): answered <- m return case method == "mesh/state.watch": n++ id := m["id"] key := m["params"].(map[string]any)["key"] // The runtime hands the current value over, then answers the watch, on a goroutine of its own, as // the tool runner's answers come in any order. go func(n int) { send(map[string]any{"jsonrpc": "2.0", "id": n, "method": "mesh/state", "params": map[string]any{"watch": id, "change": map[string]any{"state": "servers", "key": key, "op": "put", "value": 1, "current": true}}}) send(map[string]any{"jsonrpc": "2.0", "id": id, "result": map[string]any{}}) }(n) case method == "mesh/state.page": go send(map[string]any{"jsonrpc": "2.0", "id": m["id"], "result": map[string]any{"entries": []any{}}}) case method == "mesh/state.get": go send(map[string]any{"jsonrpc": "2.0", "id": m["id"], "result": map[string]any{"key": "k", "value": 1, "revision": 2}}) case method != "": go send(map[string]any{"jsonrpc": "2.0", "id": m["id"], "result": map[string]any{"revision": 1}}) } } }() select { case m := <-answered: if m["error"] != nil || fmt.Sprint(m["result"]) != "map[content:[map[text:\"done\" type:text]]]" { t.Fatalf("the concurrent calls answered %v", m) } case <-time.After(10 * time.Second): t.Fatal("the concurrent calls did not end") } }