-
Notifications
You must be signed in to change notification settings - Fork 0
/
recordsales.go
329 lines (278 loc) · 8.69 KB
/
recordsales.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package main
import (
"flag"
"fmt"
"io/ioutil"
"log"
"time"
"github.com/brotherlogic/goserver"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
pbgd "github.com/brotherlogic/godiscogs/proto"
pbg "github.com/brotherlogic/goserver/proto"
"github.com/brotherlogic/goserver/utils"
pbrc "github.com/brotherlogic/recordcollection/proto"
rcpb "github.com/brotherlogic/recordcollection/proto"
pb "github.com/brotherlogic/recordsales/proto"
)
type getter interface {
getListedRecords(ctx context.Context) ([]*pbrc.Record, error)
updatePrice(ctx context.Context, instanceID, price int32) error
updateCategory(ctx context.Context, instanceID int32, category pbrc.ReleaseMetadata_Category)
expireSale(ctx context.Context, instanceID int32) error
loadRecord(ctx context.Context, instanceID int32) (*pbrc.Record, error)
getPrice(ctx context.Context, id int32) (float32, error)
}
type prodGetter struct {
dial func(ctx context.Context, server string) (*grpc.ClientConn, error)
}
func (p *prodGetter) getListedRecords(ctx context.Context) ([]*pbrc.Record, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return nil, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
r, err := client.QueryRecords(ctx, &pbrc.QueryRecordsRequest{Query: &pbrc.QueryRecordsRequest_Category{pbrc.ReleaseMetadata_LISTED_TO_SELL}})
if err != nil {
return nil, err
}
instanceIds := r.GetInstanceIds()
r, err = client.QueryRecords(ctx, &pbrc.QueryRecordsRequest{Query: &pbrc.QueryRecordsRequest_Category{pbrc.ReleaseMetadata_STALE_SALE}})
if err != nil {
return nil, err
}
instanceIds = append(instanceIds, r.GetInstanceIds()...)
records := []*pbrc.Record{}
for _, id := range instanceIds {
r, err := client.GetRecord(ctx, &pbrc.GetRecordRequest{InstanceId: id})
if err != nil {
return nil, err
}
records = append(records, r.GetRecord())
}
return records, nil
}
func (p *prodGetter) updateCategory(ctx context.Context, instanceID int32, category pbrc.ReleaseMetadata_Category) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
update := &pbrc.UpdateRecordRequest{Reason: "RecordSales-updateCategory", Update: &pbrc.Record{Release: &pbgd.Release{InstanceId: instanceID}, Metadata: &pbrc.ReleaseMetadata{Category: category}}}
client.UpdateRecord(ctx, update)
}
func (p *prodGetter) getPrice(ctx context.Context, id int32) (float32, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return -1, err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
res, err := client.GetPrice(ctx, &pbrc.GetPriceRequest{Id: id})
if err != nil {
return -1, err
}
return res.GetPrice(), err
}
func (p *prodGetter) loadRecord(ctx context.Context, instanceID int32) (*pbrc.Record, error) {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return nil, err
}
defer conn.Close()
client := rcpb.NewRecordCollectionServiceClient(conn)
resp, err := client.GetRecord(ctx, &rcpb.GetRecordRequest{InstanceId: instanceID})
if err != nil {
return nil, err
}
return resp.GetRecord(), err
}
func (p *prodGetter) updatePrice(ctx context.Context, instanceID, price int32) error {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
update := &pbrc.UpdateRecordRequest{Reason: "RecordSales-updatePrice", Update: &pbrc.Record{Release: &pbgd.Release{InstanceId: instanceID}, Metadata: &pbrc.ReleaseMetadata{NewSalePrice: price}}}
_, err = client.UpdateRecord(ctx, update)
return err
}
func (p *prodGetter) expireSale(ctx context.Context, instanceID int32) error {
conn, err := p.dial(ctx, "recordcollection")
if err != nil {
return err
}
defer conn.Close()
client := pbrc.NewRecordCollectionServiceClient(conn)
update := &pbrc.UpdateRecordRequest{Reason: "RecordSales-expireSale", Update: &pbrc.Record{Release: &pbgd.Release{InstanceId: instanceID}, Metadata: &pbrc.ReleaseMetadata{ExpireSale: true}}}
_, err = client.UpdateRecord(ctx, update)
return err
}
const (
// KEY - where we store sale info
KEY = "/github.com/brotherlogic/recordsales/config"
PRICES = "/github.com/brotherlogic/recordsales/prices/%v"
)
// Server main server type
type Server struct {
*goserver.GoServer
config *pb.Config
getter getter
updates int64
testing bool
}
// Init builds the server
func Init() *Server {
s := &Server{
&goserver.GoServer{},
&pb.Config{},
&prodGetter{},
int64(0),
true,
}
s.getter = &prodGetter{s.FDialServer}
return s
}
var (
maxLen = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordsales_max",
Help: "The max number of sales",
})
sizes = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "recordsales_lens",
Help: "The max number of sales",
}, []string{"category"})
)
func (s *Server) save(ctx context.Context, config *pb.Config) error {
s.metrics(config)
s.CtxLog(ctx, fmt.Sprintf("FILESAVE: %v", config.GetSales()))
return s.KSclient.Save(ctx, KEY, config)
}
func (s *Server) load(ctx context.Context) (*pb.Config, error) {
config := &pb.Config{}
data, _, err := s.KSclient.Read(ctx, KEY, config)
if err != nil {
return nil, err
}
config = data.(*pb.Config)
s.CtxLog(ctx, fmt.Sprintf("FILELOAD: %v", config.GetSales()))
config.Archives = s.trimList(ctx, s.config.Archives)
s.metrics(config)
return config, nil
}
func (s *Server) loadHistory(ctx context.Context, id int32) (*pb.Prices, error) {
prices := &pb.Prices{}
data, _, err := s.KSclient.Read(ctx, fmt.Sprintf(PRICES, id), prices)
if err != nil {
if status.Code(err) == codes.FailedPrecondition {
prices = &pb.Prices{History: make([]*pb.PriceHistory, 0)}
}
} else {
prices = data.(*pb.Prices)
}
return prices, nil
}
func (s *Server) saveHistory(ctx context.Context, id int32, prices *pb.Prices) error {
return s.KSclient.Save(ctx, fmt.Sprintf(PRICES, id), prices)
}
// DoRegister does RPC registration
func (s *Server) DoRegister(server *grpc.Server) {
pb.RegisterSaleServiceServer(server, s)
rcpb.RegisterClientUpdateServiceServer(server, s)
}
// ReportHealth alerts if we're not healthy
func (s *Server) ReportHealth() bool {
return true
}
// Shutdown the server
func (s *Server) Shutdown(ctx context.Context) error {
return nil
}
// Mote promotes/demotes this server
func (s *Server) Mote(ctx context.Context, master bool) error {
return nil
}
// GetState gets the state of the server
func (s *Server) GetState() []*pbg.State {
vals := ""
for _, a := range s.config.Archives {
if a.InstanceId == 19867545 {
vals += fmt.Sprintf("%v [%v],", a.Price, time.Unix(a.LastUpdateTime, 0))
}
}
sum := int32(0)
pr := int32(0)
oldest := time.Now().Unix()
for _, s := range s.config.Sales {
if s.LastUpdateTime < oldest {
oldest = s.LastUpdateTime
}
sum += s.Price
if s.InstanceId == 330510403 {
pr += s.Price
}
}
return []*pbg.State{
&pbg.State{Key: "oldest", TimeValue: oldest},
&pbg.State{Key: "last_sale_run", TimeValue: s.config.LastSaleRun},
&pbg.State{Key: "active_sales", Value: int64(len(s.config.Sales))},
&pbg.State{Key: "archive_sales", Value: int64(len(s.config.Archives))},
&pbg.State{Key: "updates", Value: s.updates},
&pbg.State{Key: "sum_sales", Value: int64(sum)},
&pbg.State{Key: "tracker", Text: vals},
&pbg.State{Key: "test", Text: "testing123"},
&pbg.State{Key: "trac", Value: int64(pr)},
}
}
var (
sales = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordsales_sales",
Help: "The number of sales",
})
cost = promauto.NewGaugeVec(prometheus.GaugeOpts{
Name: "recordsales_costs",
Help: "The amount of potential salve value",
}, []string{"id"})
nextUpdateTime = promauto.NewGauge(prometheus.GaugeOpts{
Name: "recordsales_update_time",
Help: "The number of sales",
})
)
func main() {
var quiet = flag.Bool("quiet", false, "Show all output")
flag.Parse()
//Turn off logging
if *quiet {
log.SetFlags(0)
log.SetOutput(ioutil.Discard)
}
server := Init()
server.PrepServer("recordsales")
server.Register = server
err := server.RegisterServerV2(false)
if err != nil {
return
}
ctx, cancel := utils.ManualContext("recordsales-firstload", time.Minute)
config, err := server.load(ctx)
cancel()
code := status.Convert(err).Code()
if code == codes.NotFound {
// Silent quit if we can't read sales because of missing keystore
return
}
if code != codes.OK {
log.Fatalf("Unable to read sales: %v", err)
}
server.metrics(config)
// Stop updating sales
//go server.runSales()
fmt.Printf("%v", server.Serve())
}