Debian Codegraph @

internal/jsonrpc2_v2/serve.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package jsonrpc2
6
7 import (
8 "context"
9 "fmt"
10 "io"
11 "runtime"
12 "sync"
13 "sync/atomic"
14 "time"
15 )
16
17 // Listener is implemented by protocols to accept new inbound connections.
18 type Listener interface {
19 // Accept accepts an inbound connection to a server.
20 // It blocks until either an inbound connection is made, or the listener is closed.
21 Accept(context.Context) (io.ReadWriteCloser, error)
22
23 // Close closes the listener.
24 // Any blocked Accept or Dial operations will unblock and return errors.
25 Close() error
26
27 // Dialer returns a dialer that can be used to connect to this listener
28 // locally.
29 // If a listener does not implement this it will return nil.
30 Dialer() Dialer
31 }
32
33 // Dialer is used by clients to dial a server.
34 type Dialer interface {
35 // Dial returns a new communication byte stream to a listening server.
36 Dial(ctx context.Context) (io.ReadWriteCloser, error)
37 }
38
39 // Server is a running server that is accepting incoming connections.
40 type Server struct {
41 listener Listener
42 binder Binder
43 async *async
44
45 shutdownOnce sync.Once
46 closing atomic.Int32 // atomic: set to nonzero when Shutdown is called
47 }
48
49 // Dial uses the dialer to make a new connection, wraps the returned
50 // reader and writer using the framer to make a stream, and then builds
51 // a connection on top of that stream using the binder.
52 //
53 // The returned Connection will operate independently using the Preempter and/or
54 // Handler provided by the Binder, and will release its own resources when the
55 // connection is broken, but the caller may Close it earlier to stop accepting
56 // (or sending) new requests.
57 //
58 // If non-nil, the onDone function is called when the connection is closed.
59 func Dial(ctx context.Context, dialer Dialer, binder Binder, onDone func()) (*Connection, error) {
60 // dial a server
61 rwc, err := dialer.Dial(ctx)
62 if err != nil {
63 return nil, err
64 }
65 return bindConnection(ctx, rwc, binder, onDone), nil
66 }
67
68 // NewServer starts a new server listening for incoming connections and returns
69 // it.
70 // This returns a fully running and connected server, it does not block on
71 // the listener.
72 // You can call Wait to block on the server, or Shutdown to get the sever to
73 // terminate gracefully.
74 // To notice incoming connections, use an intercepting Binder.
75 func NewServer(ctx context.Context, listener Listener, binder Binder) *Server {
76 server := &Server{
77 listener: listener,
78 binder: binder,
79 async: newAsync(),
80 }
81 go server.run(ctx)
82 return server
83 }
84
85 // Wait returns only when the server has shut down.
86 func (s *Server) Wait() error {
87 return s.async.wait()
88 }
89
90 // Shutdown informs the server to stop accepting new connections.
91 func (s *Server) Shutdown() {
92 s.shutdownOnce.Do(func() {
93 s.closing.Store(1)
94 s.listener.Close()
95 })
96 }
97
98 // run accepts incoming connections from the listener,
99 // If IdleTimeout is non-zero, run exits after there are no clients for this
100 // duration, otherwise it exits only on error.
101 func (s *Server) run(ctx context.Context) {
102 defer s.async.done()
103
104 var activeConns sync.WaitGroup
105 for {
106 rwc, err := s.listener.Accept(ctx)
107 if err != nil {
108 // Only Shutdown closes the listener. If we get an error after Shutdown is
109 // called, assume that was the cause and don't report the error;
110 // otherwise, report the error in case it is unexpected.
111 if s.closing.Load() == 0 {
112 s.async.setError(err)
113 }
114 // We are done generating new connections for good.
115 break
116 }
117
118 // A new inbound connection.
119 activeConns.Add(1)
120 _ = bindConnection(ctx, rwc, s.binder, activeConns.Done) // unregisters itself when done
121 }
122 activeConns.Wait()
123 }
124
125 // NewIdleListener wraps a listener with an idle timeout.
126 //
127 // When there are no active connections for at least the timeout duration,
128 // calls to Accept will fail with ErrIdleTimeout.
129 //
130 // A connection is considered inactive as soon as its Close method is called.
131 func NewIdleListener(timeout time.Duration, wrap Listener) Listener {
132 l := &idleListener{
133 wrapped: wrap,
134 timeout: timeout,
135 active: make(chan int, 1),
136 timedOut: make(chan struct{}),
137 idleTimer: make(chan *time.Timer, 1),
138 }
139 l.idleTimer <- time.AfterFunc(l.timeout, l.timerExpired)
140 return l
141 }
142
143 type idleListener struct {
144 wrapped Listener
145 timeout time.Duration
146
147 // Only one of these channels is receivable at any given time.
148 active chan int // count of active connections; closed when Close is called if not timed out
149 timedOut chan struct{} // closed when the idle timer expires
150 idleTimer chan *time.Timer // holds the timer only when idle
151 }
152
153 // Accept accepts an incoming connection.
154 //
155 // If an incoming connection is accepted concurrent to the listener being closed
156 // due to idleness, the new connection is immediately closed.
157 func (l *idleListener) Accept(ctx context.Context) (io.ReadWriteCloser, error) {
158 rwc, err := l.wrapped.Accept(ctx)
159
160 select {
161 case n, ok := <-l.active:
162 if err != nil {
163 if ok {
164 l.active <- n
165 }
166 return nil, err
167 }
168 if ok {
169 l.active <- n + 1
170 } else {
171 // l.wrapped.Close Close has been called, but Accept returned a
172 // connection. This race can occur with concurrent Accept and Close calls
173 // with any net.Listener, and it is benign: since the listener was closed
174 // explicitly, it can't have also timed out.
175 }
176 return l.newConn(rwc), nil
177
178 case <-l.timedOut:
179 if err == nil {
180 // Keeping the connection open would leave the listener simultaneously
181 // active and closed due to idleness, which would be contradictory and
182 // confusing. Close the connection and pretend that it never happened.
183 rwc.Close()
184 } else {
185 // In theory the timeout could have raced with an unrelated error return
186 // from Accept. However, ErrIdleTimeout is arguably still valid (since we
187 // would have closed due to the timeout independent of the error), and the
188 // harm from returning a spurious ErrIdleTimeout is negligible anyway.
189 }
190 return nil, ErrIdleTimeout
191
192 case timer := <-l.idleTimer:
193 if err != nil {
194 // The idle timer doesn't run until it receives itself from the idleTimer
195 // channel, so it can't have called l.wrapped.Close yet and thus err can't
196 // be ErrIdleTimeout. Leave the idle timer as it was and return whatever
197 // error we got.
198 l.idleTimer <- timer
199 return nil, err
200 }
201
202 if !timer.Stop() {
203 // Failed to stop the timer — the timer goroutine is in the process of
204 // firing. Send the timer back to the timer goroutine so that it can
205 // safely close the timedOut channel, and then wait for the listener to
206 // actually be closed before we return ErrIdleTimeout.
207 l.idleTimer <- timer
208 rwc.Close()
209 <-l.timedOut
210 return nil, ErrIdleTimeout
211 }
212
213 l.active <- 1
214 return l.newConn(rwc), nil
215 }
216 }
217
218 func (l *idleListener) Close() error {
219 select {
220 case _, ok := <-l.active:
221 if ok {
222 close(l.active)
223 }
224
225 case <-l.timedOut:
226 // Already closed by the timer; take care not to double-close if the caller
227 // only explicitly invokes this Close method once, since the io.Closer
228 // interface explicitly leaves doubled Close calls undefined.
229 return ErrIdleTimeout
230
231 case timer := <-l.idleTimer:
232 if !timer.Stop() {
233 // Couldn't stop the timer. It shouldn't take long to run, so just wait
234 // (so that the Listener is guaranteed to be closed before we return)
235 // and pretend that this call happened afterward.
236 // That way we won't leak any timers or goroutines when Close returns.
237 l.idleTimer <- timer
238 <-l.timedOut
239 return ErrIdleTimeout
240 }
241 close(l.active)
242 }
243
244 return l.wrapped.Close()
245 }
246
247 func (l *idleListener) Dialer() Dialer {
248 return l.wrapped.Dialer()
249 }
250
251 func (l *idleListener) timerExpired() {
252 select {
253 case n, ok := <-l.active:
254 if ok {
255 panic(fmt.Sprintf("jsonrpc2: idleListener idle timer fired with %d connections still active", n))
256 } else {
257 panic("jsonrpc2: Close finished with idle timer still running")
258 }
259
260 case <-l.timedOut:
261 panic("jsonrpc2: idleListener idle timer fired more than once")
262
263 case <-l.idleTimer:
264 // The timer for this very call!
265 }
266
267 // Close the Listener with all channels still blocked to ensure that this call
268 // to l.wrapped.Close doesn't race with the one in l.Close.
269 defer close(l.timedOut)
270 l.wrapped.Close()
271 }
272
273 func (l *idleListener) connClosed() {
274 select {
275 case n, ok := <-l.active:
276 if !ok {
277 // l is already closed, so it can't close due to idleness,
278 // and we don't need to track the number of active connections any more.
279 return
280 }
281 n--
282 if n == 0 {
283 l.idleTimer <- time.AfterFunc(l.timeout, l.timerExpired)
284 } else {
285 l.active <- n
286 }
287
288 case <-l.timedOut:
289 panic("jsonrpc2: idleListener idle timer fired before last active connection was closed")
290
291 case <-l.idleTimer:
292 panic("jsonrpc2: idleListener idle timer active before last active connection was closed")
293 }
294 }
295
296 type idleListenerConn struct {
297 wrapped io.ReadWriteCloser
298 l *idleListener
299 closeOnce sync.Once
300 }
301
302 func (l *idleListener) newConn(rwc io.ReadWriteCloser) *idleListenerConn {
303 c := &idleListenerConn{
304 wrapped: rwc,
305 l: l,
306 }
307
308 // A caller that forgets to call Close may disrupt the idleListener's
309 // accounting, even though the file descriptor for the underlying connection
310 // may eventually be garbage-collected anyway.
311 //
312 // Set a (best-effort) finalizer to verify that a Close call always occurs.
313 // (We will clear the finalizer explicitly in Close.)
314 runtime.SetFinalizer(c, func(c *idleListenerConn) {
315 panic("jsonrpc2: IdleListener connection became unreachable without a call to Close")
316 })
317
318 return c
319 }
320
321 func (c *idleListenerConn) Read(p []byte) (int, error) { return c.wrapped.Read(p) }
322 func (c *idleListenerConn) Write(p []byte) (int, error) { return c.wrapped.Write(p) }
323
324 func (c *idleListenerConn) Close() error {
325 defer c.closeOnce.Do(func() {
326 c.l.connClosed()
327 runtime.SetFinalizer(c, nil)
328 })
329 return c.wrapped.Close()
330 }