Debian Codegraph @

discovery.go

raw
1 // This file is part of pluggable-discovery-protocol-handler.
2 //
3 // SPDX-FileCopyrightText: Arduino s.r.l. and/or its affiliated companies
4 // SPDX-License-Identifier: GPL-3.0-or-later
5
6 // Package discovery is a library for handling the Arduino Pluggable-Discovery protocol
7 // (https://github.com/arduino/tooling-rfcs/blob/main/RFCs/0002-pluggable-discovery.md#pluggable-discovery-api-via-stdinstdout)
8 //
9 // The library implements the state machine and the parsing logic to implement a pluggable-discovery client and server.
10 //
11 // While implementing a server, all the commands issued by the client are conveniently translated into function calls, in particular
12 // the methods of the Discovery interface are the only functions that must be implemented to get a fully working pluggable discovery
13 // using this library.
14 //
15 // A usage example is provided in the dummy-discovery package.
16 package discovery
17
18 import (
19 "bufio"
20 "encoding/json"
21 "fmt"
22 "io"
23 "regexp"
24 "strconv"
25 "strings"
26 "sync"
27 )
28
29 // Discovery is an interface that represents the business logic that
30 // a pluggable discovery must implement. The communication protocol
31 // is completely hidden and it's handled by a DiscoveryServer.
32 type Discovery interface {
33 // Hello is called once at startup to provide the userAgent string
34 // and the protocolVersion negotiated with the client.
35 Hello(userAgent string, protocolVersion int) error
36
37 // StartSync is called to put the discovery in event mode. When the
38 // function returns the discovery must send port events ("add" or "remove")
39 // using the eventCB function.
40 StartSync(eventCB EventCallback, errorCB ErrorCallback) error
41
42 // Stop stops the discovery internal subroutines. If the discovery is
43 // in event mode it must stop sending events through the eventCB previously
44 // set.
45 Stop() error
46
47 // Quit is called just before the server terminates. This function can be
48 // used by the discovery as a last chance gracefully close resources.
49 Quit()
50 }
51
52 // EventCallback is a callback function to call to transmit port
53 // metadata when the discovery is in "sync" mode and a new event
54 // is detected.
55 type EventCallback func(event string, port *Port)
56
57 // ErrorCallback is a callback function to signal unrecoverable errors to the
58 // client while the discovery is in event mode. Once the discovery signal an
59 // error it means that no more port-events will be delivered until the client
60 // performs a STOP+START_SYNC cycle.
61 type ErrorCallback func(err string)
62
63 // A Server is a pluggable discovery protocol handler,
64 // it must be created using the NewServer function.
65 type Server struct {
66 impl Discovery
67 userAgent string
68 reqProtocolVersion int
69 initialized bool
70 started bool
71 syncStarted bool
72 cachedPorts map[string]*Port
73 cachedErr string
74 output io.Writer
75 outputMutex sync.Mutex
76 }
77
78 // NewServer creates a new discovery server backed by the
79 // provided pluggable discovery implementation. To start the server
80 // use the Run method.
81 func NewServer(impl Discovery) *Server {
82 return &Server{
83 impl: impl,
84 }
85 }
86
87 // Run starts the protocol handling loop on the given input and
88 // output stream, usually `os.Stdin` and `os.Stdout` are used.
89 // The function blocks until the `QUIT` command is received or
90 // the input stream is closed. In case of IO error the error is
91 // returned.
92 func (d *Server) Run(in io.Reader, out io.Writer) error {
93 d.output = out
94 reader := bufio.NewReader(in)
95 for {
96 fullCmd, err := reader.ReadString('\n')
97 if err != nil {
98 d.send(messageError("command_error", err.Error()))
99 return err
100 }
101 fullCmd = strings.TrimSpace(fullCmd)
102 split := strings.Split(fullCmd, " ")
103 cmd := strings.ToUpper(split[0])
104
105 if !d.initialized && cmd != "HELLO" && cmd != "QUIT" {
106 d.send(messageError("command_error", fmt.Sprintf("First command must be HELLO, but got '%s'", cmd)))
107 continue
108 }
109
110 switch cmd {
111 case "HELLO":
112 if len(fullCmd) < 7 {
113 d.hello("")
114 } else {
115 d.hello(fullCmd[6:])
116 }
117 case "START":
118 d.start()
119 case "LIST":
120 d.list()
121 case "START_SYNC":
122 d.startSync()
123 case "STOP":
124 d.stop()
125 case "QUIT":
126 d.impl.Quit()
127 d.send(messageOk("quit"))
128 return nil
129 default:
130 d.send(messageError("command_error", fmt.Sprintf("Command %s not supported", cmd)))
131 }
132 }
133 }
134
135 func (d *Server) hello(cmd string) {
136 if d.initialized {
137 d.send(messageError("hello", "HELLO already called"))
138 return
139 }
140 re := regexp.MustCompile(`^(\d+) "([^"]+)"$`)
141 matches := re.FindStringSubmatch(cmd)
142 if len(matches) != 3 {
143 d.send(messageError("hello", "Invalid HELLO command"))
144 return
145 }
146 d.userAgent = matches[2]
147 v, err := strconv.ParseInt(matches[1], 10, 64)
148 if err != nil {
149 d.send(messageError("hello", "Invalid protocol version: "+matches[2]))
150 return
151 }
152 d.reqProtocolVersion = int(v)
153 if err := d.impl.Hello(d.userAgent, 1); err != nil {
154 d.send(messageError("hello", err.Error()))
155 return
156 }
157 d.send(&message{
158 EventType: "hello",
159 ProtocolVersion: 1, // Protocol version 1 is the only supported for now...
160 Message: "OK",
161 })
162 d.initialized = true
163 }
164
165 func (d *Server) start() {
166 if d.started {
167 d.send(messageError("start", "Discovery already STARTed"))
168 return
169 }
170 if d.syncStarted {
171 d.send(messageError("start", "Discovery already START_SYNCed, cannot START"))
172 return
173 }
174 d.cachedPorts = map[string]*Port{}
175 d.cachedErr = ""
176 if err := d.impl.StartSync(d.eventCallback, d.errorCallback); err != nil {
177 d.send(messageError("start", "Cannot START: "+err.Error()))
178 return
179 }
180 d.started = true
181 d.send(messageOk("start"))
182 }
183
184 func (d *Server) eventCallback(event string, port *Port) {
185 id := port.Address + "|" + port.Protocol
186 if event == "add" {
187 d.cachedPorts[id] = port
188 }
189 if event == "remove" {
190 delete(d.cachedPorts, id)
191 }
192 }
193
194 func (d *Server) errorCallback(msg string) {
195 d.cachedErr = msg
196 }
197
198 func (d *Server) list() {
199 if !d.started {
200 d.send(messageError("list", "Discovery not STARTed"))
201 return
202 }
203 if d.syncStarted {
204 d.send(messageError("list", "discovery already START_SYNCed, LIST not allowed"))
205 return
206 }
207 if d.cachedErr != "" {
208 d.send(messageError("list", d.cachedErr))
209 return
210 }
211 ports := []*Port{}
212 for _, port := range d.cachedPorts {
213 ports = append(ports, port)
214 }
215 d.send(&message{
216 EventType: "list",
217 Ports: &ports,
218 })
219 }
220
221 func (d *Server) startSync() {
222 if d.syncStarted {
223 d.send(messageError("start_sync", "Discovery already START_SYNCed"))
224 return
225 }
226 if d.started {
227 d.send(messageError("start_sync", "Discovery already STARTed, cannot START_SYNC"))
228 return
229 }
230 if err := d.impl.StartSync(d.syncEvent, d.errorEvent); err != nil {
231 d.send(messageError("start_sync", "Cannot START_SYNC: "+err.Error()))
232 return
233 }
234 d.syncStarted = true
235 d.send(messageOk("start_sync"))
236 }
237
238 func (d *Server) stop() {
239 if !d.syncStarted && !d.started {
240 d.send(messageError("stop", "Discovery already STOPped"))
241 return
242 }
243 if err := d.impl.Stop(); err != nil {
244 d.send(messageError("stop", "Cannot STOP: "+err.Error()))
245 return
246 }
247 d.started = false
248 if d.syncStarted {
249 d.syncStarted = false
250 }
251 d.send(messageOk("stop"))
252 }
253
254 func (d *Server) syncEvent(event string, port *Port) {
255 d.send(&message{
256 EventType: event,
257 Port: port,
258 })
259 }
260
261 func (d *Server) errorEvent(msg string) {
262 d.send(messageError("start_sync", msg))
263 }
264
265 func (d *Server) send(msg *message) {
266 data, err := json.MarshalIndent(msg, "", " ")
267 if err != nil {
268 // We are certain that this will be marshalled correctly
269 // so we don't handle the error
270 data, _ = json.MarshalIndent(messageError("command_error", err.Error()), "", " ")
271 }
272 data = append(data, '\n')
273
274 d.outputMutex.Lock()
275 defer d.outputMutex.Unlock()
276 n, err := d.output.Write(data)
277 if n != len(data) || err != nil {
278 panic("ERROR")
279 }
280 }