-
Notifications
You must be signed in to change notification settings - Fork 6
/
device.go
158 lines (138 loc) · 4.68 KB
/
device.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
package backend
import (
"context"
"sync"
"time"
pb "github.com/TUM-Dev/Campus-Backend/server/api/tumdev"
"github.com/TUM-Dev/Campus-Backend/server/model"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// deviceBuffer stores all recent device calls in a buffer and flushes them to the database periodically
type deviceBuffer struct {
lock sync.Mutex
devices map[string]*model.Device // key is uuid
}
func newDeviceBuffer() *deviceBuffer {
return &deviceBuffer{
lock: sync.Mutex{},
devices: make(map[string]*model.Device),
}
}
const FlushingInterval = time.Minute
func (s *CampusServer) RunDeviceFlusher() error {
for {
time.Sleep(FlushingInterval)
if err := s.deviceBuf.flush(s.db); err != nil {
log.WithError(err).Error("Error flushing device buffer")
}
}
}
// s.deviceBuf.add(md["x-device-id"][0], method[0], osVersion, appVersion)
func (b *deviceBuffer) add(deviceID string, method string, osVersion string, appVersion string) {
b.lock.Lock()
defer b.lock.Unlock()
if _, exists := b.devices[deviceID]; exists {
b.devices[deviceID].Counter++
} else {
b.devices[deviceID] = &model.Device{
UUID: deviceID,
LastAccess: time.Now(),
LastAPI: method,
OsVersion: osVersion,
AppVersion: appVersion,
Counter: 1,
}
}
}
// flush writes all buffered devices to the database
func (b *deviceBuffer) flush(tx *gorm.DB) error {
b.lock.Lock()
defer b.lock.Unlock()
devices := make([]*model.Device, 0, len(b.devices))
for _, device := range b.devices {
devices = append(devices, device)
}
if len(b.devices) == 0 {
return nil
}
// store devices in database, update if exists
err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "uuid"}}, // conflict on uuid -> update
DoUpdates: clause.AssignmentColumns([]string{"lastApi", "lastAccess", "osVersion", "appVersion"}),
}).Create(devices).Error
if err != nil {
log.WithError(err).Error("failed to flush device buffer")
}
// update number of calls for each device
err = tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "uuid"}},
DoUpdates: clause.Assignments(map[string]interface{}{"counter": gorm.Expr("counter+VALUES(counter)")}),
}).Create(devices).Error
if err != nil {
log.WithError(err).Error("failed to flush device buffer")
}
b.devices = make(map[string]*model.Device)
return nil
}
// checkDevice checks if the device is approved (TODO: implement)
func (s *CampusServer) checkDevice(ctx context.Context) error {
var deviceID, method string
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return status.Error(codes.Internal, "can't extract metadata from request")
}
if len(md["x-device-id"]) == 0 {
deviceID = "unknown"
md["x-device-id"] = []string{deviceID}
}
// check method header added by middleware. This should always exist.
if len(md["x-campus-method"]) == 0 {
log.Info("no method header found for request")
method = "unknown"
md["x-campus-method"] = []string{method}
}
osVersion := "unknown"
if len(md["x-os-version"]) > 0 {
osVersion = md["x-os-version"][0]
}
appVersion := "unknown"
if len(md["x-app-version"]) > 0 {
appVersion = md["x-app-version"][0]
}
// log device to db
s.deviceBuf.add(deviceID, method, osVersion, appVersion)
return nil
}
func (s *CampusServer) CreateDevice(_ context.Context, req *pb.CreateDeviceRequest) (*pb.CreateDeviceReply, error) {
if err := ValidateCreateDevice(req); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
switch req.DeviceType {
case pb.DeviceType_ANDROID:
return nil, status.Error(codes.Unimplemented, "android device creation not implemented")
case pb.DeviceType_IOS:
return nil, status.Error(codes.Unimplemented, "ios device creation not implemented")
case pb.DeviceType_WINDOWS:
return nil, status.Error(codes.Unimplemented, "windows device creation not implemented")
}
return nil, status.Error(codes.InvalidArgument, "invalid device type")
}
func (s *CampusServer) DeleteDevice(_ context.Context, req *pb.DeleteDeviceRequest) (*pb.DeleteDeviceReply, error) {
if err := ValidateDeleteDevice(req); err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
switch req.DeviceType {
case pb.DeviceType_ANDROID:
return nil, status.Error(codes.Unimplemented, "android device remove not implemented")
case pb.DeviceType_IOS:
return nil, status.Error(codes.Unimplemented, "ios device remove not implemented")
case pb.DeviceType_WINDOWS:
return nil, status.Error(codes.Unimplemented, "windows device remove not implemented")
}
return nil, status.Error(codes.InvalidArgument, "invalid device type")
}