Repository navigation
Expand file tree
/
Copy pathhandler.go
More file actions
948 lines (861 loc) · 34.9 KB
/
Copy pathhandler.go
File metadata and controls
948 lines (861 loc) · 34.9 KB
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
package pollmux
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"maps"
"net/http"
"time"
)
// PollModeBatch is the discrete-request poll mode: one send request in, one
// batched poll response out. Simple, but the downstream ceiling is one
// poll_buffer_bytes per round trip.
const PollModeBatch = "batch"
// PollModeStream is the low-latency downstream mode: PollHandler holds the
// long-poll response open and pushes framed chunks as they arrive instead of
// waiting for one ReadAvailable call and returning. See frame.go for the wire
// format inside the response body.
const PollModeStream = "stream"
// TransportWebSocket is ConnectResponse.Transport's value when the server
// negotiated WebSocket attachment (see ServerConfig.EnableWebSocket and
// websocket.go). It replaces PollMode/UploadStreamMode's poll/send-stream
// request pair with a single full-duplex connection, so a session with this
// transport is never polled — see WebSocketHandler.
const TransportWebSocket = "websocket"
// ServerConfig holds the server's half of the transport parameters. Every
// zero-valued field falls back to its documented default.
//
// The values here are authoritative: they are handed to each client at connect
// time, and the client clamps itself to them. That is what makes a mismatched
// pair of config files — the old failure mode — impossible.
type ServerConfig struct {
// PollTimeout is how long a long poll waits before answering 204.
PollTimeout time.Duration
// SessionTimeout is how long a session may go idle before the sweeper
// evicts it. Keep it at least twice PollTimeout, or a healthy client that
// is simply between polls looks dead.
SessionTimeout time.Duration
// SweepInterval is how often the sweeper runs.
SweepInterval time.Duration
// CoalesceWindow is how long a poll response waits for more data once any
// is available.
CoalesceWindow time.Duration
// PollBufferSize caps how many bytes one poll response may carry. This is
// the downstream throughput knob: at best one buffer per round trip.
PollBufferSize int
// MaxSendBytes caps a single request body. Clients are told this value and
// clamp to it, so exceeding it is a protocol violation, not a condition to
// recover from.
MaxSendBytes int
// SessionIDFunc extracts the session id from a poll or delete request. The
// zero value reads r.PathValue("id"), which suits net/http's own router;
// gorilla/mux users pass func(r) string { return mux.Vars(r)["id"] }.
SessionIDFunc func(*http.Request) string
// HighWaterWarn logs a one-shot warning when either direction of a session
// buffers this many bytes. Zero disables it. Useful for seeing how close a
// deployment runs to the window × max_streams worst case.
HighWaterWarn int
// PollMode must be "", PollModeBatch, or PollModeStream. "" behaves
// exactly like PollModeBatch.
PollMode string
// HeartbeatInterval is how long PollModeStream lets a poll go idle before
// sending a heartbeat frame — the same role PollTimeout plays in batch
// mode, reused as ReadAvailable's timeout argument. Ignored outside
// stream mode.
HeartbeatInterval time.Duration
// StreamMaxDuration caps how long one stream-mode poll response may stay
// open before the server ends it cleanly and the client reopens a new
// one. This exists to stay under intermediate proxies' idle/read
// timeouts, not for flow control — keep it comfortably below the
// tightest timeout in your deployment's path (see README). Ignored
// outside stream mode. Not used by WebSocket transport (see
// EnableWebSocket): a WebSocket connection does not need a forced
// rollover to stay under an intermediate proxy's read timeout the way a
// long-held HTTP response/request does, because proxies that buffer
// ordinary HTTP bodies generally pass WebSocket frames through live —
// that asymmetry is the whole reason WebSocket transport exists (see
// README's "五、WebSocket 传输模式").
StreamMaxDuration time.Duration
// EnableWebSocket lets ConnectHandler negotiate TransportWebSocket for a
// client that sends PreferWebSocket. Independent of PollMode: a server
// can offer WebSocket attachment without also offering poll-based stream
// mode, and vice versa. A client that does not ask for it, or that talks
// to a server with this left false, is completely unaffected — it gets
// the existing PollMode/UploadStreamMode negotiation with no visible
// difference.
EnableWebSocket bool
// EnableResume lets ConnectHandler negotiate a resumable session for a
// client that sends PreferResume: the session and the yamux session on
// top of it survive the transport breaking, as long as the client
// resumes (see ResumeHandler) within ResumeGrace. WebSocket, stream and
// batch transports are supported; batch requires the client's BatchResume
// capability. A client that does not ask, or a server
// with this left false, is completely unaffected. Mount ResumeHandler
// when turning this on.
EnableResume bool
// ResumeGrace is how long a resumable session survives with no
// transport attached, waiting to be resumed. Defaults to
// DefaultResumeGrace; capped at MaxResumeGrace (check panics above it).
// This replaces SessionTimeout as the eviction criterion for a
// resumable session that is detached; an attached one is never evicted,
// as today.
ResumeGrace time.Duration
// MaxReplayBytes caps how much unacknowledged data each direction of a
// resumable session retains for replay. Beyond it the session stops
// being resumable (it keeps working over its current transport, and
// the next transport failure ends it like a non-resumable session
// would). Defaults to DefaultMaxReplayBytes.
MaxReplayBytes int
// MaxDetachedResumable caps how many resumable sessions may be waiting
// detached at once, bounding the memory a burst of disconnects — or a
// client that connects and vanishes on purpose — can hold. The sweeper
// evicts the longest-detached first. A pure-batch session counts only
// after it has been detached longer than the client's declared
// PollInterval plus a fixed allowance, since between two healthy polls it
// has nothing attached. Defaults to DefaultMaxDetachedResumable; negative
// disables the cap.
MaxDetachedResumable int
// Logger receives diagnostics. Nil disables logging.
Logger *slog.Logger
}
func (cfg ServerConfig) withDefaults() ServerConfig {
if cfg.PollTimeout <= 0 {
cfg.PollTimeout = DefaultPollTimeout
}
if cfg.SessionTimeout <= 0 {
cfg.SessionTimeout = DefaultSessionTimeout
}
if cfg.SweepInterval <= 0 {
cfg.SweepInterval = DefaultSweepInterval
}
if cfg.CoalesceWindow <= 0 {
cfg.CoalesceWindow = DefaultCoalesceWindow
}
if cfg.PollBufferSize <= 0 {
cfg.PollBufferSize = DefaultPollBufferSize
}
if cfg.MaxSendBytes <= 0 {
cfg.MaxSendBytes = DefaultMaxSendBytes
}
if cfg.HeartbeatInterval <= 0 {
cfg.HeartbeatInterval = DefaultHeartbeatInterval
}
if cfg.StreamMaxDuration <= 0 {
cfg.StreamMaxDuration = DefaultStreamMaxDuration
}
if cfg.ResumeGrace <= 0 {
cfg.ResumeGrace = DefaultResumeGrace
}
if cfg.MaxReplayBytes <= 0 {
cfg.MaxReplayBytes = DefaultMaxReplayBytes
}
if cfg.MaxDetachedResumable == 0 {
cfg.MaxDetachedResumable = DefaultMaxDetachedResumable
}
if cfg.SessionIDFunc == nil {
cfg.SessionIDFunc = func(r *http.Request) string { return r.PathValue("id") }
}
if cfg.Logger == nil {
cfg.Logger = slog.New(discardHandler{})
}
return cfg
}
// check reports wiring mistakes that no runtime behaviour can paper over.
func (cfg ServerConfig) check() {
switch cfg.PollMode {
case "", PollModeBatch, PollModeStream:
default:
panic(fmt.Sprintf("pollmux: ServerConfig.PollMode = %q, only %q and %q are implemented",
cfg.PollMode, PollModeBatch, PollModeStream))
}
if cfg.SessionTimeout > 0 && cfg.PollTimeout > 0 && cfg.SessionTimeout < 2*cfg.PollTimeout {
panic(fmt.Sprintf("pollmux: ServerConfig.SessionTimeout=%v is below 2×PollTimeout=%v; "+
"a healthy client that is merely between polls would be swept as dead",
cfg.SessionTimeout, 2*cfg.PollTimeout))
}
// Same "fail at wiring time" spirit as the check above, for the
// stream-mode equivalent knobs: a StreamMaxDuration too close to
// HeartbeatInterval would force the stream to end almost as soon as it
// opens.
if cfg.PollMode == PollModeStream && cfg.StreamMaxDuration > 0 && cfg.HeartbeatInterval > 0 &&
cfg.StreamMaxDuration < 2*cfg.HeartbeatInterval {
panic(fmt.Sprintf("pollmux: ServerConfig.StreamMaxDuration=%v is below 2×HeartbeatInterval=%v; "+
"the stream would barely open before being forced to end",
cfg.StreamMaxDuration, 2*cfg.HeartbeatInterval))
}
if cfg.ResumeGrace > MaxResumeGrace {
panic(fmt.Sprintf("pollmux: ServerConfig.ResumeGrace=%v exceeds MaxResumeGrace=%v; "+
"a detached resumable session holds its replay buffer for the whole grace",
cfg.ResumeGrace, MaxResumeGrace))
}
}
// limits is what gets handed down to clients at connect time for the given
// negotiated mode.
func (cfg ServerConfig) limits(mode string, resumable bool) Limits {
l := Limits{
MaxSendBytes: cfg.MaxSendBytes,
PollTimeoutMS: cfg.PollTimeout.Milliseconds(),
SessionTimeoutMS: cfg.SessionTimeout.Milliseconds(),
PollBufferBytes: cfg.PollBufferSize,
}
if mode == PollModeStream {
l.HeartbeatIntervalMS = cfg.HeartbeatInterval.Milliseconds()
l.StreamMaxDurationMS = cfg.StreamMaxDuration.Milliseconds()
}
if resumable {
l.ResumeGraceMS = cfg.ResumeGrace.Milliseconds()
}
return l
}
// negotiatePollMode decides the session's mode: stream only if the server is
// configured for it AND the client asked for it. The server is always the
// authority — a client that prefers stream against a batch-only server gets
// batch, silently, which is what lets old and new binaries interoperate.
func negotiatePollMode(serverMode string, clientPrefersStream bool) string {
if serverMode == PollModeStream && clientPrefersStream {
return PollModeStream
}
return PollModeBatch
}
// Hooks is where the application plugs its own logic in. Every field is
// optional.
type Hooks struct {
// Authenticate vets a connect request. Returning an error rejects it: the
// library answers 401 unless the error carries a status (see StatusError).
// Any meta returned is merged over what the client declared and handed back
// to the client in the connect response.
Authenticate func(r *http.Request, req ConnectRequest) (meta map[string]string, err error)
// OnConnect runs after the session is registered in the store and before
// the response is written. This is where an application starts its yamux
// goroutine and files the session in its own registry.
//
// The ordering is not incidental. Registering first is what stops the
// client's first poll — which can arrive before this callback finishes —
// from finding no session and getting a 404. Returning an error aborts the
// connect and the session is discarded.
OnConnect func(s *Session, meta map[string]string) error
// OnPoll runs on every poll request, before the long-poll wait begins, so
// it must return quickly. Use it to read piggybacked headers such as
// X-Local-Health.
OnPoll func(s *Session, r *http.Request)
// OnDisconnect runs when a session ends, whatever ended it.
OnDisconnect func(s *Session, reason DisconnectReason)
}
// StatusError lets a hook choose the HTTP status the library answers with.
// A plain error from Authenticate produces 401; wrap it to say otherwise.
type StatusError struct {
Status int
Err error
}
func (e *StatusError) Error() string { return e.Err.Error() }
func (e *StatusError) Unwrap() error { return e.Err }
// StatusErrorf builds a StatusError, e.g.
// StatusErrorf(http.StatusBadRequest, "role must be consumer or provider").
func StatusErrorf(status int, format string, args ...any) error {
return &StatusError{Status: status, Err: fmt.Errorf(format, args...)}
}
// ConnectHandler serves POST {prefix}/connect: it authenticates, creates a
// session, and hands the client the transport parameters it must obey.
func ConnectHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler {
cfg.check()
cfg = cfg.withDefaults()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req ConnectRequest
body := http.MaxBytesReader(w, r.Body, 64<<10)
if err := json.NewDecoder(body).Decode(&req); err != nil && err != io.EOF {
writeError(w, http.StatusBadRequest, "malformed connect request: "+err.Error())
return
}
// Version first: nothing below is meaningful if we do not agree on the
// wire format. 426 tells the client to stop retrying and upgrade.
if req.ProtocolVersion != ProtocolVersion {
cfg.Logger.Warn("pollmux: rejecting connect with an unsupported protocol version",
"client_version", req.ProtocolVersion, "server_version", ProtocolVersion)
writeError(w, http.StatusUpgradeRequired,
fmt.Sprintf("unsupported protocol_version %d, this server speaks %d", req.ProtocolVersion, ProtocolVersion))
return
}
var authMeta map[string]string
if h.Authenticate != nil {
var err error
authMeta, err = h.Authenticate(r, req)
if err != nil {
status := http.StatusUnauthorized
var se *StatusError
if errors.As(err, &se) {
status = se.Status
}
writeError(w, status, err.Error())
return
}
}
// Application-supplied meta wins: it is derived from credentials the
// client cannot forge, unlike what the client declared about itself.
meta := maps.Clone(req.Meta)
if meta == nil {
meta = make(map[string]string, len(authMeta))
}
maps.Copy(meta, authMeta)
id, err := generateSessionID()
if err != nil {
cfg.Logger.Error("pollmux: failed to generate a session id", "error", err)
writeError(w, http.StatusInternalServerError, "failed to generate session id")
return
}
negotiatedMode := negotiatePollMode(cfg.PollMode, req.PreferStreamMode)
// Gated by the same server-side switch as download streaming — an
// operator turning on PollModeStream gets both directions, there is
// no independent server-side toggle for upload alone (see
// DESIGN.md). The wire field stays separate from PollMode purely for
// safe negotiation against mismatched binary versions.
negotiatedUpload := negotiatePollMode(cfg.PollMode, req.PreferStreamUpload)
s := newSession(id, meta)
s.pollMode = negotiatedMode
s.uploadStream = negotiatedUpload == PollModeStream
s.watchHighWater(cfg.HighWaterWarn, cfg.Logger)
// Decided here, before the session is published, because
// PollHandler/WebSocketHandler read s.rs without a lock — the same
// immutable-after-publish discipline pollMode and transport follow.
transport := ""
if cfg.EnableWebSocket && req.PreferWebSocket {
transport = TransportWebSocket
}
s.transport = transport
resumable := negotiateResume(cfg, req, transport, negotiatedMode, negotiatedUpload)
if resumable {
s.enableResume(cfg.MaxReplayBytes, cfg.ResumeGrace)
s.batchResume = req.BatchResume
if transport == "" && !s.uploadStream {
// Every upload response carries the upstream ack, so waking the
// download leg early to carry it would only cost a request.
s.rs.disableEagerAck()
if negotiatedMode == PollModeBatch {
ms := min(max(req.PollIntervalMS, 0), cfg.ResumeGrace.Milliseconds())
s.pollGap = time.Duration(ms)*time.Millisecond + batchPollGapAllowance
}
}
}
// Register before the callback. The client's first poll can beat
// OnConnect to the server, and it must find the session waiting.
st.add(s)
if h.OnConnect != nil {
if err := h.OnConnect(s, meta); err != nil {
st.Remove(id)
s.Close()
cfg.Logger.Error("pollmux: OnConnect rejected the session", "session_id", id, "error", err)
writeError(w, http.StatusInternalServerError, "failed to set up session")
return
}
}
cfg.Logger.Info("pollmux: session created", "session_id", id, "resumable", resumable)
uploadStreamMode := ""
// limitsMode drives whether cfg.limits() includes the
// Heartbeat/StreamMaxDuration fields: needed if either direction
// negotiated stream, not just download.
limitsMode := negotiatedMode
if negotiatedUpload == PollModeStream {
uploadStreamMode = PollModeStream
limitsMode = PollModeStream
}
// Independent of PollMode/UploadStreamMode's own gate (cfg.PollMode):
// WebSocket attachment has its own toggle, cfg.EnableWebSocket. It
// still rides limitsMode's Heartbeat field (WebSocketHandler uses it
// for the app-level heartbeat cadence, see websocket.go) but never
// needs StreamMaxDuration — see ServerConfig.StreamMaxDuration.
if transport == TransportWebSocket && limitsMode != PollModeStream {
limitsMode = PollModeStream
}
writeJSON(w, http.StatusOK, ConnectResponse{
ProtocolVersion: ProtocolVersion,
SessionID: id,
Limits: cfg.limits(limitsMode, resumable),
Meta: meta,
PollMode: negotiatedMode,
UploadStreamMode: uploadStreamMode,
Transport: transport,
Resumable: resumable,
BatchResume: resumable && req.BatchResume,
})
})
}
// PollHandler serves POST {prefix}/{id}/poll, which is two endpoints in one.
//
// X-Send-Only writes the body into the session and returns at once, never
// waiting. X-Receive-Only long-polls for downstream data. Splitting reads from
// writes this way is what keeps one direction from head-of-line blocking the
// other: a send never has to wait for the poll in flight.
func PollHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler {
cfg.check()
cfg = cfg.withDefaults()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := cfg.SessionIDFunc(r)
s, ok := st.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
if !s.beginPoll() {
writeError(w, http.StatusGone, "session closed")
return
}
defer s.endPoll()
s.touch()
// Before the wait, not after: a callback that runs after a 30-second
// park is useless for health reporting.
if h.OnPoll != nil {
h.OnPoll(s, r)
}
if r.Header.Get(HeaderSendStream) == "true" {
if s.rs != nil && (s.transport == TransportWebSocket || !s.uploadStream) {
writeError(w, http.StatusBadRequest, "session did not negotiate streamed uploads")
return
}
pollSendStream(w, r, s, cfg)
return
}
if s.rs != nil {
send := r.Header.Get(HeaderSendOnly) == "true"
receive := r.Header.Get(HeaderReceiveOnly) == "true"
if s.transport == TransportWebSocket || send == receive {
writeError(w, http.StatusBadRequest, "resumable HTTP session requires exactly one direction")
return
}
if receive && s.pollMode == PollModeStream {
pollStream(w, r, s, cfg)
} else if s.batchResume && (!send || !s.uploadStream) {
pollBatchResumable(w, r, s, st, cfg, h, send)
} else {
writeError(w, http.StatusBadRequest, "session did not negotiate this batch direction")
}
return
}
body := http.MaxBytesReader(w, r.Body, int64(cfg.MaxSendBytes))
data, err := io.ReadAll(body)
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
// Clients are told max_send_bytes at connect time and clamp to
// it, so this cannot come from a correct client. Treat it as
// the protocol violation it is: say so loudly and drop the
// session, rather than negotiating downward and hiding the bug.
cfg.Logger.Error("pollmux: closing session after a protocol violation — "+
"request body exceeded the max_send_bytes handed down at connect time",
"session_id", id, "max_send_bytes", cfg.MaxSendBytes)
closeSession(st, h, s, ReasonProtocolViolation)
writeError(w, http.StatusRequestEntityTooLarge,
fmt.Sprintf("request body exceeds max_send_bytes=%d", cfg.MaxSendBytes))
return
}
writeError(w, http.StatusBadRequest, "failed to read request body")
return
}
if len(data) > 0 {
if _, err := s.writeUpstream(data); err != nil {
cfg.Logger.Debug("pollmux: dropping upstream data for a closed session",
"session_id", id, "bytes", len(data), "error", err)
}
}
if r.Header.Get(HeaderSendOnly) == "true" {
w.WriteHeader(http.StatusOK)
return
}
if s.pollMode == PollModeStream {
pollStream(w, r, s, cfg)
return
}
buf := make([]byte, cfg.PollBufferSize)
n, err := s.toClient.ReadAvailable(buf, cfg.PollTimeout, cfg.CoalesceWindow)
if n > 0 {
w.Header().Set("Content-Type", "application/octet-stream")
w.WriteHeader(http.StatusOK)
w.Write(buf[:n])
return
}
if errors.Is(err, io.EOF) {
// Not 204. Sharing the idle-heartbeat code here is what used to
// leave a client polling a dead session until its own timeout
// instead of reconnecting within seconds.
writeError(w, http.StatusGone, "session closed")
return
}
w.WriteHeader(http.StatusNoContent)
})
}
// pollStream serves the stream-mode half of a long poll: instead of one
// ReadAvailable call and one response, it holds the response open and keeps
// calling ReadAvailable in a loop, writing each result out as a frame and
// flushing immediately. cfg.HeartbeatInterval takes over ReadAvailable's
// timeout role — "how long to wait before answering" becomes "how long to
// wait before sending a heartbeat frame" — which is why ReadAvailable itself
// needs no changes.
func pollStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig) {
flusher, ok := w.(http.Flusher)
if !ok {
// Not reachable behind net/http's own server; guards against a
// wrapping middleware that strips Flusher and would otherwise hang
// this handler for cfg.StreamMaxDuration for no reason.
writeError(w, http.StatusInternalServerError, "response writer does not support streaming")
return
}
// PollHandler owns the lifecycle attachment for this request.
// A resumable session additionally hands this handler exclusive
// ownership of the downstream direction, kicking any previous owner
// off first (see attachments). kick has to cover both places this loop
// can be blocked: the pipe wait (interrupt) and a write to a peer that
// stopped reading (a past write deadline fails it at once).
var att *attachment
if s.rs != nil {
rc := http.NewResponseController(w)
var err error
att, err = s.att.attach(attachDown, func() {
rc.SetWriteDeadline(time.Now())
s.rs.interruptOut()
})
if err != nil {
writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry")
return
}
defer s.att.detach(att)
s.rs.resetAck()
}
// Headers must go out now, not on the first frame. The client's
// ResponseHeaderTimeout for a stream-mode poll is short (it only needs
// to cover connection setup, not a long-poll wait) — if this handler
// waited for the first heartbeat/data frame before flushing headers, an
// idle session would blow that timeout on every single stream poll.
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("X-Accel-Buffering", "no") // best-effort: ask nginx-like proxies not to buffer
w.WriteHeader(http.StatusOK)
flusher.Flush()
buf := make([]byte, cfg.PollBufferSize)
deadline := time.Now().Add(cfg.StreamMaxDuration)
if s.rs != nil {
pollStreamResumable(w, r, s, cfg, flusher, att, buf, deadline)
return
}
for {
select {
case <-r.Context().Done():
return // client or an intermediate proxy dropped the connection
default:
}
n, err := s.toClient.ReadAvailable(buf, cfg.HeartbeatInterval, cfg.CoalesceWindow)
switch {
case errors.Is(err, io.EOF):
// Session closed: toClient.Close() unblocks ReadAvailable with
// io.EOF. This is fatal, unlike the StreamMaxDuration rollover
// below — the session is gone, so a frameGone (not frameEnd)
// tells the client to stop reopening polls against this session
// id and reconnect instead, the same role batch mode's 410 plays.
writeFrame(w, frameGone, nil)
flusher.Flush()
return
case n > 0:
if err := writeFrame(w, frameData, buf[:n]); err != nil {
cfg.Logger.Debug("pollmux: stream write failed, ending stream poll",
"session_id", s.ID, "error", err)
return
}
flusher.Flush()
default: // n == 0, err == nil: ReadAvailable's timeout fired — our heartbeat cadence
if err := writeFrame(w, frameHeartbeat, nil); err != nil {
cfg.Logger.Debug("pollmux: stream heartbeat write failed, ending stream poll",
"session_id", s.ID, "error", err)
return
}
flusher.Flush()
}
if time.Now().After(deadline) {
writeFrame(w, frameEnd, nil)
flusher.Flush()
return
}
}
}
// pollStreamResumable is pollStream's loop for a resumable session. Same
// shape — wait, frame, flush, roll over at deadline — with three
// differences: bytes come from the reliable layer (pending replay first,
// then the pipe) and go out as frameSeqData carrying their offset; every
// write is preceded by an ack of what has arrived upstream since the last
// one; and an interrupted wait means either "you have been replaced" (leave
// quietly, a newer transport owns this direction now) or "an ack is due"
// (send just that, no heartbeat).
func pollStreamResumable(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig,
flusher http.Flusher, att *attachment, buf []byte, deadline time.Time) {
for {
select {
case <-r.Context().Done():
return
default:
}
off, n, err := s.rs.nextOut(buf, cfg.HeartbeatInterval, cfg.CoalesceWindow)
interrupted := false
switch {
case errors.Is(err, io.EOF):
writeFrame(w, frameGone, nil)
flusher.Flush()
return
case errors.Is(err, errPipeInterrupted):
if !s.att.isCurrent(att) {
return
}
// The current attachment was nudged, not failed. Keep the
// handled signal from being mistaken for an I/O error if this
// loop gains a shared error check in the future.
interrupted = true
err = nil
}
if ack, due := s.rs.takeAck(); due {
if err := writeFrame(w, frameAck, encodeOffset(ack)); err != nil {
cfg.Logger.Debug("pollmux: stream ack write failed, ending stream poll",
"session_id", s.ID, "error", err)
return
}
}
switch {
case n > 0:
if err := writeSeqFrame(w, off, buf[:n]); err != nil {
cfg.Logger.Debug("pollmux: stream write failed, ending stream poll",
"session_id", s.ID, "error", err)
return
}
case !interrupted:
if err := writeFrame(w, frameHeartbeat, nil); err != nil {
cfg.Logger.Debug("pollmux: stream heartbeat write failed, ending stream poll",
"session_id", s.ID, "error", err)
return
}
}
flusher.Flush()
if time.Now().After(deadline) {
writeFrame(w, frameEnd, nil)
flusher.Flush()
return
}
}
}
// pollSendStream serves the upload-stream half of PollHandler: instead of
// reading one discrete, bounded request body and answering at once, it reads
// a sequence of frames off the (potentially long-lived) request body and
// writes each data frame's payload upstream as soon as it is decoded — it
// never waits for the request to end. The client (see httpConn.
// feedSendStream), not this handler, decides when to end one request and
// open the next: it is the writer, so it is the only side that knows when it
// is safely between frames (see DESIGN.md's "谁来决定轮转" section). This
// handler just reads until told to stop.
func pollSendStream(w http.ResponseWriter, r *http.Request, s *Session, cfg ServerConfig) {
// PollHandler owns the lifecycle attachment for this request.
// A read-idle watchdog is this handler's only liveness signal: unlike
// pollStream (where the server is the writer and controls the pace
// itself), here the server is a passive reader and has no other way to
// notice a client that has gone silent without actually closing the
// connection. defaultStreamReadGrace is a local safety margin — it never
// needs to match anything the client declares.
rc := http.NewResponseController(w)
resetDeadline := func() {
rc.SetReadDeadline(time.Now().Add(cfg.HeartbeatInterval + defaultStreamReadGrace))
}
resetDeadline()
// A resumable session hands this handler exclusive ownership of the
// upstream direction (see attachments); a past read deadline is what
// gets a kicked reader out of fr.next() immediately. The probe never
// carries session data, so it needs no attachment.
probe := r.Header.Get(HeaderSendStreamProbe) == "true"
resumable := s.rs != nil && !probe
if resumable {
att, err := s.att.attach(attachUp, func() { rc.SetReadDeadline(time.Now()) })
if err != nil {
writeError(w, http.StatusServiceUnavailable, "previous transport is still detaching, retry")
return
}
defer s.att.detach(att)
}
// A probe request (see Connector.UploadStreamPreference /
// probeUploadStream) carries no real session data: its frames are
// discarded instead of being written upstream. Otherwise it is handled
// exactly like a real send-stream request — same bounded shape (filler,
// then frameEnd), same response-at-the-end timing — deliberately, so the
// probe exercises the identical code path and timing as production
// traffic rather than a bespoke fast-path that might behave differently
// under a buffering proxy.
fr := newFrameReader(r.Body, cfg.MaxSendBytes)
for {
typ, payload, err := fr.next()
if err != nil {
if errors.Is(err, io.EOF) {
// Clean end at a frame boundary: same as an explicit
// frameEnd, the client already knows to reopen.
w.WriteHeader(http.StatusOK)
}
// Anything else — a deadline expiring, a mid-frame network
// error — leaves no good response to give; net/http will close
// the connection once this handler returns without having read
// the body to completion, which is exactly the signal the
// client's sendStreamClient.Do() needs to treat this as a
// transport failure.
return
}
resetDeadline()
switch typ {
case frameData:
if len(payload) == 0 || probe {
continue
}
if resumable {
// Plain data has no offset and would silently desync the
// upstream count; a resumable client never sends it.
cfg.Logger.Debug("pollmux: unnumbered data frame on a resumable session", "session_id", s.ID)
s.rs.markBroken()
writeError(w, http.StatusBadRequest, "resumable session requires seq-data frames")
return
}
if _, err := s.writeUpstream(payload); err != nil {
cfg.Logger.Debug("pollmux: send-stream write failed, session is gone",
"session_id", s.ID, "error", err)
writeError(w, http.StatusGone, "session closed")
return
}
case frameSeqData:
if !resumable {
cfg.Logger.Debug("pollmux: seq-data frame on a non-resumable session", "session_id", s.ID)
writeError(w, http.StatusBadRequest, "seq-data frames require a resumable session")
return
}
off, data, err := splitSeq(payload)
if err == nil {
err = s.rs.recvIn(off, data)
}
if err != nil {
if errors.Is(err, io.ErrClosedPipe) {
writeError(w, http.StatusGone, "session closed")
return
}
cfg.Logger.Warn("pollmux: send-stream data rejected, session is no longer resumable",
"session_id", s.ID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
case frameAck:
if !resumable {
writeError(w, http.StatusBadRequest, "ack frames require a resumable session")
return
}
n, err := decodeAck(payload)
if err == nil {
err = s.rs.ack(n)
}
if err != nil {
cfg.Logger.Warn("pollmux: send-stream ack rejected, session is no longer resumable",
"session_id", s.ID, "error", err)
writeError(w, http.StatusBadRequest, err.Error())
return
}
case frameHeartbeat:
// Nothing to do beyond the resetDeadline above.
case frameEnd:
w.WriteHeader(http.StatusOK)
return
default:
cfg.Logger.Debug("pollmux: unexpected frame type on send-stream",
"session_id", s.ID, "frame_type", typ)
writeError(w, http.StatusBadRequest, "unexpected frame type on send-stream")
return
}
}
}
// DeleteHandler serves DELETE {prefix}/{id}, the clean way for a client to go
// away.
func DeleteHandler(st *SessionStore, cfg ServerConfig, h Hooks) http.Handler {
cfg.check()
cfg = cfg.withDefaults()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := cfg.SessionIDFunc(r)
s, ok := st.Get(id)
if !ok {
writeError(w, http.StatusNotFound, "session not found")
return
}
closeSession(st, h, s, ReasonClientDelete)
cfg.Logger.Info("pollmux: session deleted", "session_id", id)
w.WriteHeader(http.StatusOK)
})
}
// CloseSession removes a session from the store, closes it, and reports the
// reason to Hooks.OnDisconnect. Use it for application-initiated teardown,
// notably graceful shutdown:
//
// for _, s := range store.All() {
// pollmux.CloseSession(store, hooks, s, pollmux.ReasonServerClose)
// }
//
// Closing the session makes any parked poll answer 410, so clients reconnect
// promptly instead of waiting out a timeout.
func CloseSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) {
closeSession(st, h, s, reason)
}
func closeSession(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) {
if !st.removeAndMarkClosed(s, false) {
return
}
s.closePipes()
if h.OnDisconnect != nil {
h.OnDisconnect(s, reason)
}
}
// CloseSessionIfNoPollInFlight atomically closes s only when it is still the
// current store entry and no poll or persistent transport is attached. It
// returns true only when this call completed the removal and close.
//
// A resumable session (see ServerConfig.EnableResume) that is detached but
// still inside its ResumeGrace also counts as attached here: its client may
// be about to resume it. A periodic reaper that calls this after noticing a
// transport drop therefore needs no resume-specific logic — it simply keeps
// getting false until the grace has passed, and the sweeper evicts the
// session at that point anyway. Session.ResumeDeadline says when.
func CloseSessionIfNoPollInFlight(st *SessionStore, h Hooks, s *Session, reason DisconnectReason) bool {
if !st.removeAndMarkClosed(s, true) {
return false
}
s.closePipes()
if h.OnDisconnect != nil {
h.OnDisconnect(s, reason)
}
return true
}
// StartSweeper runs the store's expiry scan with this config's timings, wired
// to Hooks.OnDisconnect. The returned stop function is idempotent and waits for
// the sweeper to finish.
func StartSweeper(st *SessionStore, cfg ServerConfig, h Hooks) (stop func()) {
cfg.check()
cfg = cfg.withDefaults()
st.mu.Lock()
st.maxDetachedResumable = max(cfg.MaxDetachedResumable, 0)
st.mu.Unlock()
return st.StartSweeper(cfg.SweepInterval, cfg.SessionTimeout, func(s *Session) {
cfg.Logger.Info("pollmux: evicting an idle session",
"session_id", s.ID, "idle_for", time.Since(s.LastActive()))
if h.OnDisconnect != nil {
h.OnDisconnect(s, ReasonEvicted)
}
})
}
// generateSessionID returns a random 32-character hex string.
func generateSessionID() (string, error) {
b := make([]byte, 16)
if _, err := rand.Read(b); err != nil {
return "", err
}
return hex.EncodeToString(b), nil
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}
func writeError(w http.ResponseWriter, status int, msg string) {
writeJSON(w, status, errorResponse{Error: msg})
}