generated from fun-stack/example
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstatspage.go
242 lines (199 loc) · 6.84 KB
/
statspage.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
package main
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/johnwarden/httperror"
)
type StatsPageParams struct {
StoryID int `schema:"id,required"`
OptionalModelParams
}
type StatsData struct {
RanksPlotDataJSON template.JS
UpvotesPlotDataJSON template.JS
MaxSampleTime int
}
type StatsPageData struct {
StatsPageParams
EstimatedUpvoteRate int
StoryTemplateData
StatsData
}
func (s StatsPageData) MaxSampleTimeISOString() string {
return time.Unix(int64(s.MaxSampleTime), 0).UTC().Format("2006-01-02T15:04")
}
func (s StatsPageData) OriginalSubmissionTimeISOString() string {
return time.Unix(s.OriginalSubmissionTime, 0).UTC().Format("2006-01-02T15:04")
}
func (s StatsPageData) MaxAgeHours() int {
return (s.MaxSampleTime - int(s.OriginalSubmissionTime)) / 3600
}
var ErrStoryIDNotFound = httperror.New(404, "Story ID not found")
func (app app) statsPage(w io.Writer, r *http.Request, params StatsPageParams, userID sql.NullInt64) error {
s, stats, err := app.loadStoryAndStats(r.Context(), params.StoryID, params.OptionalModelParams)
if err != nil {
return err
}
modelParams := params.OptionalModelParams.WithDefaults()
s.UpvoteRate = modelParams.upvoteRate(s.CumulativeUpvotes, s.CumulativeExpectedUpvotes)
pageTemplate := PageTemplateData{
UserID: userID,
}
storyTemplate := StoryTemplateData{
Story: s,
PageTemplateData: pageTemplate,
}
d := StatsPageData{
StatsPageParams: params,
EstimatedUpvoteRate: 1.0,
StoryTemplateData: storyTemplate,
StatsData: stats,
}
err = templates.ExecuteTemplate(w, "stats.html.tmpl", d)
return errors.Wrap(err, "executing stats page template")
}
func (app app) loadStoryAndStats(ctx context.Context, storyID int, modelParams OptionalModelParams) (Story, StatsData, error) {
ndb := app.ndb
// Try to get story from DB first
s, err := ndb.selectStoryDetails(storyID)
// for debugging
// err = sql.ErrNoRows
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// Story not in DB, try to load from archive
sc, err := NewStorageClient()
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "create storage client")
}
// Try v2 archive first
filename := fmt.Sprintf("%d.v2.json", storyID)
jsonData, err := sc.DownloadFile(ctx, filename)
isV2 := err == nil
if err != nil {
// Try legacy archive
filename = fmt.Sprintf("%d.json", storyID)
jsonData, err = sc.DownloadFile(ctx, filename)
if err != nil {
return Story{}, StatsData{}, ErrStoryIDNotFound
}
}
var archiveData ArchiveData
err = json.Unmarshal(jsonData, &archiveData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "unmarshal archive data")
}
// For v2 archives, construct Story from archive data
if isV2 {
// Calculate AgeApprox as current time minus submission time
ageApprox := time.Now().Unix() - archiveData.SubmissionTime
s = Story{
ID: archiveData.ID,
By: archiveData.By,
Title: archiveData.Title,
URL: archiveData.URL,
SubmissionTime: archiveData.SubmissionTime,
OriginalSubmissionTime: archiveData.OriginalSubmissionTime,
AgeApprox: ageApprox,
Score: archiveData.Score,
Comments: archiveData.Comments,
CumulativeUpvotes: archiveData.CumulativeUpvotes,
CumulativeExpectedUpvotes: archiveData.CumulativeExpectedUpvotes,
TopRank: archiveData.TopRank,
QNRank: archiveData.QNRank,
RawRank: archiveData.RawRank,
Flagged: archiveData.Flagged,
Dupe: archiveData.Dupe,
Job: archiveData.Job,
}
} else {
// For legacy archives, we need story details from DB
return Story{}, StatsData{}, ErrStoryIDNotFound
}
// Convert plot data to JSON
ranksJson, err := json.Marshal(archiveData.RanksPlotData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal ranks plot data")
}
upvotesJson, err := json.Marshal(archiveData.UpvotesPlotData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal upvotes plot data")
}
stats := StatsData{
RanksPlotDataJSON: template.JS(string(ranksJson)),
UpvotesPlotDataJSON: template.JS(string(upvotesJson)),
MaxSampleTime: archiveData.MaxSampleTime,
}
return s, stats, nil
}
return Story{}, StatsData{}, err
}
// Story found in DB
if s.Archived {
// Story is archived in legacy format (v2 format deletes from DB)
sc, err := NewStorageClient()
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "create storage client")
}
app.logger.Debug("Loading legacy archive data", "storyID", storyID)
// Only try legacy format since story is still in DB
filename := fmt.Sprintf("%d.json", storyID)
jsonData, err := sc.DownloadFile(ctx, filename)
if err != nil {
return Story{}, StatsData{}, fmt.Errorf("Missing archive file for story id %d", storyID)
}
var archiveData ArchiveData
err = json.Unmarshal(jsonData, &archiveData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "unmarshal archive data")
}
// Convert plot data to JSON
ranksJson, err := json.Marshal(archiveData.RanksPlotData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal ranks plot data")
}
upvotesJson, err := json.Marshal(archiveData.UpvotesPlotData)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal upvotes plot data")
}
stats := StatsData{
RanksPlotDataJSON: template.JS(string(ranksJson)),
UpvotesPlotDataJSON: template.JS(string(upvotesJson)),
MaxSampleTime: archiveData.MaxSampleTime,
}
return s, stats, nil
}
// Story is not archived, get stats from DB
maxSampleTime, err := maxSampleTime(ndb, storyID)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "maxSampleTime")
}
ranks, err := rankDatapoints(ndb, storyID)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "rankDatapoints")
}
ranksJson, err := json.Marshal(ranks)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal ranks plot data")
}
upvotes, err := upvotesDatapoints(ndb, storyID, modelParams.WithDefaults())
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "upvotesDatapoints")
}
upvotesJson, err := json.Marshal(upvotes)
if err != nil {
return Story{}, StatsData{}, errors.Wrap(err, "marshal upvotes plot data")
}
stats := StatsData{
RanksPlotDataJSON: template.JS(string(ranksJson)),
UpvotesPlotDataJSON: template.JS(string(upvotesJson)),
MaxSampleTime: maxSampleTime,
}
return s, stats, nil
}