Repository navigation
Expand file tree
/
Copy pathconnection_controller.go
More file actions
356 lines (318 loc) · 9.37 KB
/
Copy pathconnection_controller.go
File metadata and controls
356 lines (318 loc) · 9.37 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
package http2
import (
"gnalloy.org/gnalloy/buffer"
"gnalloy.org/gnalloy/channel"
"gnalloy.org/gnalloy/codec"
)
// ConnectionControllerConfig 描述 HTTP/2 连接级协议控制边界。
type ConnectionControllerConfig struct {
// Server 表示本端是服务端;用于校验本端和对端 stream ID 奇偶性。
Server bool
// InitialConnectionWindow 是本端接收连接窗口,0 使用 RFC 默认值。
InitialConnectionWindow int32
// InitialStreamWindow 是本端接收 stream 窗口,0 使用 RFC 默认值。
InitialStreamWindow int32
// MaxConcurrentStreams 限制对端可同时打开的 stream 数,0 表示不额外限制。
MaxConcurrentStreams int
// DisablePush 禁用本端接收 server push。
DisablePush bool
}
// ConnectionController 维护 HTTP/2 SETTINGS、GOAWAY、并发 stream 和入站流控。
type ConnectionController struct {
cfg ConnectionControllerConfig
localSettings SettingsSnapshot
remoteSettings SettingsSnapshot
connectionReceiveWindow int32
initialStreamWindow int32
streams map[StreamID]*multiplexedStream
goAwayReceived bool
goAwayLastStream StreamID
}
// NewConnectionController 创建连接级协议控制 handler。
func NewConnectionController(cfg ConnectionControllerConfig) (*ConnectionController, error) {
if cfg.InitialConnectionWindow < 0 || cfg.InitialStreamWindow < 0 || cfg.MaxConcurrentStreams < 0 {
return nil, ErrFlowControl
}
connWindow := normalizedWindow(cfg.InitialConnectionWindow)
streamWindow := normalizedWindow(cfg.InitialStreamWindow)
return &ConnectionController{
cfg: cfg,
localSettings: defaultSettingsSnapshot(streamWindow, cfg.MaxConcurrentStreams, !cfg.DisablePush),
remoteSettings: defaultSettingsSnapshot(defaultInitialWindowSize, 0, true),
connectionReceiveWindow: connWindow,
initialStreamWindow: streamWindow,
streams: make(map[StreamID]*multiplexedStream, 16),
}, nil
}
// LocalSettings 返回本端设置快照。
func (c *ConnectionController) LocalSettings() SettingsSnapshot {
return c.localSettings
}
// RemoteSettings 返回对端已应用设置快照。
func (c *ConnectionController) RemoteSettings() SettingsSnapshot {
return c.remoteSettings
}
// ConnectionReceiveWindow 返回当前连接级接收窗口。
func (c *ConnectionController) ConnectionReceiveWindow() int32 {
return c.connectionReceiveWindow
}
// StreamReceiveWindow 返回指定 stream 接收窗口。
func (c *ConnectionController) StreamReceiveWindow(id StreamID) int32 {
if stream := c.streams[id]; stream != nil {
return stream.recvWindow
}
return c.initialStreamWindow
}
// ActiveStreams 返回连接控制器仍跟踪的 stream 数。
func (c *ConnectionController) ActiveStreams() int {
return len(c.streams)
}
// ChannelRead 校验并应用入站连接级语义后继续传播 frame。
func (c *ConnectionController) ChannelRead(ctx *channel.HandlerContext, msg any) {
frame, ok := msg.(TypedFrame)
if !ok {
ctx.FireChannelRead(msg)
return
}
if err := c.readFrame(frame); err != nil {
frame.Release()
ctx.FireExceptionCaught(err)
return
}
ctx.FireChannelRead(msg)
}
// Write 校验并应用出站连接级语义。
func (c *ConnectionController) Write(ctx *channel.HandlerContext, msg any) error {
frame, ok := msg.(TypedFrame)
if !ok {
return ctx.Write(msg)
}
if err := c.writeFrame(frame); err != nil {
frame.Release()
return err
}
return ctx.Write(msg)
}
const maxStreamID StreamID = 1<<31 - 1
type StreamID uint32
func (id StreamID) Valid() bool {
return id > 0 && id <= maxStreamID
}
func (id StreamID) ClientInitiated() bool {
return id.Valid() && id%2 == 1
}
func (id StreamID) ServerInitiated() bool {
return id.Valid() && id%2 == 0
}
type StreamState uint8
const (
StreamIdle StreamState = iota
StreamOpen
StreamHalfClosedLocal
StreamHalfClosedRemote
StreamClosed
)
type Stream struct {
ID StreamID
State StreamState
}
func NewStream(id StreamID) Stream {
return Stream{ID: id, State: StreamIdle}
}
func (s *Stream) Open(endStream bool) error {
if !s.ID.Valid() {
return ErrInvalidStreamID
}
if s.State != StreamIdle {
return ErrInvalidStreamState
}
if endStream {
s.State = StreamHalfClosedLocal
return nil
}
s.State = StreamOpen
return nil
}
func (s *Stream) HalfCloseLocal() error {
switch s.State {
case StreamOpen:
s.State = StreamHalfClosedLocal
return nil
case StreamHalfClosedRemote:
s.State = StreamClosed
return nil
default:
return ErrInvalidStreamState
}
}
func (s *Stream) HalfCloseRemote() error {
switch s.State {
case StreamOpen:
s.State = StreamHalfClosedRemote
return nil
case StreamHalfClosedLocal:
s.State = StreamClosed
return nil
default:
return ErrInvalidStreamState
}
}
func (s *Stream) Close() error {
if s.State == StreamClosed {
return nil
}
if s.State == StreamIdle {
return ErrInvalidStreamState
}
s.State = StreamClosed
return nil
}
func (c *ConnectionController) readFrame(frame TypedFrame) error {
switch f := frame.(type) {
case SettingsFrame:
return c.readSettings(f)
case HeadersFrame:
return c.readHeaders(f.StreamID, f.Flags&FlagEndStream != 0)
case HeadersBlock:
return c.readHeaders(f.StreamID, f.EndStream)
case PushPromiseFrame:
return c.readPushPromise(f.StreamID, f.PromisedStreamID)
case PushPromiseBlock:
return c.readPushPromise(f.StreamID, f.PromisedStreamID)
case DataFrame:
return c.readData(f)
case RSTStreamFrame:
c.closeStream(f.StreamID)
case GoAwayFrame:
c.readGoAway(f)
}
return nil
}
func (c *ConnectionController) readSettings(frame SettingsFrame) error {
if frame.Ack {
return nil
}
before := c.remoteSettings.InitialWindowSize
if err := c.remoteSettings.apply(frame.Settings); err != nil {
return err
}
if before != c.remoteSettings.InitialWindowSize {
return c.applyRemoteInitialWindowDelta(c.remoteSettings.InitialWindowSize - before)
}
return nil
}
func (c *ConnectionController) readHeaders(streamID StreamID, endStream bool) error {
stream, _, err := c.stream(streamID, false)
if err != nil {
return err
}
if err := stream.openRemote(endStream); err != nil {
return err
}
c.closeIfNeeded(stream)
return nil
}
func (c *ConnectionController) readPushPromise(parentID StreamID, promisedID StreamID) error {
if !c.localSettings.EnablePush {
return ErrInvalidFrame
}
if c.streams[parentID] == nil {
return ErrInvalidStreamState
}
_, _, err := c.stream(promisedID, false)
return err
}
func (c *ConnectionController) readData(frame DataFrame) error {
stream := c.streams[frame.StreamID]
if stream == nil || !canReceiveData(stream.state) {
return ErrInvalidStreamState
}
size := readableBytes(frame.Data)
if size > int(c.connectionReceiveWindow) || size > int(stream.recvWindow) {
return ErrFlowControl
}
c.connectionReceiveWindow -= int32(size)
stream.recvWindow -= int32(size)
if frame.Flags&FlagEndStream != 0 {
if err := stream.halfCloseRemote(); err != nil {
return err
}
}
c.closeIfNeeded(stream)
return nil
}
func (c *ConnectionController) readGoAway(frame GoAwayFrame) {
c.goAwayReceived = true
c.goAwayLastStream = frame.LastStreamID
c.closeStreamsAfter(frame.LastStreamID)
}
var clientPrefaceBytes = []byte(ClientPreface)
// PrefaceReceivedEvent 表示 HTTP/2 client connection preface 已完整接收。
type PrefaceReceivedEvent struct{}
// PrefaceDecoder 在连接起始处消费 HTTP/2 client preface,并把剩余字节继续传给后续帧解码器。
type PrefaceDecoder struct {
*codec.ByteToMessageDecoder
received bool
}
// NewPrefaceDecoder 创建 HTTP/2 client preface 入站解码器。
func NewPrefaceDecoder() *PrefaceDecoder {
d := &PrefaceDecoder{}
d.ByteToMessageDecoder = codec.NewByteToMessageDecoder(d)
return d
}
// Decode 校验并消费固定 preface;完成后恢复为普通字节透传。
func (d *PrefaceDecoder) Decode(ctx *channel.HandlerContext, in *buffer.CompositeByteBuf) (any, error) {
if d.received {
return forwardReadable(in)
}
readable := in.ReadableBytes()
compare := readable
if compare > len(clientPrefaceBytes) {
compare = len(clientPrefaceBytes)
}
reader := in.ReaderIndex()
for i := 0; i < compare; i++ {
b, ok := in.GetByte(reader + i)
if !ok || b != clientPrefaceBytes[i] {
return nil, ErrInvalidFrame
}
}
if readable < len(clientPrefaceBytes) {
return nil, nil
}
if err := in.SkipBytes(len(clientPrefaceBytes)); err != nil {
return nil, err
}
d.received = true
ctx.FireUserEventTriggered(PrefaceReceivedEvent{})
return forwardReadable(in)
}
// PrefaceEncoder 在 client channel active 时写出 HTTP/2 client connection preface。
type PrefaceEncoder struct{}
// NewPrefaceEncoder 创建 HTTP/2 client preface 出站写入器。
func NewPrefaceEncoder() *PrefaceEncoder {
return &PrefaceEncoder{}
}
// ChannelActive 使用共享只读常量写出 preface,避免每条连接额外构造字符串。
func (e *PrefaceEncoder) ChannelActive(ctx *channel.HandlerContext) {
if err := ctx.WriteStaticBytesAndFlush(clientPrefaceBytes); err != nil {
ctx.FireExceptionCaught(err)
return
}
ctx.FireChannelActive()
}
func forwardReadable(in *buffer.CompositeByteBuf) (buffer.ByteBuf, error) {
readable := in.ReadableBytes()
if readable == 0 {
return nil, nil
}
out, err := in.Slice(in.ReaderIndex(), readable)
if err != nil {
return nil, err
}
if err := in.SkipBytes(readable); err != nil {
out.Release()
return nil, err
}
return out, nil
}