Debian Codegraph @

testscript/plugin/server.go

raw symbols SCIP
1 package plugin
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io"
7 "os"
8 "sync"
9 )
10
11 // Serve runs a plugin server for impl, reading JSON-RPC requests from
12 // [os.Stdin] and writing responses to [os.Stdout]. It is a convenience wrapper
13 // around [NewServer]; a plugin binary's main is typically just a call to Serve.
14 //
15 // A plugin must not write anything other than JSON-RPC frames to standard
16 // output. Use standard error (the default for the log package) for logging.
17 func Serve(impl Interface) error {
18 return NewServer(impl, struct {
19 io.Reader
20 io.Writer
21 }{os.Stdin, os.Stdout})
22 }
23
24 // NewServer reads JSON-RPC requests from c and writes responses to c, invoking
25 // the corresponding methods of impl. It is the counterpart of [NewClient]. It
26 // returns when it reads EOF from c (which the host arranges by closing the
27 // connection when it shuts the plugin down), after calling impl.Close.
28 //
29 // Requests are dispatched concurrently, so impl's methods must be safe for
30 // concurrent use.
31 func NewServer(impl Interface, c io.ReadWriter) error {
32 s := &server{impl: impl, insts: make(map[int]TestInstance)}
33 dec := json.NewDecoder(c)
34 enc := json.NewEncoder(c)
35 var (
36 wg sync.WaitGroup
37 encMu sync.Mutex
38 )
39 var loopErr error
40 for {
41 var req rpcRequest
42 if err := dec.Decode(&req); err != nil {
43 if err != io.EOF {
44 loopErr = err
45 }
46 break
47 }
48 wg.Add(1)
49 go func(req rpcRequest) {
50 defer wg.Done()
51 result, errStr := s.dispatch(req.Method, req.Params)
52 encMu.Lock()
53 enc.Encode(rpcResponse{ID: req.ID, Result: result, Error: errStr})
54 encMu.Unlock()
55 }(req)
56 }
57 wg.Wait()
58 impl.Close()
59 return loopErr
60 }
61
62 // server tracks the test instances created on behalf of a single connection.
63 type server struct {
64 impl Interface
65
66 // mu guards the fields below it. Per-instance work runs without the lock
67 // held so that commands on different instances proceed in parallel.
68 mu sync.Mutex
69 next int
70 insts map[int]TestInstance
71 }
72
73 // dispatch invokes the named method and returns its JSON-encoded result, or a
74 // non-empty error string if the method failed.
75 func (s *server) dispatch(method string, params json.RawMessage) (json.RawMessage, string) {
76 switch method {
77 case methodInfo:
78 var a infoArgs
79 if len(params) > 0 {
80 if err := json.Unmarshal(params, &a); err != nil {
81 return nil, err.Error()
82 }
83 }
84 // Select the lower of the version we implement and the version the
85 // client asked for, so the reply is never newer than the client
86 // understands.
87 version := min(protocolVersion, a.Version)
88 return mustMarshal(infoResult{Version: version, Info: s.impl.Info()}), ""
89 case methodNewInstance:
90 var p TestParams
91 if err := json.Unmarshal(params, &p); err != nil {
92 return nil, err.Error()
93 }
94 inst, err := s.impl.NewTestInstance(p)
95 if err != nil {
96 return nil, err.Error()
97 }
98 s.mu.Lock()
99 s.next++
100 id := s.next
101 s.insts[id] = inst
102 s.mu.Unlock()
103 return mustMarshal(newInstanceResult{InstID: id, Env: inst.Env()}), ""
104 case methodRunCmd:
105 var a runCmdArgs
106 if err := json.Unmarshal(params, &a); err != nil {
107 return nil, err.Error()
108 }
109 s.mu.Lock()
110 inst := s.insts[a.InstID]
111 s.mu.Unlock()
112 if inst == nil {
113 return nil, fmt.Sprintf("unknown plugin instance %d", a.InstID)
114 }
115 res, err := inst.RunCmd(a.Params)
116 if err != nil {
117 return nil, err.Error()
118 }
119 return mustMarshal(res), ""
120 case methodCloseInstance:
121 var a closeInstanceArgs
122 if err := json.Unmarshal(params, &a); err != nil {
123 return nil, err.Error()
124 }
125 s.mu.Lock()
126 inst := s.insts[a.InstID]
127 delete(s.insts, a.InstID)
128 s.mu.Unlock()
129 if inst != nil {
130 inst.Close()
131 }
132 return nil, ""
133 }
134 return nil, fmt.Sprintf("unknown method %q", method)
135 }
136
137 func mustMarshal(v any) json.RawMessage {
138 data, err := json.Marshal(v)
139 if err != nil {
140 // The values marshaled here are simple data structures that should
141 // always marshal successfully.
142 panic(err)
143 }
144 return data
145 }