0
Fork 0
mirror of https://codeberg.org/SafeTwitch/safetwitch-backend.git synced 2024-12-21 20:53:00 -05:00

Fix concurrent read and errors by using Mutex

This commit is contained in:
dragongoose 2023-06-08 07:50:34 -04:00
parent cdea6bd093
commit ce25f0fd88
No known key found for this signature in database
GPG key ID: 50DB99B921579009
4 changed files with 40 additions and 17 deletions

View file

@ -67,7 +67,11 @@ func (c *Client) Write() {
}
func (c *Client) Close() {
close(c.send)
_, ok := <-c.send
if ok {
close(c.send)
}
c.Conn.Close()
}

View file

@ -6,14 +6,12 @@ import (
func ClientMessageHandler(client *Client, msg string) {
splitMsg := strings.Split(msg, " ")
if len(splitMsg) == 2 && splitMsg[0] == "JOIN" {
client.send <- "OK"
client.FollowingStreamers[splitMsg[1]] = true
FollowStreamer(splitMsg[1])
return
} else {
client.Close()
}
client.send <- "Invalid request"
client.Close()
}

View file

@ -1,24 +1,41 @@
package chat
type ClientMap map[*Client]bool
import (
"sync"
)
var ClientHandler = ClientMap{}
func (c ClientMap) AddClient(client *Client) {
c[client] = true
type ClientMap struct {
Clients map[*Client]bool
sync.Mutex
}
func (c ClientMap) DeleteClient(ID string) {
for client := range c {
var ClientHandler = ClientMap{
Clients: map[*Client]bool{},
Mutex: sync.Mutex{},
}
func (c *ClientMap) AddClient(client *Client) {
c.Lock()
c.Clients[client] = true
c.Unlock()
}
func (c *ClientMap) DeleteClient(ID string) {
c.Lock()
for client := range c.Clients {
if client.ID == ID {
delete(c, client)
delete(c.Clients, client)
}
}
c.Unlock()
}
func (c ClientMap) FindClientsByStreamer(streamer string) []*Client {
func (c *ClientMap) FindClientsByStreamer(streamer string) []*Client {
c.Lock()
var clients []*Client
for client := range c {
for client := range c.Clients {
// check if the client is following the given streamer
for s, _ := range client.FollowingStreamers {
if s == streamer {
@ -27,5 +44,6 @@ func (c ClientMap) FindClientsByStreamer(streamer string) []*Client {
}
}
}
c.Unlock()
return clients
}

View file

@ -178,11 +178,13 @@ func SendMessage(msg string) error {
// function to check and remove unused streamers from server map
func RemoveUnusedStreamers() {
ClientHandler.Lock()
for streamer := range streamersFollowing {
found := false
// iterate over each client and their streamer map
for client, _ := range ClientHandler {
if client.FollowingStreamers[streamer] == true {
for client, _ := range ClientHandler.Clients {
if client.FollowingStreamers[streamer] {
found = true
break
}
@ -193,4 +195,5 @@ func RemoveUnusedStreamers() {
sendMessage("PART #" + streamer)
}
}
ClientHandler.Unlock()
}