Repository navigation
Expand file tree
/
Copy pathapplication_queue.go
More file actions
360 lines (322 loc) · 8.7 KB
/
Copy pathapplication_queue.go
File metadata and controls
360 lines (322 loc) · 8.7 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
package tls
import (
cryptotls "crypto/tls"
"fmt"
"io"
"net"
"reflect"
"strings"
"sync"
"sync/atomic"
"gnalloy.org/gnalloy/buffer"
)
const (
applicationQueuePending uint32 = iota
applicationQueueReady
applicationQueueClosed
)
// applicationQueue 只保存握手完成前的应用数据,并在切换稳态时一次性交接所有权。
type applicationQueue struct {
mu sync.Mutex
buffers []buffer.ByteBuf
state atomic.Uint32
}
func (q *applicationQueue) enqueue(buf buffer.ByteBuf) (bool, error) {
switch q.state.Load() {
case applicationQueueReady:
return false, nil
case applicationQueueClosed:
return false, io.ErrClosedPipe
}
q.mu.Lock()
defer q.mu.Unlock()
switch q.state.Load() {
case applicationQueueReady:
return false, nil
case applicationQueueClosed:
return false, io.ErrClosedPipe
}
q.buffers = append(q.buffers, buf)
return true, nil
}
func (q *applicationQueue) markReady() []buffer.ByteBuf {
q.mu.Lock()
if q.state.Load() == applicationQueueClosed {
q.mu.Unlock()
return nil
}
buffers := q.buffers
q.buffers = nil
q.state.Store(applicationQueueReady)
q.mu.Unlock()
return buffers
}
func (q *applicationQueue) close() []buffer.ByteBuf {
q.mu.Lock()
buffers := q.buffers
q.buffers = nil
q.state.Store(applicationQueueClosed)
q.mu.Unlock()
return buffers
}
func (q *applicationQueue) len() int {
q.mu.Lock()
n := len(q.buffers)
q.mu.Unlock()
return n
}
const (
defaultBytePoolBufferSize = 16 * 1024
defaultBytePoolMaxSize = 64 * 1024
)
// BytePool 为 TLS handler 提供跨 goroutine 边界使用的临时字节切片。
//
// 实现必须并发安全。Acquire 返回的切片长度必须等于 size;Release 调用后调用方
// 不得再访问该切片。
type BytePool interface {
Acquire(size int) []byte
Release(buf []byte)
}
// BytePoolConfig 描述默认池化字节切片的容量策略。
type BytePoolConfig struct {
// DefaultSize 是池中常规缓冲区容量,0 表示 16 KiB。
DefaultSize int
// MaxSize 是允许回收到池中的最大容量,0 表示 64 KiB。
MaxSize int
// ZeroOnRelease 控制释放时是否清零内容;默认关闭以保护热路径性能。
ZeroOnRelease bool
}
// PooledBytePool 是基于 sync.Pool 的 TLS 临时字节池。
type PooledBytePool struct {
pools [bytePoolClassCount]sync.Pool
fallback sync.Pool
defaultSize int
maxSize int
zeroOnRelease bool
}
var defaultBytePool = NewPooledBytePool(BytePoolConfig{})
// NewPooledBytePool 创建可复用的 TLS 临时字节池。
func NewPooledBytePool(cfg BytePoolConfig) *PooledBytePool {
defaultSize := cfg.DefaultSize
if defaultSize <= 0 {
defaultSize = defaultBytePoolBufferSize
}
maxSize := cfg.MaxSize
if maxSize <= 0 {
maxSize = defaultBytePoolMaxSize
}
if maxSize < defaultSize {
maxSize = defaultSize
}
p := &PooledBytePool{
defaultSize: defaultSize,
maxSize: maxSize,
zeroOnRelease: cfg.ZeroOnRelease,
}
p.fallback.New = func() any {
return make([]byte, defaultSize)
}
return p
}
// Acquire 返回长度为 size 的临时切片。
func (p *PooledBytePool) Acquire(size int) []byte {
if size <= 0 {
return nil
}
if p == nil {
return make([]byte, size)
}
targetSize := size
if targetSize < p.defaultSize {
targetSize = p.defaultSize
}
if class := bytePoolClass(targetSize, p.maxSize); class >= 0 {
return p.acquireClass(class, size)
}
buf := p.fallback.Get().([]byte)
if cap(buf) < size {
return make([]byte, size)
}
return buf[:size]
}
// Release 回收临时切片。
func (p *PooledBytePool) Release(buf []byte) {
if p == nil || cap(buf) == 0 || cap(buf) > p.maxSize {
return
}
if p.zeroOnRelease {
clear(buf[:cap(buf)])
}
if class := bytePoolExactClass(cap(buf)); class >= 0 && cap(buf) <= p.maxSize {
p.releaseClass(class, buf)
return
}
size := p.defaultSize
if cap(buf) < size {
size = cap(buf)
}
p.fallback.Put(buf[:size])
}
func normalizeBytePool(pool BytePool) BytePool {
if pool == nil {
return defaultBytePool
}
return pool
}
func acquireBytes(pool BytePool, size int) []byte {
if size <= 0 {
return nil
}
if pool == nil {
return make([]byte, size)
}
return pool.Acquire(size)
}
func releaseBytes(pool BytePool, buf []byte) {
if pool == nil || buf == nil {
return
}
pool.Release(buf)
}
type byteChunk struct {
data []byte
pool BytePool
}
func newByteChunk(data []byte, pool BytePool) byteChunk {
if pool == nil {
pool = defaultBytePool
}
return byteChunk{data: data, pool: pool}
}
func (c *byteChunk) releaseOwned() {
if c == nil || c.data == nil || c.pool == nil {
return
}
c.pool.Release(c.data)
*c = byteChunk{}
}
// Conn 是 TLS 引擎对 handler 暴露的最小连接接口。
type Conn interface {
Handshake() error
ConnectionState() cryptotls.ConnectionState
Read([]byte) (int, error)
Write([]byte) (int, error)
Close() error
}
// Provider 描述可插拔 TLS 引擎的连接工厂边界。
type Provider interface {
NativeProvider
Client(conn net.Conn, cfg *cryptotls.Config) (Conn, error)
Server(conn net.Conn, cfg *cryptotls.Config) (Conn, error)
}
// NativeCapabilities 描述可选 native TLS 引擎能提供的能力。
type NativeCapabilities struct {
Provider string
TLS13 bool
ALPN bool
SNI bool
QUICPacketProtection bool
ZeroCopyRead bool
ZeroCopyWrite bool
RequiresCGO bool
}
// NativeProvider 描述 native TLS 引擎的能力探测边界。
type NativeProvider interface {
Capabilities() NativeCapabilities
}
// NativeEvaluation 是 native TLS 路线是否可接入的静态评估结果。
type NativeEvaluation struct {
Supported bool
Reasons []string
}
// CryptoProvider 是默认 TLS provider,基于 Go 标准库 crypto/tls。
type CryptoProvider struct{}
// Capabilities 返回 crypto/tls 在 handler 场景下的能力快照。
func (CryptoProvider) Capabilities() NativeCapabilities {
return NativeCapabilities{
Provider: "crypto/tls",
TLS13: true,
ALPN: true,
SNI: true,
}
}
// Client 创建客户端 TLS 连接。
func (CryptoProvider) Client(conn net.Conn, cfg *cryptotls.Config) (Conn, error) {
return cryptotls.Client(conn, cfg), nil
}
// Server 创建服务端 TLS 连接。
func (CryptoProvider) Server(conn net.Conn, cfg *cryptotls.Config) (Conn, error) {
return cryptotls.Server(conn, cfg), nil
}
// EvaluateNativeProvider 根据能力矩阵判断 native TLS provider 是否满足 gnalloy 热路径要求。
func EvaluateNativeProvider(provider NativeProvider) NativeEvaluation {
if nativeProviderMissing(provider) {
return NativeEvaluation{Reasons: []string{"未提供 native TLS provider"}}
}
capabilities := provider.Capabilities()
reasons := make([]string, 0, 4)
if capabilities.Provider == "" {
reasons = append(reasons, "provider 名称为空")
}
if !capabilities.TLS13 {
reasons = append(reasons, "缺少 TLS 1.3")
}
if !capabilities.ALPN {
reasons = append(reasons, "缺少 ALPN")
}
if !capabilities.QUICPacketProtection {
reasons = append(reasons, "缺少 QUIC packet protection")
}
return NativeEvaluation{Supported: len(reasons) == 0, Reasons: reasons}
}
// EvaluateProvider 判断 TLS handler 可插拔 provider 是否满足连接级 TLS 能力。
func EvaluateProvider(provider Provider) NativeEvaluation {
if nativeProviderMissing(provider) {
return NativeEvaluation{Reasons: []string{"未提供 TLS provider"}}
}
capabilities := provider.Capabilities()
reasons := make([]string, 0, 3)
if capabilities.Provider == "" {
reasons = append(reasons, "provider 名称为空")
}
if !capabilities.TLS13 {
reasons = append(reasons, "缺少 TLS 1.3")
}
if !capabilities.ALPN {
reasons = append(reasons, "缺少 ALPN")
}
if !capabilities.SNI {
reasons = append(reasons, "缺少 SNI")
}
return NativeEvaluation{Supported: len(reasons) == 0, Reasons: reasons}
}
func normalizeProvider(provider Provider) Provider {
if nativeProviderMissing(provider) {
return CryptoProvider{}
}
return provider
}
func nativeProviderMissing(provider NativeProvider) bool {
if provider == nil {
return true
}
value := reflect.ValueOf(provider)
switch value.Kind() {
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Pointer, reflect.Slice:
return value.IsNil()
default:
return false
}
}
func providerEvaluationError(evaluation NativeEvaluation) error {
if evaluation.Supported {
return nil
}
return fmt.Errorf("%w: %s", ErrNativeTLSUnavailable, strings.Join(evaluation.Reasons, "; "))
}
// UnsupportedNativeProvider 是默认的显式不可用 provider,占位而不引入 cgo/native 依赖。
type UnsupportedNativeProvider struct{}
// Capabilities 返回默认不可用能力集。
func (UnsupportedNativeProvider) Capabilities() NativeCapabilities {
return NativeCapabilities{}
}