summaryrefslogtreecommitdiff
path: root/internal/router/client-cache.go
blob: e448fb3710689cf8b1f138e55be804cdc38efc82 (plain)
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
package router

import (
	"database/sql"
	"encoding/base64"
	"fmt"
	"log/slog"
	"strings"
	"sync"

	"golang.org/x/crypto/argon2"
)

type ClientCache struct {
	hashMap      map[string]string
	hashMapMutex sync.RWMutex

	likePageMap       map[string]map[string]struct{}
	pageMutexMap      map[string]*sync.RWMutex
	pageMutexMapMutex sync.Mutex

	salt []byte
	db   *sql.DB
}

var CCache *ClientCache

func NewClientCache(db *sql.DB, salt []byte) (*ClientCache, error) {
	tx, err := db.Begin()
	if err != nil {
		return nil, fmt.Errorf("fail to init transaction with db to fill cache: %w", err)
	}

	rows, err := tx.Query("select * from blog_likes;")
	if err != nil {
		tx.Rollback()
		return nil, fmt.Errorf("fail to query db for blog_likes to fill cache: %w", err)
	}

	likePageMap := make(map[string]map[string]struct{})
	pageMutexMap := make(map[string]*sync.RWMutex)

	for rows.Next() {
		var pageRef string
		var userId []byte
		if err = rows.Scan(&pageRef, &userId); err != nil {
			tx.Rollback()
			return nil, fmt.Errorf("fail scanning blog_likes to fill cache: %w", err)
		}
		userIdString := base64.RawStdEncoding.EncodeToString(userId)
		if _, ok := likePageMap[pageRef]; !ok {
			likePageMap[pageRef] = make(map[string]struct{})
			pageMutexMap[pageRef] = &sync.RWMutex{}
		}
		likePageMap[pageRef][userIdString] = struct{}{}
	}

	if err = tx.Commit(); err != nil {
		return nil, fmt.Errorf("fail to commit transaction in db: %w", err)
	}

	return &ClientCache{
		hashMap:      make(map[string]string),
		likePageMap:  likePageMap,
		pageMutexMap: pageMutexMap,
		salt:         salt,
		db:           db,
	}, nil
}

func (c *ClientCache) Close() error {
	tx, err := c.db.Begin()
	if err != nil {
		return fmt.Errorf("fail to init transaction with db to dump cache: %w", err)
	}

	if _, err = tx.Exec("delete from blog_likes;"); err != nil {
		tx.Rollback()
		return fmt.Errorf("fail to truncate table blog_likes: %w", err)
	}

	userIdBytes := make(map[string][]byte)

	sqlStatement := fmt.Sprintf(`
    INSERT OR IGNORE INTO blog_likes (page_ref, user_id)
    VALUES %s(?, ?);
    `, strings.Repeat("(?, ?), ", 99))
	sqlStatementVars := make([]any, 0, 200)

	for pageRef, userSet := range c.likePageMap {
		for userId := range userSet {
			if _, ok := userIdBytes[userId]; !ok {
				userIdBytes[userId], err = base64.RawStdEncoding.DecodeString(userId)
				if err != nil {
					slog.Warn("couldn't parse one of user hashes into bytes back", slog.String("hash", userId), slog.String("error", err.Error()))
					continue
				}
			}

			sqlStatementVars = append(sqlStatementVars, any(pageRef), any(userIdBytes[userId]))
			if len(sqlStatementVars) < 200 {
				continue
			}

			if _, err := tx.Exec(sqlStatement, sqlStatementVars...); err != nil {
				slog.Warn("couldn't insert blog like pairs into db", slog.String("error", err.Error()))
			}

			sqlStatementVars = make([]any, 0, 200)
		}
	}

	if len(sqlStatementVars) > 0 {
		sqlStatement = fmt.Sprintf(`
		INSERT OR IGNORE INTO blog_likes (page_ref, user_id)
		VALUES %s(?, ?);
		`, strings.Repeat("(?, ?), ", len(sqlStatementVars)/2-1))

		if _, err := tx.Exec(sqlStatement, sqlStatementVars...); err != nil {
			slog.Warn("couldn't insert blog like pairs into db", slog.String("error", err.Error()))
		}
	}

	return tx.Commit()
}

func (c *ClientCache) GetHash(id string) string {
	c.hashMapMutex.RLock()
	if val, ok := c.hashMap[id]; ok {
		c.hashMapMutex.RUnlock()
		slog.Debug("gave an old hash", slog.String("hash", val))
		return val
	}
	c.hashMapMutex.RUnlock()

	c.hashMapMutex.Lock()
	defer c.hashMapMutex.Unlock()

	if val, ok := c.hashMap[id]; ok {
		slog.Debug("gave a newly generated hash", slog.String("hash", val))
		return val
	}

	c.hashMap[id] = base64.RawStdEncoding.EncodeToString(argon2.IDKey([]byte(id), c.salt, 1, 64*1024, 4, 32))
	slog.Debug("generated hash", slog.String("hash", c.hashMap[id]))
	return c.hashMap[id]
}

func (c *ClientCache) getPageMutex(page string) *sync.RWMutex {
	c.pageMutexMapMutex.Lock()
	defer c.pageMutexMapMutex.Unlock()

	if mutex, ok := c.pageMutexMap[page]; ok {
		return mutex
	}

	c.pageMutexMap[page] = &sync.RWMutex{}
	return c.pageMutexMap[page]
}

func (c *ClientCache) GetLikeStatus(id string, page string) bool {
	page = strings.Clone(page)

	mutex := c.getPageMutex(page)
	mutex.RLock()
	defer mutex.RUnlock()

	if _, ok := c.likePageMap[page]; !ok {
		return false
	}
	_, ok := c.likePageMap[page][c.GetHash(id)]
	return ok
}

func (c *ClientCache) GetLikeCount(page string) int {
	page = strings.Clone(page)

	mutex := c.getPageMutex(page)
	mutex.RLock()
	defer mutex.RUnlock()

	if userSet, ok := c.likePageMap[page]; ok {
		return len(userSet)
	}
	return 0
}

func (c *ClientCache) LikeOn(id string, page string) (alreadyLiked bool) {
	page = strings.Clone(page)
	hash := c.GetHash(id)

	mutex := c.getPageMutex(page)
	mutex.Lock()
	defer mutex.Unlock()

	if userSet, ok := c.likePageMap[page]; ok {
		_, alreadyLiked = userSet[hash]
		c.likePageMap[page][hash] = struct{}{}
		return
	}

	c.likePageMap[page] = make(map[string]struct{})
	c.likePageMap[page][hash] = struct{}{}
	return
}

func (c *ClientCache) LikeOff(id string, page string) (alreadyUnliked bool) {
	page = strings.Clone(page)
	hash := c.GetHash(id)

	mutex := c.getPageMutex(page)
	mutex.Lock()
	defer mutex.Unlock()

	if _, ok := c.likePageMap[page]; !ok {
		return true
	}
	if _, ok := c.likePageMap[page][hash]; !ok {
		return true
	}

	delete(c.likePageMap[page], hash)
	return false
}