/
auction.go
96 lines (77 loc) · 1.54 KB
/
auction.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
package tyche
import (
"container/heap"
"github.com/elos/autonomous"
"github.com/elos/models"
)
type Potentiality interface {
Grant()
}
type Bid struct {
Action *models.Action
Salience float64
Registree string
}
type Auction struct {
*autonomous.Core
Leaders chan *Bid
*PriorityQueue
Orders chan *Bid
Cancels chan string
books map[string]*Item
leader *Bid
}
func NewAuction() *Auction {
pq := make(PriorityQueue, 0)
heap.Init(&pq)
return &Auction{
Core: autonomous.NewCore(),
Cancels: make(chan string),
Leaders: make(chan *Bid),
Orders: make(chan *Bid),
PriorityQueue: &pq,
books: make(map[string]*Item),
}
}
func (a *Auction) Start() {
Run:
for {
select {
case b := <-a.Orders:
apriori, ok := a.books[b.Registree]
if !ok {
apriori := &Item{
value: b,
priority: b.Salience,
}
a.books[b.Registree] = apriori
a.PriorityQueue.Push(apriori)
} else {
a.PriorityQueue.update(apriori, b, b.Salience)
}
case registree := <-a.Cancels:
record, ok := a.books[registree]
if !ok {
return
}
heap.Remove(a.PriorityQueue, record.index)
delete(a.books, registree)
case <-a.Stopper:
break Run
}
if max := a.PriorityQueue.max().value.(*Bid); max != a.leader {
a.leader = max
a.Leaders <- a.leader
}
}
}
func (a *Auction) Bid(as string, salience float64, action *models.Action) {
a.Orders <- &Bid{
Registree: as,
Salience: salience,
Action: action,
}
}
func (a *Auction) Forfeit(as string) {
a.Cancels <- as
}