-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
182 lines (160 loc) · 4.43 KB
/
main.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
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
package main
import (
"encoding/json"
"fmt"
"os"
"sync"
"time"
)
// Message struct for messages being published
type Message struct {
Topic string `json:"topic"`
Payload interface{} `json:"payload"`
}
// Subscriber struct represents a subscriber to a topic
type Subscriber struct {
Channel chan interface{}
Unsubscribe chan bool
}
// Broker struct manages subscriptions and publishing
type Broker struct {
subscribers map[string][]*Subscriber
mutex sync.Mutex
messages []Message // Store messages for persistence
}
// NewBroker returns a new instance of Broker
func NewBroker() *Broker {
broker := &Broker{
subscribers: make(map[string][]*Subscriber),
}
broker.loadMessages() // Load messages from file on startup
return broker
}
// Subscribe adds a new subscriber to a topic
func (b *Broker) Subscribe(topic string) *Subscriber {
b.mutex.Lock()
defer b.mutex.Unlock()
subscriber := &Subscriber{
Channel: make(chan interface{}, 10), // Buffered channel to prevent blocking
Unsubscribe: make(chan bool),
}
b.subscribers[topic] = append(b.subscribers[topic], subscriber)
// Send previously stored messages to the new subscriber
for _, msg := range b.messages {
if msg.Topic == topic {
select {
case subscriber.Channel <- msg.Payload:
default: // Avoid blocking if the channel is full
}
}
}
return subscriber
}
// Unsubscribe removes a subscriber from a topic
func (b *Broker) Unsubscribe(topic string, subscriber *Subscriber) {
b.mutex.Lock()
defer b.mutex.Unlock()
if subscribers, found := b.subscribers[topic]; found {
for i, sub := range subscribers {
if sub == subscriber {
close(sub.Channel)
b.subscribers[topic] = append(subscribers[:i], subscribers[i+1:]...)
return
}
}
}
}
// Publish sends a message to all subscribers of a topic and saves it
func (b *Broker) Publish(topic string, payload interface{}) {
b.mutex.Lock()
defer b.mutex.Unlock()
message := Message{Topic: topic, Payload: payload}
b.messages = append(b.messages, message) // Save message for persistence
b.saveMessages() // Save to file
if subscribers, found := b.subscribers[topic]; found {
for _, sub := range subscribers {
select {
case sub.Channel <- payload:
case <-time.After(time.Second):
fmt.Printf("Subscriber is slow, unsubscribing from topic %s\n", topic)
b.Unsubscribe(topic, sub)
}
}
}
}
// DeleteTopic removes all subscribers and the topic itself from the broker
func (b *Broker) DeleteTopic(topic string) {
b.mutex.Lock()
defer b.mutex.Unlock()
// Check if the topic exists
if subscribers, found := b.subscribers[topic]; found {
// Close all subscribers' channels
for _, sub := range subscribers {
close(sub.Channel) // Ensure the channel is cleaned up
}
// Remove the topic from the map
delete(b.subscribers, topic) // Delete the topic
fmt.Printf("Deleted topic %s along with its subscribers.\n", topic)
} else {
fmt.Printf("Topic %s not found.\n", topic)
}
}
// Save messages to a JSON file
func (b *Broker) saveMessages() {
file, err := os.Create("messages.json")
if err != nil {
fmt.Println("Error creating messages file:", err)
return
}
defer file.Close()
encoder := json.NewEncoder(file)
if err := encoder.Encode(b.messages); err != nil {
fmt.Println("Error encoding messages:", err)
}
}
// Load messages from a JSON file
func (b *Broker) loadMessages() {
file, err := os.Open("messages.json")
if err != nil {
if os.IsNotExist(err) {
return // No previous messages
}
fmt.Println("Error opening messages file:", err)
return
}
defer file.Close()
decoder := json.NewDecoder(file)
if err := decoder.Decode(&b.messages); err != nil {
fmt.Println("Error decoding messages:", err)
}
}
// Main function to run the broker
func main() {
broker := NewBroker()
subscriber := broker.Subscribe("GSoC")
go func() {
for {
select {
case msg, ok := <-subscriber.Channel:
if !ok {
fmt.Println("Channel closed")
return
}
fmt.Printf("Received: %s\n", msg)
case <-subscriber.Unsubscribe:
fmt.Println("Unsubscribed")
return
}
}
}()
broker.Publish("GSoC", "Hello GSoC!")
time.Sleep(2 * time.Second)
broker.Unsubscribe("GSoC", subscriber)
broker.Publish("arpit", "ho gya")
time.Sleep(time.Second)
// Delete the topic "GSoC"
broker.DeleteTopic("GSoC")
//broker.Publish("GSoC", "This should not be received")
// You can delete other topics similarly
broker.DeleteTopic("arpit")
}