Skip to content

Commit aa5fdf9

Browse files
committed
Optimize UpdateStatuses function with cache
1 parent b5e05c6 commit aa5fdf9

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

pkg/storage/status.go

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package storage
22

33
import (
44
"context"
5+
"encoding/hex"
56
"fmt"
67
"net"
78

@@ -16,6 +17,8 @@ type UpdateStatusesArgs struct {
1617
Counters StatusTx
1718
}
1819

20+
var bcryptCache = make(map[string]bool)
21+
1922
// UpdateStatuses set online user fields, with any device's MAC equal to one
2023
// of addresses from given slice, to true and writes them to database.
2124
func UpdateStatuses(ctx context.Context, args UpdateStatusesArgs) error {
@@ -30,9 +33,21 @@ func UpdateStatuses(ctx context.Context, args UpdateStatusesArgs) error {
3033

3134
for _, address := range args.Addresses {
3235
for _, device := range devices {
33-
if err := bcrypt.CompareHashAndPassword(device.MAC, address); err == nil {
36+
var matched bool
37+
cacheKey := generateCacheKey(device.MAC, address)
38+
39+
if val, ok := bcryptCache[cacheKey]; ok {
40+
matched = val
41+
} else {
42+
err := bcrypt.CompareHashAndPassword(device.MAC, address)
43+
matched = err == nil
44+
bcryptCache[cacheKey] = matched
45+
}
46+
47+
if matched {
3448
known += 1
3549
onlineIDs = append(onlineIDs, device.OwnerID)
50+
break
3651
}
3752
}
3853
}
@@ -56,3 +71,7 @@ func UpdateStatuses(ctx context.Context, args UpdateStatusesArgs) error {
5671
return nil
5772
})
5873
}
74+
75+
func generateCacheKey(mac []byte, address net.HardwareAddr) string {
76+
return string(mac) + ":" + hex.EncodeToString(address)
77+
}

0 commit comments

Comments
 (0)