M cmd/tallyard/main.go => cmd/tallyard/main.go +2 -2
@@ 55,9 55,9 @@ func main() {
if data.Elections == nil {
data.Elections = election.NewElectionsMap()
}
- data.Elections.Save = func() {
+ data.Elections.SetSave(func() {
data.Save()
- }
+ })
syncer := client.Syncer.(*mautrix.DefaultSyncer)
syncer.OnEvent(client.Store.(*mautrix.InMemoryStore).UpdateState)
M election/election.go => election/election.go +1 -2
@@ 26,7 26,7 @@ type Election struct {
func NewElection(candidates []Candidate, createEventId id.EventID,
creationTimestamp int64, creator id.UserID, roomID id.RoomID,
- title string, save func()) *Election {
+ title string) *Election {
return &Election{
Candidates: candidates,
CreateEventId: createEventId,
@@ 34,7 34,6 @@ func NewElection(candidates []Candidate, createEventId id.EventID,
Creator: creator,
Joins: make(map[id.EventID]*Voter),
RoomID: roomID,
- Save: save,
Title: title,
}
}
M election/map.go => election/map.go +15 -0
@@ 45,6 45,18 @@ func (em *ElectionsMap) UnmarshalJSON(b []byte) error {
return nil
}
+func (em *ElectionsMap) SetSave(save func ()) {
+ em.Lock()
+ defer em.Unlock()
+ em.Save = save
+ // ensure old elections have Save set
+ for _, el := range em.M {
+ el.Lock()
+ el.Save = save
+ el.Unlock()
+ }
+}
+
func (em *ElectionsMap) Get(createEventID id.EventID) *Election {
em.RLock()
defer em.RUnlock()
@@ 76,6 88,9 @@ func (em *ElectionsMap) SetIfNotExists(createEventID id.EventID, el *Election) {
}
func (em *ElectionsMap) set(createEventID id.EventID, el *Election) {
+ el.Lock()
+ defer el.Unlock()
+ el.Save = em.Save
em.M[createEventID] = el
em.insort(createEventID, el)
}
M election/msg.go => election/msg.go +1 -1
@@ 95,7 95,7 @@ func OnCreateElectionMessage(evt *event.Event, elections *ElectionsMap) {
return
}
elections.SetIfNotExists(evt.ID, NewElection(content.Candidates, evt.ID,
- evt.Timestamp, evt.Sender, evt.RoomID, content.Title, elections.Save))
+ evt.Timestamp, evt.Sender, evt.RoomID, content.Title))
}
func getElection(client *mautrix.Client, roomID id.RoomID, createEventId id.EventID, elections *ElectionsMap) *Election {