generated from fun-stack/example
-
Notifications
You must be signed in to change notification settings - Fork 4
/
position.go
390 lines (344 loc) · 9.72 KB
/
position.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
package main
import (
"context"
"database/sql"
"fmt"
"math"
"net/http"
"time"
humanize "github.com/dustin/go-humanize"
"github.com/johnwarden/httperror"
"github.com/pkg/errors"
)
type Position struct {
UserID int
StoryID int
PositionID int
Direction int8
EntryTime int64
EntryUpvotes int
EntryExpectedUpvotes float64
EntryUpvoteRate float64
ExitTime sql.NullInt64
ExitUpvotes sql.NullInt64
ExitExpectedUpvotes sql.NullFloat64
ExitUpvoteRate sql.NullFloat64
CurrentUpvotes int
CurrentExpectedUpvotes float64
CurrentUpvoteRate float64
Story
RunningScore float64
Label string
UserScore float64
}
func (p Position) VoteTypeString() string {
switch p.Direction {
case 1:
return "upvoted"
case -1:
return "downvoted"
default:
panic("Invalid direction value")
}
}
func (p Position) EntryTimeString() string {
return humanize.Time(time.Unix(p.EntryTime, 0))
}
func (p Position) EntryUpvoteRateString() string {
return fmt.Sprintf("%.2f", p.EntryUpvoteRate)
}
func (p Position) Exited() bool {
return p.ExitTime.Valid
}
func (p Position) ExitTimeString() string {
// return time.Unix(int64(s.MaxSampleTime), 0).UTC().Format("2006-01-02T15:04")
if !p.ExitTime.Valid {
return ""
}
return humanize.Time(time.Unix(p.ExitTime.Int64, 0))
}
func (p Position) ExitUpvoteRateString() string {
if !p.Exited() {
return ""
}
return fmt.Sprintf("%.2f", p.ExitUpvoteRate.Float64)
}
func (p Position) CurrentUpvoteRateString() string {
return fmt.Sprintf("%.2f", p.CurrentUpvoteRate)
}
func (p Position) UserScoreString() string {
gain := p.UserScore
if math.Abs(gain) < .01 {
return "-"
}
if gain > 0 {
return fmt.Sprintf("+%.2f", gain)
}
return fmt.Sprintf("%.2f", gain)
}
func (p Position) IsGain() bool {
return p.UserScore > 0
}
// Gets every position for the user, along with story details
func (app app) getDetailedPositions(ctx context.Context, userID int) ([]Position, error) {
positions := make([]Position, 0)
db, err := app.ndb.upvotesDBWithDataset(ctx)
if err != nil {
return positions, errors.Wrap(err, "upvotesDBWithDataset")
}
var statement *sql.Stmt
// userIDs < 100 are pseudo-users that upvote randomly according to a strategy
Debugf(app.logger, "Getting positions for user %d", userID)
if userID < 100 {
switch userID {
case 0:
randomNewVoterStmt, err := db.PrepareContext(ctx, fmt.Sprintf(randomVoterSQL, "new", userID))
if err != nil {
return positions, errors.Wrap(err, "Preparing randomNewVoterStmt")
}
statement = randomNewVoterStmt
case 1:
randomTopVoterStmt, err := db.PrepareContext(ctx, fmt.Sprintf(randomVoterSQL, "top", userID))
if err != nil {
return positions, errors.Wrapf(err, "Preparing randomTopVoterStmt %s", fmt.Sprintf(randomVoterSQL, "top"))
}
statement = randomTopVoterStmt
case 2:
everyStoryVoter, err := db.PrepareContext(ctx, fmt.Sprintf(everyStoryVoterSQL, userID, 1))
if err != nil {
return positions, errors.Wrap(err, "Preparing everyStoryVoter")
}
statement = everyStoryVoter
case 3:
everyStoryDownVoter, err := db.PrepareContext(ctx, fmt.Sprintf(everyStoryVoterSQL, userID, -1))
if err != nil {
return positions, errors.Wrap(err, "Preparing everyStoryVoter")
}
statement = everyStoryDownVoter
default:
return positions, httperror.PublicErrorf(http.StatusUnauthorized, "Unknown user ID")
}
// These special user IDs are causing the app to freeze up in production. So disable for now.
// return positions, httperror.PublicErrorf(http.StatusUnauthorized, "Unknown user ID")
// var sqlFilename string
// switch userID {
// case 0:
// sqlFilename = "random-new-voter.sql"
// case 1:
// sqlFilename = "random-top-voter.sql"
// default:
// return positions, httperror.PublicErrorf(http.StatusUnauthorized, "Unknown user ID")
// }
// Debugf(app.logger, "Sql filename %s", sqlFilename)
// tx, e := db.BeginTx(ctx, nil)
// if e != nil {
// return positions, errors.Wrap(e, "BeginTX")
// }
// err := executeSQLFile(ctx, tx, sqlFilename)
// if err != nil {
// return positions, errors.Wrap(err, "executing "+sqlFilename)
// }
// err = tx.Commit()
// if err != nil {
// return positions, errors.Wrap(err, "tx.Commit in getDetailedPositions")
// }
} else {
getDetailedPositionsStmt, err := db.PrepareContext(ctx, getDetailedPositionsSQL)
if err != nil {
return positions, errors.Wrap(err, "Preparing getDetailedPositionsStmt")
}
statement = getDetailedPositionsStmt
}
rows, err := statement.QueryContext(ctx, userID)
if err != nil {
return positions, errors.Wrap(err, "Getting positions")
}
defer rows.Close()
for rows.Next() {
// var storyID int
// var direction int8
// var exitTime sql.NullInt64
// var upvoteRate, endingUpvoteRate float64
var p Position
err := rows.Scan(
&p.UserID,
&p.StoryID,
&p.PositionID,
&p.Direction,
&p.EntryTime,
&p.EntryUpvotes,
&p.EntryExpectedUpvotes,
&p.ExitTime,
&p.ExitUpvotes,
&p.ExitExpectedUpvotes,
&p.CurrentUpvotes,
&p.CurrentExpectedUpvotes,
&p.Story.Title,
&p.Story.URL,
&p.Story.By,
&p.Story.AgeApprox,
&p.Story.Score,
&p.Story.Comments)
if err != nil {
return positions, errors.Wrap(err, "scanning positions")
}
p.Story.ID = p.StoryID
positions = append(positions, p)
}
Debugf(app.logger, "Number of Positions %d", len(positions))
return positions, nil
}
// Gets position for the user, without details
func (app app) getPositions(ctx context.Context, userID int64, storyIDs []int) ([]Position, error) {
positions := make([]Position, 0)
db, err := app.ndb.upvotesDBWithDataset(ctx)
if err != nil {
return positions, errors.Wrap(err, "upvotesDBWithDataset")
}
// TODO: only select votes relevant to the stories on the page
getPositionsStatement, err := db.PrepareContext(ctx, `
select
storyID
, direction
, entryUpvotes
, entryExpectedUpvotes
, exitUpvotes
, exitExpectedUpvotes
from positions
where userID = ?
and exitTime is null
group by storyID
having max(positionID)
`)
if err != nil {
return positions, errors.Wrap(err, "Preparing getOpenPositions")
}
rows, err := getPositionsStatement.QueryContext(ctx, userID)
if err != nil {
return positions, errors.Wrap(err, "getPositionsStatement.QuertyContext")
}
defer rows.Close()
for rows.Next() {
// var storyID int
// var direction int8
// var entryUpvotes int
// var entryExpectedUpvotes float64
var p Position
err := rows.Scan(&p.StoryID, &p.Direction, &p.EntryUpvotes, &p.EntryExpectedUpvotes, &p.ExitUpvotes, &p.ExitExpectedUpvotes)
if err != nil {
return positions, errors.Wrap(err, "scanning getPositions")
}
positions = append(positions, p)
}
return positions, nil
}
var getDetailedPositionsSQL = `
select
userID
, storyID
, positionID
, direction
, entryTime
, entryUpvotes
, entryExpectedUpvotes
, exitTime
, exitUpvotes
, exitExpectedUpvotes
, cumulativeUpvotes
, cumulativeExpectedUpvotes
, title
, url
, by
, unixepoch() - sampleTime + coalesce(ageApprox, sampleTime - submissionTime) ageApprox
, score
, descendants as comments
from positions
join dataset on
positions.storyID = id
and userID = ?
join stories using (id)
group by positionID
having max(dataset.sampleTime)
order by entryTime desc
`
var everyStoryVoterSQL = `
with storiesToUpvote as (
select id as storyID
, min(sampleTime) as minSampleTime
, min(cumulativeUpvotes) as minUpvotes
, min(cumulativeExpectedUpvotes) as minExpectedUpvotes
from dataset join stories using (id)
where id > (select max(id) from stories) - 100000
and timestamp > ( select min(sampleTime) from dataset ) -- only stories submitted since we started crawling
and not job
group by id
order by id desc
limit 1000
)
, positions as (
select
%d as userID
, storiesToUpvote.storyID
, %d as direction
, minSampleTime as entryTime
, minUpvotes as entryUpvotes
, minExpectedUPvotes as entryExpectedUpvotes
, null as exitTime
, null as exitUpvotes
, null as exitExpectedUpvotes
, row_number() over () as positionID
from storiesToUpvote
-- left join votes existingVotes using (storyID)
-- where existingVotes.storyID is null
)
` + getDetailedPositionsSQL
var randomVoterSQL = `
with randomDatapoints as (
select
id, sampleTime , cumulativeUpvotes, cumulativeExpectedUpvotes
, null as exitTime
, null as exitUpvotes
, null as exitExpectedUpvotes
, row_number() over () as i
, count() over () as nIDs
from dataset
join stories using (id)
where
timestamp > ( select min(sampleTime) from dataset ) -- only stories submitted since we started crawling
and sampleTime > ( select max(sampleTime) from dataset ) - 24 * 60 * 60
and %sRank is not null
and not job
),
limits as (
select abs(random()) %% ( nIds / 1000 ) as n
from randomDatapoints
where i = 1
)
, storiesToUpvote as (
select id as storyID
, min(sampleTime) as minSampleTime
, min(cumulativeUpvotes) as minUpvotes
, min(cumulativeExpectedUpvotes) as minExpectedUpvotes
from randomDatapoints join limits
where
( i ) %% (nIDs / 1000) = n
group by id
order by sampleTime
limit 1000
)
, positions as (
select
%d as userID
, storiesToUpvote.storyID
, 1 as direction
, minSampleTime as entryTime
, minUpvotes as entryUpvotes
, minExpectedUPvotes as entryExpectedUpvotes
, null as exitTime
, null as exitUpvotes
, null as exitExpectedUpvotes
, row_number() over () as positionID
from storiesToUpvote
-- left join votes existingVotes using (storyID)
-- where existingVotes.storyID is null
) ` + getDetailedPositionsSQL