Repository navigation
Expand file tree
/
Copy pathwatcher.go
More file actions
644 lines (529 loc) · 15.9 KB
/
Copy pathwatcher.go
File metadata and controls
644 lines (529 loc) · 15.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
package confy
// Config watcher and source files use error handlers that don't return errors.
import (
"context"
"fmt"
"sync"
"time"
errors "github.com/xraph/go-utils/errs"
logger "github.com/xraph/go-utils/log"
"github.com/xraph/go-utils/metrics"
)
// Watcher handles watching configuration sources for changes.
type Watcher struct {
interval time.Duration
sources map[string]*WatchContext
callbacks map[string][]SourceEventHandler
changeHandlers map[string]func(string, map[string]any)
logger logger.Logger
metrics metrics.Metrics
errorHandler errors.ErrorHandler
mu sync.RWMutex
stopChannels map[string]chan struct{}
stopped bool
}
// WatcherConfig contains configuration for the watcher.
type WatcherConfig struct {
Interval time.Duration
BufferSize int
MaxRetries int
RetryInterval time.Duration
Logger logger.Logger
Metrics metrics.Metrics
ErrorHandler errors.ErrorHandler
EnableDebounce bool
DebounceTime time.Duration
}
// WatchEvent represents a configuration change event.
type WatchEvent struct {
SourceName string `json:"source_name"`
EventType WatchEventType `json:"event_type"`
Data map[string]any `json:"data"`
Timestamp time.Time `json:"timestamp"`
Checksum string `json:"checksum,omitempty"`
Error error `json:"error,omitempty"`
}
// WatchEventType represents the type of watch event.
type WatchEventType string
const (
WatchEventTypeChange WatchEventType = "change"
WatchEventTypeCreate WatchEventType = "create"
WatchEventTypeDelete WatchEventType = "delete"
WatchEventTypeError WatchEventType = "error"
WatchEventTypeReload WatchEventType = "reload"
)
// WatchCallback represents a callback function for configuration changes.
type WatchCallback func(string, map[string]any)
// ChangeDetector detects changes in configuration data.
type ChangeDetector interface {
DetectChanges(old, new map[string]any) []ConfigChange
CalculateChecksum(data map[string]any) string
}
// FileWatcher represents a file system watcher.
type FileWatcher interface {
Watch(path string, callback func(string)) error
Stop() error
}
// NewWatcher creates a new configuration watcher.
func NewWatcher(config WatcherConfig) *Watcher {
if config.Interval == 0 {
config.Interval = 30 * time.Second
}
if config.BufferSize == 0 {
config.BufferSize = 100
}
if config.MaxRetries == 0 {
config.MaxRetries = 3
}
if config.RetryInterval == 0 {
config.RetryInterval = 5 * time.Second
}
if config.DebounceTime == 0 {
config.DebounceTime = 1 * time.Second
}
return &Watcher{
interval: config.Interval,
sources: make(map[string]*WatchContext),
callbacks: make(map[string][]SourceEventHandler),
changeHandlers: make(map[string]func(string, map[string]any)),
logger: config.Logger,
metrics: config.Metrics,
errorHandler: config.ErrorHandler,
stopChannels: make(map[string]chan struct{}),
stopped: false,
}
}
// WatchSource starts watching a configuration source.
func (w *Watcher) WatchSource(ctx context.Context, source ConfigSource, callback WatchCallback) error {
if !source.IsWatchable() {
return ErrConfigError(fmt.Sprintf("source %s is not watchable", source.Name()), nil)
}
w.mu.Lock()
defer w.mu.Unlock()
if w.stopped {
return ErrConfigError("watcher is stopped", nil)
}
sourceName := source.Name()
// Check if already watching
if _, exists := w.sources[sourceName]; exists {
return ErrConfigError("already watching source "+sourceName, nil)
}
// Create watch context
watchCtx := &WatchContext{
Source: source,
Interval: w.interval,
LastCheck: time.Now(),
ChangeCount: 0,
ErrorCount: 0,
Active: true,
}
w.sources[sourceName] = watchCtx
w.changeHandlers[sourceName] = callback
// Create stop channel
stopChan := make(chan struct{})
w.stopChannels[sourceName] = stopChan
// Start watching in a goroutine
go w.watchSourceLoop(ctx, source, callback, stopChan)
if w.logger != nil {
w.logger.Info("started watching configuration source",
logger.String("source", sourceName),
logger.Duration("interval", w.interval),
)
}
if w.metrics != nil {
w.metrics.Counter("config.watcher.sources_started").Inc()
w.metrics.Gauge("config.watcher.active_sources").Set(float64(len(w.sources)))
}
return nil
}
// StopWatching stops watching a specific source.
func (w *Watcher) StopWatching(sourceName string) error {
w.mu.Lock()
defer w.mu.Unlock()
watchCtx, exists := w.sources[sourceName]
if !exists {
return ErrConfigError("not watching source "+sourceName, nil)
}
// Signal stop
if stopChan, exists := w.stopChannels[sourceName]; exists {
close(stopChan)
delete(w.stopChannels, sourceName)
}
// Update context
watchCtx.Active = false
// Clean up
delete(w.sources, sourceName)
delete(w.changeHandlers, sourceName)
if w.logger != nil {
w.logger.Info("stopped watching configuration source",
logger.String("source", sourceName),
)
}
if w.metrics != nil {
w.metrics.Counter("config.watcher.sources_stopped").Inc()
w.metrics.Gauge("config.watcher.active_sources").Set(float64(len(w.sources)))
}
return nil
}
// StopAll stops watching all sources.
func (w *Watcher) StopAll() error {
w.mu.Lock()
defer w.mu.Unlock()
w.stopped = true
// Stop all sources
for sourceName := range w.sources {
if stopChan, exists := w.stopChannels[sourceName]; exists {
close(stopChan)
}
}
// Clear all data
w.sources = make(map[string]*WatchContext)
w.changeHandlers = make(map[string]func(string, map[string]any))
w.stopChannels = make(map[string]chan struct{})
if w.logger != nil {
w.logger.Info("stopped watching all configuration sources")
}
if w.metrics != nil {
w.metrics.Counter("config.watcher.stopped_all").Inc()
w.metrics.Gauge("config.watcher.active_sources").Set(0)
}
return nil
}
// GetWatchedSources returns the list of currently watched sources.
func (w *Watcher) GetWatchedSources() []string {
w.mu.RLock()
defer w.mu.RUnlock()
sources := make([]string, 0, len(w.sources))
for sourceName := range w.sources {
sources = append(sources, sourceName)
}
return sources
}
// GetSourceStats returns statistics for a watched source.
func (w *Watcher) GetSourceStats(sourceName string) (*WatchStats, error) {
w.mu.RLock()
defer w.mu.RUnlock()
watchCtx, exists := w.sources[sourceName]
if !exists {
return nil, ErrConfigError(fmt.Sprintf("source %s is not being watched", sourceName), nil)
}
return &WatchStats{
SourceName: sourceName,
Active: watchCtx.Active,
LastCheck: watchCtx.LastCheck,
ChangeCount: watchCtx.ChangeCount,
ErrorCount: watchCtx.ErrorCount,
Interval: watchCtx.Interval,
Uptime: time.Since(watchCtx.LastCheck),
}, nil
}
// GetAllStats returns statistics for all watched sources.
func (w *Watcher) GetAllStats() map[string]*WatchStats {
w.mu.RLock()
defer w.mu.RUnlock()
stats := make(map[string]*WatchStats)
for sourceName, watchCtx := range w.sources {
stats[sourceName] = &WatchStats{
SourceName: sourceName,
Active: watchCtx.Active,
LastCheck: watchCtx.LastCheck,
ChangeCount: watchCtx.ChangeCount,
ErrorCount: watchCtx.ErrorCount,
Interval: watchCtx.Interval,
Uptime: time.Since(watchCtx.LastCheck),
}
}
return stats
}
// watchSourceLoop is the main watching loop for a source.
func (w *Watcher) watchSourceLoop(ctx context.Context, source ConfigSource, callback WatchCallback, stopChan chan struct{}) {
sourceName := source.Name()
ticker := time.NewTicker(w.interval)
defer ticker.Stop()
var (
lastData map[string]any
lastChecksum string
)
// Initial load
if data, err := source.Load(ctx); err == nil {
lastData = data
lastChecksum = w.calculateChecksum(data)
} else {
w.handleWatchError(sourceName, err)
}
for {
select {
case <-ctx.Done():
return
case <-stopChan:
return
case <-ticker.C:
w.checkForChanges(ctx, source, &lastData, &lastChecksum, callback)
}
}
}
// checkForChanges checks for changes in a configuration source.
func (w *Watcher) checkForChanges(ctx context.Context, source ConfigSource, lastData *map[string]any, lastChecksum *string, callback WatchCallback) {
sourceName := source.Name()
// Update last check time
w.mu.Lock()
if watchCtx, exists := w.sources[sourceName]; exists {
watchCtx.LastCheck = time.Now()
}
w.mu.Unlock()
// Load current data
currentData, err := source.Load(ctx)
if err != nil {
w.handleWatchError(sourceName, err)
return
}
// Calculate checksum
currentChecksum := w.calculateChecksum(currentData)
// Check if data has changed
if *lastChecksum != "" && currentChecksum != *lastChecksum {
// Data has changed
w.handleChange(sourceName, *lastData, currentData, callback)
// Update change count
w.mu.Lock()
if watchCtx, exists := w.sources[sourceName]; exists {
watchCtx.ChangeCount++
}
w.mu.Unlock()
if w.metrics != nil {
w.metrics.Counter("config.watcher.changes_detected").Inc()
}
}
// Update last data and checksum
*lastData = currentData
*lastChecksum = currentChecksum
}
// handleChange handles a configuration change.
func (w *Watcher) handleChange(sourceName string, oldData, newData map[string]any, callback WatchCallback) {
if w.logger != nil {
w.logger.Info("configuration change detected",
logger.String("source", sourceName),
logger.Int("old_keys", len(oldData)),
logger.Int("new_keys", len(newData)),
)
}
// Create change event
event := WatchEvent{
SourceName: sourceName,
EventType: WatchEventTypeChange,
Data: newData,
Timestamp: time.Now(),
Checksum: w.calculateChecksum(newData),
}
// Notify callback
if callback != nil {
go func() {
defer func() {
if r := recover(); r != nil {
if w.logger != nil {
w.logger.Error("panic in watch callback",
logger.String("source", sourceName),
logger.Any("panic", r),
)
}
}
}()
callback(sourceName, newData)
}()
}
// Notify event handlers
w.notifyEventHandlers(sourceName, event)
}
// handleWatchError handles errors during watching.
func (w *Watcher) handleWatchError(sourceName string, err error) {
// Update error count
w.mu.Lock()
if watchCtx, exists := w.sources[sourceName]; exists {
watchCtx.ErrorCount++
}
w.mu.Unlock()
if w.logger != nil {
w.logger.Error("error watching configuration source",
logger.String("source", sourceName),
logger.Error(err),
)
}
if w.errorHandler != nil {
_ = w.errorHandler.HandleError(context.Background(), ErrConfigError("watch error for source "+sourceName, err))
}
if w.metrics != nil {
w.metrics.Counter("config.watcher.errors").Inc()
}
// Create error event
event := WatchEvent{
SourceName: sourceName,
EventType: WatchEventTypeError,
Timestamp: time.Now(),
Error: err,
}
// Notify event handlers
w.notifyEventHandlers(sourceName, event)
}
// RegisterEventHandler registers an event handler for a source.
func (w *Watcher) RegisterEventHandler(sourceName string, handler SourceEventHandler) {
w.mu.Lock()
defer w.mu.Unlock()
if w.callbacks[sourceName] == nil {
w.callbacks[sourceName] = make([]SourceEventHandler, 0)
}
w.callbacks[sourceName] = append(w.callbacks[sourceName], handler)
if w.logger != nil {
w.logger.Debug("event handler registered",
logger.String("source", sourceName),
)
}
}
// UnregisterEventHandler unregisters an event handler for a source.
func (w *Watcher) UnregisterEventHandler(sourceName string, handler SourceEventHandler) {
w.mu.Lock()
defer w.mu.Unlock()
handlers := w.callbacks[sourceName]
for i, h := range handlers {
if h == handler {
w.callbacks[sourceName] = append(handlers[:i], handlers[i+1:]...)
break
}
}
if w.logger != nil {
w.logger.Debug("event handler unregistered",
logger.String("source", sourceName),
)
}
}
// notifyEventHandlers notifies all registered event handlers.
func (w *Watcher) notifyEventHandlers(sourceName string, event WatchEvent) {
w.mu.RLock()
handlers := w.callbacks[sourceName]
w.mu.RUnlock()
for _, handler := range handlers {
go func(h SourceEventHandler) {
defer func() {
if r := recover(); r != nil {
if w.logger != nil {
w.logger.Error("panic in event handler",
logger.String("source", sourceName),
logger.Any("panic", r),
)
}
}
}()
sourceEvent := SourceEvent{
SourceName: event.SourceName,
EventType: string(event.EventType),
Data: event.Data,
Timestamp: event.Timestamp,
Error: event.Error,
}
if err := h.HandleEvent(sourceEvent); err != nil {
if w.logger != nil {
w.logger.Error("error in event handler",
logger.String("source", sourceName),
logger.Error(err),
)
}
}
}(handler)
}
}
// calculateChecksum calculates a simple checksum for configuration data.
func (w *Watcher) calculateChecksum(data map[string]any) string {
// Simple checksum based on string representation
// In production, you might want to use a proper hash function
return fmt.Sprintf("%x", fmt.Sprintf("%v", data))
}
// WatchStats contains statistics about a watched source.
type WatchStats struct {
SourceName string `json:"source_name"`
Active bool `json:"active"`
LastCheck time.Time `json:"last_check"`
ChangeCount int64 `json:"change_count"`
ErrorCount int64 `json:"error_count"`
Interval time.Duration `json:"interval"`
Uptime time.Duration `json:"uptime"`
}
// DefaultChangeDetector is a simple implementation of ChangeDetector.
type DefaultChangeDetector struct{}
func (d *DefaultChangeDetector) DetectChanges(old, new map[string]any) []ConfigChange {
var changes []ConfigChange
timestamp := time.Now()
// Check for added/modified keys
for key, newValue := range new {
if oldValue, exists := old[key]; exists {
if fmt.Sprintf("%v", oldValue) != fmt.Sprintf("%v", newValue) {
changes = append(changes, ConfigChange{
Type: ChangeTypeUpdate,
Key: key,
OldValue: oldValue,
NewValue: newValue,
Timestamp: timestamp,
})
}
} else {
changes = append(changes, ConfigChange{
Type: ChangeTypeSet,
Key: key,
NewValue: newValue,
Timestamp: timestamp,
})
}
}
// Check for deleted keys
for key, oldValue := range old {
if _, exists := new[key]; !exists {
changes = append(changes, ConfigChange{
Type: ChangeTypeDelete,
Key: key,
OldValue: oldValue,
Timestamp: timestamp,
})
}
}
return changes
}
func (d *DefaultChangeDetector) CalculateChecksum(data map[string]any) string {
return fmt.Sprintf("%x", fmt.Sprintf("%v", data))
}
// DebounceWatcher wraps another watcher with debouncing functionality.
type DebounceWatcher struct {
*Watcher
debounceTime time.Duration
timers map[string]*time.Timer
mu sync.Mutex
}
// NewDebounceWatcher creates a watcher with debouncing.
func NewDebounceWatcher(config WatcherConfig, debounceTime time.Duration) *DebounceWatcher {
return &DebounceWatcher{
Watcher: NewWatcher(config),
debounceTime: debounceTime,
timers: make(map[string]*time.Timer),
}
}
// WatchSource starts watching with debouncing.
func (dw *DebounceWatcher) WatchSource(ctx context.Context, source ConfigSource, callback WatchCallback) error {
// Wrap the callback with debouncing
debouncedCallback := func(sourceName string, data map[string]any) {
dw.debounceCallback(sourceName, data, callback)
}
return dw.Watcher.WatchSource(ctx, source, debouncedCallback)
}
// debounceCallback implements debouncing for configuration changes.
func (dw *DebounceWatcher) debounceCallback(sourceName string, data map[string]any, callback WatchCallback) {
dw.mu.Lock()
defer dw.mu.Unlock()
// Cancel existing timer
if timer, exists := dw.timers[sourceName]; exists {
timer.Stop()
}
// Create new timer
dw.timers[sourceName] = time.AfterFunc(dw.debounceTime, func() {
callback(sourceName, data)
// Clean up timer
dw.mu.Lock()
delete(dw.timers, sourceName)
dw.mu.Unlock()
})
}