summaryrefslogtreecommitdiffstats
path: root/updates.go
blob: 78db802c8d179a29d0ba8fd8ad06b4fd55bbbaee (plain)
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
package main

import (
	"time"
	"sync"
)

const (
	addAction      = 0
	removeAction   = 1
	moveUpAction   = 2
	moveDownAction = 3
)
type Update struct {
	Song *Song
	Action uint
	Timestamp int64
	Next *Update
}
type Listener struct {
	L chan bool
	Next *Listener
}

var headUpdates map[int]*Update
var tailUpdates map[int]*Update
var listeners map[int]*Listener
var updateLock sync.Mutex

func init() {
	headUpdates = make(map[int]*Update)
	tailUpdates = make(map[int]*Update)
	listeners = make(map[int]*Listener)
}

func addUpdate(pid int, action uint, song *Song) {
	update := new(Update)
	update.Song = song
	update.Action = action
	update.Timestamp = time.Nanoseconds()

	updateLock.Lock()
	defer updateLock.Unlock()

	pup := tailUpdates[pid]
	if pup != nil {
		pup.Next = update
	} else {
		headUpdates[pid] = update
	}
	tailUpdates[pid] = update

	listener := listeners[pid]
	for listener != nil {
		listener.L <- true
		listener = listener.Next
	}
	listeners[pid] = nil
}

// assumes locked
func checkUpdates(pid int, timestamp int64) *Update {
	pup, _ := headUpdates[pid]
	for pup != nil {
		if pup.Timestamp > timestamp {
			return pup
		}
		pup = pup.Next
	}
	return nil
}

func getUpdates(id string, timestamp int64) *Update {
	db := <-dbPool
	pid := getpid(db, id)
	dbPool <- db
	if pid == -1 {
		return nil
	}

	updateLock.Lock()
	pup := checkUpdates(pid, timestamp)
	if pup != nil {
		updateLock.Unlock()
		return pup
	}

	// didn't get updates
	listener := new(Listener)
	listener.L = make(chan bool)
	lhead := listeners[pid]
	if lhead != nil {
		listener.Next = lhead
	}
	listeners[pid] = listener
	updateLock.Unlock()
	<-listener.L

	updateLock.Lock()
	pup = checkUpdates(pid, timestamp)
	updateLock.Unlock()
	return pup
}