-
Notifications
You must be signed in to change notification settings - Fork 623
/
conn.go
1757 lines (1506 loc) · 44.9 KB
/
conn.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Content before git sha 34fdeebefcbf183ed7f916f931aa0586fdaa1b40
* Copyright (c) 2012, The Gocql authors,
* provided under the BSD-3-Clause License.
* See the NOTICE file distributed with this work for additional information.
*/
package gocql
import (
"bufio"
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gocql/gocql/internal/lru"
"github.com/gocql/gocql/internal/streams"
)
// approve the authenticator with the list of allowed authenticators. If the provided list is empty,
// the given authenticator is allowed.
func approve(authenticator string, approvedAuthenticators []string) bool {
if len(approvedAuthenticators) == 0 {
return true
}
for _, s := range approvedAuthenticators {
if authenticator == s {
return true
}
}
return false
}
// JoinHostPort is a utility to return an address string that can be used
// by `gocql.Conn` to form a connection with a host.
func JoinHostPort(addr string, port int) string {
addr = strings.TrimSpace(addr)
if _, _, err := net.SplitHostPort(addr); err != nil {
addr = net.JoinHostPort(addr, strconv.Itoa(port))
}
return addr
}
type Authenticator interface {
Challenge(req []byte) (resp []byte, auth Authenticator, err error)
Success(data []byte) error
}
// PasswordAuthenticator specifies credentials to be used when authenticating.
// It can be configured with an "allow list" of authenticator class names to avoid
// attempting to authenticate with Cassandra if it doesn't provide an expected authenticator.
type PasswordAuthenticator struct {
Username string
Password string
// Setting this to nil or empty will allow authenticating with any authenticator
// provided by the server. This is the default behavior of most other driver
// implementations.
AllowedAuthenticators []string
}
func (p PasswordAuthenticator) Challenge(req []byte) ([]byte, Authenticator, error) {
if !approve(string(req), p.AllowedAuthenticators) {
return nil, nil, fmt.Errorf("unexpected authenticator %q", req)
}
resp := make([]byte, 2+len(p.Username)+len(p.Password))
resp[0] = 0
copy(resp[1:], p.Username)
resp[len(p.Username)+1] = 0
copy(resp[2+len(p.Username):], p.Password)
return resp, nil, nil
}
func (p PasswordAuthenticator) Success(data []byte) error {
return nil
}
// SslOptions configures TLS use.
//
// Warning: Due to historical reasons, the SslOptions is insecure by default, so you need to set EnableHostVerification
// to true if no Config is set. Most users should set SslOptions.Config to a *tls.Config.
// SslOptions and Config.InsecureSkipVerify interact as follows:
//
// Config.InsecureSkipVerify | EnableHostVerification | Result
// Config is nil | false | do not verify host
// Config is nil | true | verify host
// false | false | verify host
// true | false | do not verify host
// false | true | verify host
// true | true | verify host
type SslOptions struct {
*tls.Config
// CertPath and KeyPath are optional depending on server
// config, but both fields must be omitted to avoid using a
// client certificate
CertPath string
KeyPath string
CaPath string //optional depending on server config
// If you want to verify the hostname and server cert (like a wildcard for cass cluster) then you should turn this
// on.
// This option is basically the inverse of tls.Config.InsecureSkipVerify.
// See InsecureSkipVerify in http://golang.org/pkg/crypto/tls/ for more info.
//
// See SslOptions documentation to see how EnableHostVerification interacts with the provided tls.Config.
EnableHostVerification bool
}
type ConnConfig struct {
ProtoVersion int
CQLVersion string
Timeout time.Duration
WriteTimeout time.Duration
ConnectTimeout time.Duration
Dialer Dialer
HostDialer HostDialer
Compressor Compressor
Authenticator Authenticator
AuthProvider func(h *HostInfo) (Authenticator, error)
Keepalive time.Duration
Logger StdLogger
tlsConfig *tls.Config
disableCoalesce bool
}
func (c *ConnConfig) logger() StdLogger {
if c.Logger == nil {
return Logger
}
return c.Logger
}
type ConnErrorHandler interface {
HandleError(conn *Conn, err error, closed bool)
}
type connErrorHandlerFn func(conn *Conn, err error, closed bool)
func (fn connErrorHandlerFn) HandleError(conn *Conn, err error, closed bool) {
fn(conn, err, closed)
}
// If not zero, how many timeouts we will allow to occur before the connection is closed
// and restarted. This is to prevent a single query timeout from killing a connection
// which may be serving more queries just fine.
// Default is 0, should not be changed concurrently with queries.
//
// Deprecated.
var TimeoutLimit int64 = 0
// Conn is a single connection to a Cassandra node. It can be used to execute
// queries, but users are usually advised to use a more reliable, higher
// level API.
type Conn struct {
conn net.Conn
r *bufio.Reader
w contextWriter
timeout time.Duration
writeTimeout time.Duration
cfg *ConnConfig
frameObserver FrameHeaderObserver
streamObserver StreamObserver
headerBuf [maxFrameHeaderSize]byte
streams *streams.IDGenerator
mu sync.Mutex
// calls stores a map from stream ID to callReq.
// This map is protected by mu.
// calls should not be used when closed is true, calls is set to nil when closed=true.
calls map[int]*callReq
errorHandler ConnErrorHandler
compressor Compressor
auth Authenticator
addr string
version uint8
currentKeyspace string
host *HostInfo
isSchemaV2 bool
session *Session
// true if connection close process for the connection started.
// closed is protected by mu.
closed bool
ctx context.Context
cancel context.CancelFunc
timeouts int64
logger StdLogger
}
// connect establishes a connection to a Cassandra node using session's connection config.
func (s *Session) connect(ctx context.Context, host *HostInfo, errorHandler ConnErrorHandler) (*Conn, error) {
return s.dial(ctx, host, s.connCfg, errorHandler)
}
// dial establishes a connection to a Cassandra node and notifies the session's connectObserver.
func (s *Session) dial(ctx context.Context, host *HostInfo, connConfig *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
var obs ObservedConnect
if s.connectObserver != nil {
obs.Host = host
obs.Start = time.Now()
}
conn, err := s.dialWithoutObserver(ctx, host, connConfig, errorHandler)
if s.connectObserver != nil {
obs.End = time.Now()
obs.Err = err
s.connectObserver.ObserveConnect(obs)
}
return conn, err
}
// dialWithoutObserver establishes connection to a Cassandra node.
//
// dialWithoutObserver does not notify the connection observer, so you most probably want to call dial() instead.
func (s *Session) dialWithoutObserver(ctx context.Context, host *HostInfo, cfg *ConnConfig, errorHandler ConnErrorHandler) (*Conn, error) {
dialedHost, err := cfg.HostDialer.DialHost(ctx, host)
if err != nil {
return nil, err
}
writeTimeout := cfg.Timeout
if cfg.WriteTimeout > 0 {
writeTimeout = cfg.WriteTimeout
}
ctx, cancel := context.WithCancel(ctx)
c := &Conn{
conn: dialedHost.Conn,
r: bufio.NewReader(dialedHost.Conn),
cfg: cfg,
calls: make(map[int]*callReq),
version: uint8(cfg.ProtoVersion),
addr: dialedHost.Conn.RemoteAddr().String(),
errorHandler: errorHandler,
compressor: cfg.Compressor,
session: s,
streams: streams.New(cfg.ProtoVersion),
host: host,
isSchemaV2: true, // Try using "system.peers_v2" until proven otherwise
frameObserver: s.frameObserver,
w: &deadlineContextWriter{
w: dialedHost.Conn,
timeout: writeTimeout,
semaphore: make(chan struct{}, 1),
quit: make(chan struct{}),
},
ctx: ctx,
cancel: cancel,
logger: cfg.logger(),
streamObserver: s.streamObserver,
writeTimeout: writeTimeout,
}
if err := c.init(ctx, dialedHost); err != nil {
cancel()
c.Close()
return nil, err
}
return c, nil
}
func (c *Conn) init(ctx context.Context, dialedHost *DialedHost) error {
if c.session.cfg.AuthProvider != nil {
var err error
c.auth, err = c.cfg.AuthProvider(c.host)
if err != nil {
return err
}
} else {
c.auth = c.cfg.Authenticator
}
startup := &startupCoordinator{
frameTicker: make(chan struct{}),
conn: c,
}
c.timeout = c.cfg.ConnectTimeout
if err := startup.setupConn(ctx); err != nil {
return err
}
c.timeout = c.cfg.Timeout
// dont coalesce startup frames
if c.session.cfg.WriteCoalesceWaitTime > 0 && !c.cfg.disableCoalesce && !dialedHost.DisableCoalesce {
c.w = newWriteCoalescer(c.conn, c.writeTimeout, c.session.cfg.WriteCoalesceWaitTime, ctx.Done())
}
go c.serve(ctx)
go c.heartBeat(ctx)
return nil
}
func (c *Conn) Write(p []byte) (n int, err error) {
return c.w.writeContext(context.Background(), p)
}
func (c *Conn) Read(p []byte) (n int, err error) {
const maxAttempts = 5
for i := 0; i < maxAttempts; i++ {
var nn int
if c.timeout > 0 {
c.conn.SetReadDeadline(time.Now().Add(c.timeout))
}
nn, err = io.ReadFull(c.r, p[n:])
n += nn
if err == nil {
break
}
if verr, ok := err.(net.Error); !ok || !verr.Temporary() {
break
}
}
return
}
type startupCoordinator struct {
conn *Conn
frameTicker chan struct{}
}
func (s *startupCoordinator) setupConn(ctx context.Context) error {
var cancel context.CancelFunc
if s.conn.timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, s.conn.timeout)
} else {
ctx, cancel = context.WithCancel(ctx)
}
defer cancel()
startupErr := make(chan error)
go func() {
for range s.frameTicker {
err := s.conn.recv(ctx)
if err != nil {
select {
case startupErr <- err:
case <-ctx.Done():
}
return
}
}
}()
go func() {
defer close(s.frameTicker)
err := s.options(ctx)
select {
case startupErr <- err:
case <-ctx.Done():
}
}()
select {
case err := <-startupErr:
if err != nil {
return err
}
case <-ctx.Done():
return errors.New("gocql: no response to connection startup within timeout")
}
return nil
}
func (s *startupCoordinator) write(ctx context.Context, frame frameBuilder) (frame, error) {
select {
case s.frameTicker <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
framer, err := s.conn.exec(ctx, frame, nil)
if err != nil {
return nil, err
}
return framer.parseFrame()
}
func (s *startupCoordinator) options(ctx context.Context) error {
frame, err := s.write(ctx, &writeOptionsFrame{})
if err != nil {
return err
}
supported, ok := frame.(*supportedFrame)
if !ok {
return NewErrProtocol("Unknown type of response to startup frame: %T", frame)
}
return s.startup(ctx, supported.supported)
}
func (s *startupCoordinator) startup(ctx context.Context, supported map[string][]string) error {
m := map[string]string{
"CQL_VERSION": s.conn.cfg.CQLVersion,
"DRIVER_NAME": driverName,
"DRIVER_VERSION": driverVersion,
}
if s.conn.compressor != nil {
comp := supported["COMPRESSION"]
name := s.conn.compressor.Name()
for _, compressor := range comp {
if compressor == name {
m["COMPRESSION"] = compressor
break
}
}
if _, ok := m["COMPRESSION"]; !ok {
s.conn.compressor = nil
}
}
frame, err := s.write(ctx, &writeStartupFrame{opts: m})
if err != nil {
return err
}
switch v := frame.(type) {
case error:
return v
case *readyFrame:
return nil
case *authenticateFrame:
return s.authenticateHandshake(ctx, v)
default:
return NewErrProtocol("Unknown type of response to startup frame: %s", v)
}
}
func (s *startupCoordinator) authenticateHandshake(ctx context.Context, authFrame *authenticateFrame) error {
if s.conn.auth == nil {
return fmt.Errorf("authentication required (using %q)", authFrame.class)
}
resp, challenger, err := s.conn.auth.Challenge([]byte(authFrame.class))
if err != nil {
return err
}
req := &writeAuthResponseFrame{data: resp}
for {
frame, err := s.write(ctx, req)
if err != nil {
return err
}
switch v := frame.(type) {
case error:
return v
case *authSuccessFrame:
if challenger != nil {
return challenger.Success(v.data)
}
return nil
case *authChallengeFrame:
resp, challenger, err = challenger.Challenge(v.data)
if err != nil {
return err
}
req = &writeAuthResponseFrame{
data: resp,
}
default:
return fmt.Errorf("unknown frame response during authentication: %v", v)
}
}
}
func (c *Conn) closeWithError(err error) {
if c == nil {
return
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return
}
c.closed = true
var callsToClose map[int]*callReq
// We should attempt to deliver the error back to the caller if it
// exists. However, don't block c.mu while we are delivering the
// error to outstanding calls.
if err != nil {
callsToClose = c.calls
// It is safe to change c.calls to nil. Nobody should use it after c.closed is set to true.
c.calls = nil
}
c.mu.Unlock()
for _, req := range callsToClose {
// we need to send the error to all waiting queries.
select {
case req.resp <- callResp{err: err}:
case <-req.timeout:
}
if req.streamObserverContext != nil {
req.streamObserverEndOnce.Do(func() {
req.streamObserverContext.StreamAbandoned(ObservedStream{
Host: c.host,
})
})
}
}
// if error was nil then unblock the quit channel
c.cancel()
cerr := c.close()
if err != nil {
c.errorHandler.HandleError(c, err, true)
} else if cerr != nil {
// TODO(zariel): is it a good idea to do this?
c.errorHandler.HandleError(c, cerr, true)
}
}
func (c *Conn) close() error {
return c.conn.Close()
}
func (c *Conn) Close() {
c.closeWithError(nil)
}
// Serve starts the stream multiplexer for this connection, which is required
// to execute any queries. This method runs as long as the connection is
// open and is therefore usually called in a separate goroutine.
func (c *Conn) serve(ctx context.Context) {
var err error
for err == nil {
err = c.recv(ctx)
}
c.closeWithError(err)
}
func (c *Conn) discardFrame(head frameHeader) error {
_, err := io.CopyN(ioutil.Discard, c, int64(head.length))
if err != nil {
return err
}
return nil
}
type protocolError struct {
frame frame
}
func (p *protocolError) Error() string {
if err, ok := p.frame.(error); ok {
return err.Error()
}
return fmt.Sprintf("gocql: received unexpected frame on stream %d: %v", p.frame.Header().stream, p.frame)
}
func (c *Conn) heartBeat(ctx context.Context) {
sleepTime := 1 * time.Second
timer := time.NewTimer(sleepTime)
defer timer.Stop()
var failures int
for {
if failures > 5 {
c.closeWithError(fmt.Errorf("gocql: heartbeat failed"))
return
}
timer.Reset(sleepTime)
select {
case <-ctx.Done():
return
case <-timer.C:
}
framer, err := c.exec(context.Background(), &writeOptionsFrame{}, nil)
if err != nil {
failures++
continue
}
resp, err := framer.parseFrame()
if err != nil {
// invalid frame
failures++
continue
}
switch resp.(type) {
case *supportedFrame:
// Everything ok
sleepTime = 5 * time.Second
failures = 0
case error:
// TODO: should we do something here?
default:
panic(fmt.Sprintf("gocql: unknown frame in response to options: %T", resp))
}
}
}
func (c *Conn) recv(ctx context.Context) error {
// not safe for concurrent reads
// read a full header, ignore timeouts, as this is being ran in a loop
// TODO: TCP level deadlines? or just query level deadlines?
if c.timeout > 0 {
c.conn.SetReadDeadline(time.Time{})
}
headStartTime := time.Now()
// were just reading headers over and over and copy bodies
head, err := readHeader(c.r, c.headerBuf[:])
headEndTime := time.Now()
if err != nil {
return err
}
if c.frameObserver != nil {
c.frameObserver.ObserveFrameHeader(context.Background(), ObservedFrameHeader{
Version: protoVersion(head.version),
Flags: head.flags,
Stream: int16(head.stream),
Opcode: frameOp(head.op),
Length: int32(head.length),
Start: headStartTime,
End: headEndTime,
Host: c.host,
})
}
if head.stream > c.streams.NumStreams {
return fmt.Errorf("gocql: frame header stream is beyond call expected bounds: %d", head.stream)
} else if head.stream == -1 {
// TODO: handle cassandra event frames, we shouldnt get any currently
framer := newFramer(c.compressor, c.version)
if err := framer.readFrame(c, &head); err != nil {
return err
}
go c.session.handleEvent(framer)
return nil
} else if head.stream <= 0 {
// reserved stream that we dont use, probably due to a protocol error
// or a bug in Cassandra, this should be an error, parse it and return.
framer := newFramer(c.compressor, c.version)
if err := framer.readFrame(c, &head); err != nil {
return err
}
frame, err := framer.parseFrame()
if err != nil {
return err
}
return &protocolError{
frame: frame,
}
}
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return ErrConnectionClosed
}
call, ok := c.calls[head.stream]
delete(c.calls, head.stream)
c.mu.Unlock()
if call == nil || !ok {
c.logger.Printf("gocql: received response for stream which has no handler: header=%v\n", head)
return c.discardFrame(head)
} else if head.stream != call.streamID {
panic(fmt.Sprintf("call has incorrect streamID: got %d expected %d", call.streamID, head.stream))
}
framer := newFramer(c.compressor, c.version)
err = framer.readFrame(c, &head)
if err != nil {
// only net errors should cause the connection to be closed. Though
// cassandra returning corrupt frames will be returned here as well.
if _, ok := err.(net.Error); ok {
return err
}
}
// we either, return a response to the caller, the caller timedout, or the
// connection has closed. Either way we should never block indefinatly here
select {
case call.resp <- callResp{framer: framer, err: err}:
case <-call.timeout:
c.releaseStream(call)
case <-ctx.Done():
}
return nil
}
func (c *Conn) releaseStream(call *callReq) {
if call.timer != nil {
call.timer.Stop()
}
c.streams.Clear(call.streamID)
if call.streamObserverContext != nil {
call.streamObserverEndOnce.Do(func() {
call.streamObserverContext.StreamFinished(ObservedStream{
Host: c.host,
})
})
}
}
func (c *Conn) handleTimeout() {
if TimeoutLimit > 0 && atomic.AddInt64(&c.timeouts, 1) > TimeoutLimit {
c.closeWithError(ErrTooManyTimeouts)
}
}
type callReq struct {
// resp will receive the frame that was sent as a response to this stream.
resp chan callResp
timeout chan struct{} // indicates to recv() that a call has timed out
streamID int // current stream in use
timer *time.Timer
// streamObserverContext is notified about events regarding this stream
streamObserverContext StreamObserverContext
// streamObserverEndOnce ensures that either StreamAbandoned or StreamFinished is called,
// but not both.
streamObserverEndOnce sync.Once
}
type callResp struct {
// framer is the response frame.
// May be nil if err is not nil.
framer *framer
// err is error encountered, if any.
err error
}
// contextWriter is like io.Writer, but takes context as well.
type contextWriter interface {
// writeContext writes p to the connection.
//
// If ctx is canceled before we start writing p (e.g. during waiting while another write is currently in progress),
// p is not written and ctx.Err() is returned. Context is ignored after we start writing p (i.e. we don't interrupt
// blocked writes that are in progress) so that we always either write the full frame or not write it at all.
//
// It returns the number of bytes written from p (0 <= n <= len(p)) and any error that caused the write to stop
// early. writeContext must return a non-nil error if it returns n < len(p). writeContext must not modify the
// data in p, even temporarily.
writeContext(ctx context.Context, p []byte) (n int, err error)
}
type deadlineWriter interface {
SetWriteDeadline(time.Time) error
io.Writer
}
type deadlineContextWriter struct {
w deadlineWriter
timeout time.Duration
// semaphore protects critical section for SetWriteDeadline/Write.
// It is a channel with capacity 1.
semaphore chan struct{}
// quit closed once the connection is closed.
quit chan struct{}
}
// writeContext implements contextWriter.
func (c *deadlineContextWriter) writeContext(ctx context.Context, p []byte) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-c.quit:
return 0, ErrConnectionClosed
case c.semaphore <- struct{}{}:
// acquired
}
defer func() {
// release
<-c.semaphore
}()
if c.timeout > 0 {
err := c.w.SetWriteDeadline(time.Now().Add(c.timeout))
if err != nil {
return 0, err
}
}
return c.w.Write(p)
}
func newWriteCoalescer(conn deadlineWriter, writeTimeout, coalesceDuration time.Duration,
quit <-chan struct{}) *writeCoalescer {
wc := &writeCoalescer{
writeCh: make(chan writeRequest),
c: conn,
quit: quit,
timeout: writeTimeout,
}
go wc.writeFlusher(coalesceDuration)
return wc
}
type writeCoalescer struct {
c deadlineWriter
mu sync.Mutex
quit <-chan struct{}
writeCh chan writeRequest
timeout time.Duration
testEnqueuedHook func()
testFlushedHook func()
}
type writeRequest struct {
// resultChan is a channel (with buffer size 1) where to send results of the write.
resultChan chan<- writeResult
// data to write.
data []byte
}
type writeResult struct {
n int
err error
}
// writeContext implements contextWriter.
func (w *writeCoalescer) writeContext(ctx context.Context, p []byte) (int, error) {
resultChan := make(chan writeResult, 1)
wr := writeRequest{
resultChan: resultChan,
data: p,
}
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-w.quit:
return 0, io.EOF // TODO: better error here?
case w.writeCh <- wr:
// enqueued for writing
}
if w.testEnqueuedHook != nil {
w.testEnqueuedHook()
}
result := <-resultChan
return result.n, result.err
}
func (w *writeCoalescer) writeFlusher(interval time.Duration) {
timer := time.NewTimer(interval)
defer timer.Stop()
if !timer.Stop() {
<-timer.C
}
w.writeFlusherImpl(timer.C, func() { timer.Reset(interval) })
}
func (w *writeCoalescer) writeFlusherImpl(timerC <-chan time.Time, resetTimer func()) {
running := false
var buffers net.Buffers
var resultChans []chan<- writeResult
for {
select {
case req := <-w.writeCh:
buffers = append(buffers, req.data)
resultChans = append(resultChans, req.resultChan)
if !running {
// Start timer on first write.
resetTimer()
running = true
}
case <-w.quit:
result := writeResult{
n: 0,
err: io.EOF, // TODO: better error here?
}
// Unblock whoever was waiting.
for _, resultChan := range resultChans {
// resultChan has capacity 1, so it does not block.
resultChan <- result
}
return
case <-timerC:
running = false
w.flush(resultChans, buffers)
buffers = nil
resultChans = nil
if w.testFlushedHook != nil {
w.testFlushedHook()
}
}
}
}
func (w *writeCoalescer) flush(resultChans []chan<- writeResult, buffers net.Buffers) {
// Flush everything we have so far.
if w.timeout > 0 {
err := w.c.SetWriteDeadline(time.Now().Add(w.timeout))
if err != nil {
for i := range resultChans {
resultChans[i] <- writeResult{
n: 0,
err: err,
}
}
return
}
}
// Copy buffers because WriteTo modifies buffers in-place.
buffers2 := make(net.Buffers, len(buffers))
copy(buffers2, buffers)
n, err := buffers2.WriteTo(w.c)
// Writes of bytes before n succeeded, writes of bytes starting from n failed with err.
// Use n as remaining byte counter.
for i := range buffers {
if int64(len(buffers[i])) <= n {
// this buffer was fully written.
resultChans[i] <- writeResult{
n: len(buffers[i]),
err: nil,
}
n -= int64(len(buffers[i]))
} else {
// this buffer was not (fully) written.
resultChans[i] <- writeResult{
n: int(n),
err: err,
}
n = 0
}
}