-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathstrategy.go
More file actions
389 lines (337 loc) · 10.1 KB
/
strategy.go
File metadata and controls
389 lines (337 loc) · 10.1 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
/*
* Copyright 2025 The RuleGo Authors.
*
* Licensed 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.
*/
package stream
import (
"fmt"
"sync"
"sync/atomic"
"time"
"github.com/rulego/streamsql/logger"
"github.com/rulego/streamsql/types"
)
// Overflow strategy constants
const (
StrategyDrop = "drop" // Drop strategy
StrategyBlock = "block" // Blocking strategy
StrategyExpand = "expand" // Dynamic strategy
)
// DataProcessingStrategy data processing strategy interface
// Defines unified interface for different overflow strategies, providing better extensibility and maintainability
type DataProcessingStrategy interface {
// ProcessData core method for processing data
// Parameters:
// - data: data to process, must be map[string]interface{} type
ProcessData(data map[string]interface{})
// GetStrategyName gets strategy name
GetStrategyName() string
// Init initializes strategy
// Parameters:
// - stream: Stream instance reference
// - config: performance configuration
Init(stream *Stream, config types.PerformanceConfig) error
// Stop stops and cleans up resources
Stop() error
}
// BlockingStrategy blocking strategy implementation
type BlockingStrategy struct {
stream *Stream
}
// NewBlockingStrategy creates blocking strategy instance
func NewBlockingStrategy() *BlockingStrategy {
return &BlockingStrategy{}
}
// ProcessData implements blocking mode data processing
func (bs *BlockingStrategy) ProcessData(data map[string]interface{}) {
// Check if stream is stopped
if atomic.LoadInt32(&bs.stream.stopped) == 1 {
return
}
if bs.stream.blockingTimeout <= 0 {
// No timeout limit, block permanently until success
dataChan := bs.stream.safeGetDataChan()
if dataChan == nil {
return
}
select {
case dataChan <- data:
return
case <-bs.stream.done:
return
}
}
// Blocking with timeout
timer := time.NewTimer(bs.stream.blockingTimeout)
defer timer.Stop()
dataChan := bs.stream.safeGetDataChan()
if dataChan == nil {
return
}
select {
case dataChan <- data:
// Successfully added data
return
case <-timer.C:
// Timeout but don't drop data, log error but continue blocking
logger.Error("Data addition timeout, but continue waiting to avoid data loss")
// Continue blocking indefinitely, re-get current channel reference
finalDataChan := bs.stream.safeGetDataChan()
if finalDataChan == nil {
return
}
select {
case finalDataChan <- data:
return
case <-bs.stream.done:
return
}
case <-bs.stream.done:
return
}
}
// GetStrategyName gets strategy name
func (bs *BlockingStrategy) GetStrategyName() string {
return StrategyBlock
}
// Init initializes blocking strategy
func (bs *BlockingStrategy) Init(stream *Stream, config types.PerformanceConfig) error {
bs.stream = stream
return nil
}
// Stop stops and cleans up blocking strategy resources
func (bs *BlockingStrategy) Stop() error {
return nil
}
// ExpansionStrategy expansion strategy implementation
type ExpansionStrategy struct {
stream *Stream
}
// NewExpansionStrategy creates expansion strategy instance
func NewExpansionStrategy() *ExpansionStrategy {
return &ExpansionStrategy{}
}
// ProcessData implements expansion mode data processing
func (es *ExpansionStrategy) ProcessData(data map[string]interface{}) {
// First attempt to add data
if es.stream.safeSendToDataChan(data) {
return
}
// Channel is full, dynamically expand
es.stream.expandDataChannel()
// Retry after expansion, re-acquire channel reference
if es.stream.safeSendToDataChan(data) {
logger.Debug("Successfully added data after data channel expansion")
return
}
// If still full after expansion, block and wait
dataChan := es.stream.safeGetDataChan()
if dataChan == nil {
return
}
select {
case dataChan <- data:
return
case <-es.stream.done:
return
}
}
// GetStrategyName gets strategy name
func (es *ExpansionStrategy) GetStrategyName() string {
return StrategyExpand
}
// Init initializes expansion strategy
func (es *ExpansionStrategy) Init(stream *Stream, config types.PerformanceConfig) error {
es.stream = stream
return nil
}
// Stop stops and cleans up expansion strategy resources
func (es *ExpansionStrategy) Stop() error {
return nil
}
// DropStrategy drop strategy implementation
type DropStrategy struct {
stream *Stream
}
// NewDropStrategy creates drop strategy instance
func NewDropStrategy() *DropStrategy {
return &DropStrategy{}
}
// ProcessData implements drop mode data processing
func (ds *DropStrategy) ProcessData(data map[string]interface{}) {
// Intelligent non-blocking add with layered backpressure control
if ds.stream.safeSendToDataChan(data) {
return
}
// Data channel is full, use layered backpressure strategy, get channel status
ds.stream.dataChanMux.RLock()
chanLen := len(ds.stream.dataChan)
chanCap := cap(ds.stream.dataChan)
currentDataChan := ds.stream.dataChan
ds.stream.dataChanMux.RUnlock()
usage := float64(chanLen) / float64(chanCap)
// Adjust strategy based on channel usage rate and buffer size
var waitTime time.Duration
var maxRetries int
switch {
case chanCap >= 100000: // Extra large buffer (benchmark mode)
switch {
case usage > 0.99:
waitTime = 1 * time.Millisecond // Longer wait
maxRetries = 3
case usage > 0.95:
waitTime = 500 * time.Microsecond
maxRetries = 2
case usage > 0.90:
waitTime = 100 * time.Microsecond
maxRetries = 1
default:
// Drop immediately
logger.Warn("Data channel is full, dropping input data")
atomic.AddInt64(&ds.stream.droppedCount, 1)
return
}
case chanCap >= 50000: // High performance mode
switch {
case usage > 0.99:
waitTime = 500 * time.Microsecond
maxRetries = 2
case usage > 0.95:
waitTime = 200 * time.Microsecond
maxRetries = 1
case usage > 0.90:
waitTime = 50 * time.Microsecond
maxRetries = 1
default:
logger.Warn("Data channel is full, dropping input data")
atomic.AddInt64(&ds.stream.droppedCount, 1)
return
}
default: // Default mode
switch {
case usage > 0.99:
waitTime = 100 * time.Microsecond
maxRetries = 1
case usage > 0.95:
waitTime = 50 * time.Microsecond
maxRetries = 1
default:
logger.Warn("Data channel is full, dropping input data")
atomic.AddInt64(&ds.stream.droppedCount, 1)
return
}
}
// Multiple retries to add data, using thread-safe approach
for retry := 0; retry < maxRetries; retry++ {
timer := time.NewTimer(waitTime)
select {
case currentDataChan <- data:
// Retry successful
timer.Stop()
return
case <-timer.C:
// Timeout, continue to next retry or drop
if retry == maxRetries-1 {
// Last retry failed, record drop
logger.Warn("Data channel is full, dropping input data")
atomic.AddInt64(&ds.stream.droppedCount, 1)
}
}
}
}
// GetStrategyName gets strategy name
func (ds *DropStrategy) GetStrategyName() string {
return StrategyDrop
}
// Init initializes drop strategy
func (ds *DropStrategy) Init(stream *Stream, config types.PerformanceConfig) error {
ds.stream = stream
return nil
}
// Stop stops and cleans up drop strategy resources
func (ds *DropStrategy) Stop() error {
return nil
}
// StrategyFactory strategy factory
// Uses unified registration mechanism to manage all strategies (built-in and custom)
type StrategyFactory struct {
// Registered strategy mapping
strategies map[string]func() DataProcessingStrategy
mutex sync.RWMutex // Protects concurrent access
}
// NewStrategyFactory creates strategy factory instance
// Automatically registers all built-in strategies
func NewStrategyFactory() *StrategyFactory {
factory := &StrategyFactory{
strategies: make(map[string]func() DataProcessingStrategy),
}
// Register built-in strategies
factory.RegisterStrategy(StrategyBlock, func() DataProcessingStrategy { return NewBlockingStrategy() })
factory.RegisterStrategy(StrategyExpand, func() DataProcessingStrategy { return NewExpansionStrategy() })
factory.RegisterStrategy(StrategyDrop, func() DataProcessingStrategy { return NewDropStrategy() })
return factory
}
// RegisterStrategy registers strategy to factory
// Parameters:
// - name: strategy name
// - constructor: strategy constructor function
func (sf *StrategyFactory) RegisterStrategy(name string, constructor func() DataProcessingStrategy) {
sf.mutex.Lock()
defer sf.mutex.Unlock()
sf.strategies[name] = constructor
}
// UnregisterStrategy unregisters strategy
// Parameters:
// - name: strategy name
func (sf *StrategyFactory) UnregisterStrategy(name string) {
sf.mutex.Lock()
defer sf.mutex.Unlock()
delete(sf.strategies, name)
}
// GetRegisteredStrategies gets all registered strategy names
// Returns:
// - []string: strategy name list
func (sf *StrategyFactory) GetRegisteredStrategies() []string {
sf.mutex.RLock()
defer sf.mutex.RUnlock()
names := make([]string, 0, len(sf.strategies))
for name := range sf.strategies {
names = append(names, name)
}
return names
}
// CreateStrategy creates corresponding strategy instance based on strategy name
// Parameters:
// - strategyName: strategy name
//
// Returns:
// - DataProcessingStrategy: strategy instance
// - error: error information
func (sf *StrategyFactory) CreateStrategy(strategyName string) (DataProcessingStrategy, error) {
sf.mutex.RLock()
constructor, exists := sf.strategies[strategyName]
sf.mutex.RUnlock()
if !exists {
// If strategy doesn't exist, use default drop strategy
sf.mutex.RLock()
defaultConstructor, defaultExists := sf.strategies[StrategyDrop]
sf.mutex.RUnlock()
if defaultExists {
return defaultConstructor(), nil
}
// If even default strategy doesn't exist, return error
return nil, fmt.Errorf("strategy '%s' not found and no default strategy available", strategyName)
}
return constructor(), nil
}