summaryrefslogtreecommitdiff
path: root/internal/router/client-cache.go
blob: d607cdd1c3d27d8d0fb86099c5e8c352798aaf4f (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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
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{}
	viewPageMap       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{})
	viewPageMap := 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{})
			viewPageMap[pageRef] = make(map[string]struct{})
			pageMutexMap[pageRef] = &sync.RWMutex{}
		}
		likePageMap[pageRef][userIdString] = struct{}{}
		viewPageMap[pageRef][userIdString] = struct{}{}
	}

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

	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_views to fill cache: %w", err)
		}
		userIdString := base64.RawStdEncoding.EncodeToString(userId)
		if _, ok := viewPageMap[pageRef]; !ok {
			viewPageMap[pageRef] = make(map[string]struct{})
			pageMutexMap[pageRef] = &sync.RWMutex{}
		}
		viewPageMap[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,
		viewPageMap:  viewPageMap,
		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 = batchSave(tx, "blog_likes", c.likePageMap); err != nil {
		tx.Rollback()
		return fmt.Errorf("fail to save blog_likes: %s", err)
	}

	if err = batchSave(tx, "blog_views", c.viewPageMap); err != nil {
		tx.Rollback()
		return fmt.Errorf("fail to save blog_views: %s", err)
	}

	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
}

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

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

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

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

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

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

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

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

	if _, ok := c.viewPageMap[page]; !ok {
		c.viewPageMap[page] = make(map[string]struct{})
	}
	c.viewPageMap[page][hash] = struct{}{}
}

func batchSave(tx *sql.Tx, table string, pageMap map[string]map[string]struct{}) (err error) {
	if _, err = tx.Exec(fmt.Sprintf("delete from %s;", table)); err != nil {
		return fmt.Errorf("fail to truncate table %s: %w", table, err)
	}

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

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

	for pageRef, userSet := range pageMap {
		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 stat pairs into db", slog.String("table", table), slog.String("error", err.Error()))
			}

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

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

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

	return nil
}