This repository has been archived by the owner on Jul 12, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
key_server_stats.go
252 lines (218 loc) · 8.72 KB
/
key_server_stats.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
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"strconv"
"time"
keyserver "github.com/google/exposure-notifications-server/pkg/api/v1"
"github.com/google/exposure-notifications-verification-server/pkg/cache"
"github.com/jinzhu/gorm"
"github.com/lib/pq"
)
// KeyServerStats represents statistics for a key-server for this realm
type KeyServerStats struct {
Errorable
// RealmId that these stats belong to.
RealmID uint `gorm:"column:realm_id; primary_key; type:integer; not null;"`
// KeyServerURLOverride allows a realm to override the system's URL with its own
KeyServerURLOverride string `gorm:"column:key_server_url_override; type:text;"`
// KeyServerAudience allows a realm to override the system's audience
KeyServerAudienceOverride string `gorm:"column:key_server_audience_override; type:text;"`
}
// KeyServerStatsDay represents statistics for each day
type KeyServerStatsDay struct {
Errorable
// RealmId that these stats belong to.
RealmID uint `gorm:"column:realm_id; primary_key; type:integer; not null;"`
// Day will be set to midnight UTC of the day represented. An individual day
// isn't released until there is a minimum threshold for updates has been met.
Day time.Time `gorm:"column:day; primary_key;"`
// PublishRequests is a count of requests per OS
// where the index corresponds to the value of OSType
PublishRequests pq.Int64Array `gorm:"column:publish_requests; type:bigint[];"`
TotalTEKsPublished int64 `gorm:"column:total_teks_published; type:bigint; not null; default: 0;"`
// RevisionRequests is the number of publish requests that contained at least one TEK revision.
RevisionRequests int64 `gorm:"column:revision_requests; type:bigint; not null; default: 0;"`
// TEKAgeDistribution shows a distribution of the oldest tek in an upload.
// The count at index 0-15 represent the number of uploads there the oldest TEK is that value.
// Index 16 represents > 15 days.
TEKAgeDistribution pq.Int64Array `gorm:"column:tek_age_distribution; type:bigint[];"`
// OnsetToUploadDistribution shows a distribution of onset to upload, the index is in days.
// The count at index 0-29 represents the number of uploads with that symptom onset age.
// Index 30 represents > 29 days.
OnsetToUploadDistribution pq.Int64Array `gorm:"column:onset_to_upload_distribution; type:bigint[];"`
// RequestsMissingOnsetDate is the number of publish requests where no onset date
// was provided. These request are not included in the onset to upload distribution.
RequestsMissingOnsetDate int64 `gorm:"column:request_missing_onset_date; type:bigint; not null; default: 0;"`
}
// BeforeSave runs validations. If there are errors, the save fails.
func (kss *KeyServerStats) BeforeSave(tx *gorm.DB) error {
if kss.RealmID == 0 && (kss.KeyServerURLOverride == "" || kss.KeyServerAudienceOverride == "") {
kss.AddError("realm_id", "the system realm must have a key server and audience")
}
return kss.ErrorOrNil()
}
// BeforeSave runs validations. If there are errors, the save fails.
func (kssd *KeyServerStatsDay) BeforeSave(tx *gorm.DB) error {
if kssd.RealmID == 0 {
kssd.AddError("realm_id", "statistics may not be saved on the system realm")
}
return kssd.ErrorOrNil()
}
// TotalPublishRequests returns the sum of all publish requests for this
// day, which are stored by operating system.
func (kssd *KeyServerStatsDay) TotalPublishRequests() int64 {
var sum int64
for _, v := range kssd.PublishRequests {
sum += v
}
return sum
}
// GetKeyServerStatsCached returns true if the provided realm has key
// server stats enabled.
func (db *Database) GetKeyServerStatsCached(ctx context.Context, realmID uint, cacher cache.Cacher) (*KeyServerStats, error) {
var kss *KeyServerStats
cacheKey := &cache.Key{
Namespace: "stats:realm:key_server_enabled",
Key: strconv.FormatUint(uint64(realmID), 10),
}
if err := cacher.Fetch(ctx, cacheKey, &kss, 30*time.Minute, func() (interface{}, error) {
val, err := db.GetKeyServerStats(realmID)
if err != nil {
if IsNotFound(err) {
return nil, nil
}
return nil, err
}
return val, nil
}); err != nil {
return nil, err
}
return kss, nil
}
// GetKeyServerStats retrieves the configuration for gathering key-server statistics
func (db *Database) GetKeyServerStats(realmID uint) (*KeyServerStats, error) {
var stats KeyServerStats
if err := db.db.
Where("realm_id = ?", realmID).
First(&stats).
Error; err != nil {
return nil, err
}
return &stats, nil
}
// SaveKeyServerStats stores the configuration for gathering key-server statistics
func (db *Database) SaveKeyServerStats(stats *KeyServerStats) error {
return db.db.Save(stats).Error
}
// DeleteKeyServerStats disables gathering key-server statistics and removes the entry
func (db *Database) DeleteKeyServerStats(realmID uint) error {
kss := &KeyServerStats{
RealmID: realmID,
}
return db.db.Unscoped().
Set("gorm:delete_option", "RETURNING *").
Delete(kss).
Error
}
// ListKeyServerStats retrieves the key-server statistics configuration for all realms
func (db *Database) ListKeyServerStats() ([]*KeyServerStats, error) {
var stats []*KeyServerStats
if err := db.db.
Model(&KeyServerStats{}).
Find(&stats).
Error; err != nil {
return nil, err
}
return stats, nil
}
// SaveKeyServerStatsDay stores a single day of key-server statistics
func (db *Database) SaveKeyServerStatsDay(day *KeyServerStatsDay) error {
return db.db.Debug().Save(day).Error
}
// DeleteOldKeyServerStatsDays deletes rows from KeyServerStatsDays that are older than 30 days
func (db *Database) DeleteOldKeyServerStatsDays(maxAge time.Duration) (int64, error) {
if maxAge > 0 {
maxAge = -1 * maxAge
}
a := time.Now().UTC().Add(maxAge)
rtn := db.db.Unscoped().
Where("day < ?", a).
Delete(&KeyServerStatsDay{})
return rtn.RowsAffected, rtn.Error
}
// ListKeyServerStatsDaysCached retrieves the last 30 days of key-server statistics
func (db *Database) ListKeyServerStatsDaysCached(ctx context.Context, realmID uint, cacher cache.Cacher) ([]*KeyServerStatsDay, error) {
var stats []*KeyServerStatsDay
cacheKey := &cache.Key{
Namespace: "stats:realm:key_server",
Key: strconv.FormatUint(uint64(realmID), 10),
}
if err := cacher.Fetch(ctx, cacheKey, &stats, 30*time.Minute, func() (interface{}, error) {
return db.ListKeyServerStatsDays(realmID)
}); err != nil {
return nil, err
}
return stats, nil
}
// ListKeyServerStatsDays retrieves the last 30 days of key-server statistics
func (db *Database) ListKeyServerStatsDays(realmID uint) ([]*KeyServerStatsDay, error) {
var stats []*KeyServerStatsDay
if err := db.db.
Model(&KeyServerStatsDay{}).
Where("realm_id = ?", realmID).
Order("day DESC").
Limit(30).
Find(&stats).
Error; err != nil {
return nil, err
}
return stats, nil
}
// MakeKeyServerStatsDay creates a storage struct from a key-server StatsDay response
func MakeKeyServerStatsDay(realmID uint, d *keyserver.StatsDay) *KeyServerStatsDay {
pr := make([]int64, 3)
pr[OSTypeUnknown] = d.PublishRequests.UnknownPlatform
pr[OSTypeIOS] = d.PublishRequests.IOS
pr[OSTypeAndroid] = d.PublishRequests.Android
return &KeyServerStatsDay{
RealmID: realmID,
Day: d.Day,
PublishRequests: pr,
TotalTEKsPublished: d.TotalTEKsPublished,
RevisionRequests: d.RevisionRequests,
TEKAgeDistribution: d.TEKAgeDistribution,
OnsetToUploadDistribution: d.OnsetToUploadDistribution,
RequestsMissingOnsetDate: d.RequestsMissingOnsetDate,
}
}
// ToResponse makes a json-marshallable StatsDay from a KetServerStatsDay
func (kssd *KeyServerStatsDay) ToResponse() *keyserver.StatsDay {
reqs := keyserver.PublishRequests{}
if l := len(kssd.PublishRequests); l == 3 {
reqs.UnknownPlatform = kssd.PublishRequests[OSTypeUnknown]
reqs.IOS = kssd.PublishRequests[OSTypeIOS]
reqs.Android = kssd.PublishRequests[OSTypeAndroid]
}
return &keyserver.StatsDay{
Day: kssd.Day,
PublishRequests: reqs,
TotalTEKsPublished: kssd.TotalTEKsPublished,
RevisionRequests: kssd.RevisionRequests,
TEKAgeDistribution: kssd.TEKAgeDistribution,
OnsetToUploadDistribution: kssd.OnsetToUploadDistribution,
RequestsMissingOnsetDate: kssd.RequestsMissingOnsetDate,
}
}