mtsatellite/cmd/mtredisalize/changetracker.go
2014-09-17 17:34:03 +02:00

74 lines
1.5 KiB
Go

package main
import (
"encoding/json"
"log"
"net/http"
"sync"
"bytes"
"bitbucket.org/s_l_teichmann/mtredisalize/common"
)
type quantizedXZ struct {
X, Z int16
}
type ChangeTracker struct {
changes map[quantizedXZ]bool
mutex sync.Mutex
}
func NewChangeTracker() *ChangeTracker {
return &ChangeTracker{changes: make(map[quantizedXZ]bool)}
}
func (ct *ChangeTracker) BlockChanged(key []byte) {
var err error
var coord common.Coord
if coord, err = common.DecodeStringBytesToCoord(key); err != nil {
log.Printf("decoding key failed: %s", err)
return
}
ct.mutex.Lock()
ct.changes[quantizedXZ{X: coord.X / 16, Z: coord.Z / 16}] = true
ct.mutex.Unlock()
}
func (ct *ChangeTracker) FlushChanges(url string) (err error) {
log.Println("change flush triggered")
var oldChanges map[quantizedXZ]bool
var sendNotification bool
ct.mutex.Lock()
oldChanges = ct.changes
if len(oldChanges) > 0 {
sendNotification = true
ct.changes = make(map[quantizedXZ]bool)
}
ct.mutex.Unlock()
if !sendNotification {
return
}
go func() {
changes := make([]quantizedXZ, len(oldChanges))
i := 0
for change, _ := range oldChanges {
changes[i] = change
i++
}
var err error
var encoded []byte
if encoded, err = json.Marshal(changes); err != nil {
log.Printf("WARN: encode changes to JSON failed: %s", err)
return
}
var buf bytes.Buffer
buf.Write(encoded)
if _, err = http.Post(url, "application/json", &buf); err != nil {
log.Printf("WARN: posting changes to %s failed: %s", url, err)
}
}()
return
}