-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
98 lines (79 loc) · 2.08 KB
/
example_test.go
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
// example_test.go
package gonsensus_test
import (
"context"
"fmt"
"log"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/thevilledev/gonsensus"
)
func Example() {
// Load AWS configuration
cfg, err := config.LoadDefaultConfig(context.Background())
if err != nil {
log.Printf("Failed to load AWS config: %v", err)
return
}
// Create S3 client
s3Client := s3.NewFromConfig(cfg)
// Create consensus manager config
consensusConfig := gonsensus.Config{
TTL: 30 * time.Second,
PollInterval: 5 * time.Second,
LockPrefix: "consensus/",
NodeID: "example-node-1",
}
// Create consensus manager
manager, err := gonsensus.NewManager(s3Client, "my-bucket-1", consensusConfig)
if err != nil {
log.Printf("Failed to create consensus manager: %v", err)
return
}
// Create worker to handle leader duties
worker := &Worker{nodeID: "example-node-1"}
// Set callbacks
manager.SetCallbacks(worker.OnElected, worker.OnDemoted)
// Create cancellable context
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
// Run consensus manager
go func() {
if err := manager.Run(ctx); err != nil && err != context.Canceled {
fmt.Printf("Consensus manager error: %v\n", err)
}
}()
// Simulate some work
time.Sleep(5 * time.Second)
// Get current leader info
lockInfo, err := manager.GetLockInfo(ctx)
if err != nil {
fmt.Printf("%s: %v\n", gonsensus.ErrFailedToGetLockInfo, err)
return
}
fmt.Printf("Current leader: %s\n", lockInfo.Node)
// Output:
// Node example-node-1 elected as leader
// Current leader: example-node-1
}
// Worker handles leader-specific tasks
type Worker struct {
nodeID string
isLeader bool
mu sync.RWMutex
}
func (w *Worker) OnElected(ctx context.Context) error {
w.mu.Lock()
w.isLeader = true
w.mu.Unlock()
fmt.Printf("Node %s elected as leader\n", w.nodeID)
return nil
}
func (w *Worker) OnDemoted(ctx context.Context) {
w.mu.Lock()
w.isLeader = false
w.mu.Unlock()
fmt.Printf("Node %s demoted from leader\n", w.nodeID)
}