From d20ad73467c0636edea6133d7bd4b38bbfdefc55 Mon Sep 17 00:00:00 2001 From: Ben Morrison Date: Thu, 13 Jun 2019 22:52:36 -0400 Subject: mutex and readability cleanup --- svc/conf.go | 10 +++++----- svc/handlers.go | 5 ++--- svc/leveldb.go | 16 +++++----------- svc/query.go | 6 +----- svc/sqlite.go | 14 ++++---------- svc/svc.go | 16 +++++----------- 6 files changed, 22 insertions(+), 45 deletions(-) diff --git a/svc/conf.go b/svc/conf.go index c1b9abb..e80234f 100644 --- a/svc/conf.go +++ b/svc/conf.go @@ -74,8 +74,9 @@ func initConfig() { // to the default logger, and the same for the // request logger. func initLogging() { - confObj.Mu.RLock() + defer confObj.Mu.RUnlock() + if confObj.StdoutLogging { log.SetOutput(os.Stdout) reqLog = log.New(os.Stdout, "", log.LstdFlags) @@ -100,7 +101,6 @@ func initLogging() { log.SetOutput(msgLog) reqLog = log.New(reqLogFile, "", log.LstdFlags) } - confObj.Mu.RUnlock() } // Default values should a config file @@ -189,14 +189,15 @@ func bindConfig() { if *flagAssets != "" { confObj.AssetsDir = *flagAssets } - confObj.Mu.Unlock() + confObj.Mu.Unlock() announceConfig() - } func announceConfig() { confObj.Mu.RLock() + defer confObj.Mu.RUnlock() + if confObj.IsProxied { log.Printf("Behind reverse proxy, not using host matching\n") } else { @@ -216,5 +217,4 @@ func announceConfig() { log.Printf("Using %v database: %v\n", confObj.DBType, confObj.DBPath) log.Printf("Database push interval: %v\n", confObj.DBInterval) log.Printf("User status fetch interval: %v\n", confObj.CacheInterval) - confObj.Mu.RUnlock() } diff --git a/svc/handlers.go b/svc/handlers.go index 924b487..973bd62 100644 --- a/svc/handlers.go +++ b/svc/handlers.go @@ -20,14 +20,14 @@ func getEtag(modtime time.Time) string { func servStatic(w http.ResponseWriter, isCSS bool) error { pingAssets() - staticCache.mu.RLock() + defer staticCache.mu.RUnlock() + if isCSS { etag := getEtag(staticCache.cssMod) w.Header().Set("ETag", "\""+etag+"\"") w.Header().Set("Content-Type", cssutf8) _, err := w.Write(staticCache.css) - staticCache.mu.RUnlock() return err } @@ -35,7 +35,6 @@ func servStatic(w http.ResponseWriter, isCSS bool) error { w.Header().Set("ETag", "\""+etag+"\"") w.Header().Set("Content-Type", htmlutf8) _, err := w.Write(staticCache.index) - staticCache.mu.RUnlock() return err } diff --git a/svc/leveldb.go b/svc/leveldb.go index 7446dad..91d7ca9 100644 --- a/svc/leveldb.go +++ b/svc/leveldb.go @@ -15,9 +15,10 @@ type dbLevel struct { func (lvl *dbLevel) push() error { twtxtCache.Mu.RLock() + defer twtxtCache.Mu.RUnlock() + var dbBasket = &leveldb.Batch{} for k, v := range twtxtCache.Users { - dbBasket.Put([]byte(k+"*Nick"), []byte(v.Nick)) dbBasket.Put([]byte(k+"*URL"), []byte(v.URL)) dbBasket.Put([]byte(k+"*IP"), []byte(v.IP.String())) @@ -29,7 +30,6 @@ func (lvl *dbLevel) push() error { dbBasket.Put([]byte(k+"*Status*"+rfc), []byte(e)) } } - twtxtCache.Mu.RUnlock() for k, v := range remoteRegistries.List { dbBasket.Put([]byte("remote*"+string(k)), []byte(v)) @@ -40,6 +40,8 @@ func (lvl *dbLevel) push() error { func (lvl *dbLevel) pull() { iter := lvl.db.NewIterator(nil, nil) + twtxtCache.Mu.Lock() + defer twtxtCache.Mu.Unlock() for iter.Next() { key := string(iter.Key()) @@ -54,13 +56,9 @@ func (lvl *dbLevel) pull() { } data := registry.NewUser() - twtxtCache.Mu.RLock() if _, ok := twtxtCache.Users[urls]; ok { - twtxtCache.Users[urls].Mu.RLock() data = twtxtCache.Users[urls] - twtxtCache.Users[urls].Mu.RUnlock() } - twtxtCache.Mu.RUnlock() data.Mu.Lock() switch field { @@ -79,15 +77,11 @@ func (lvl *dbLevel) pull() { errLog("", err) data.Status[thetime] = val } - data.Mu.Unlock() - - twtxtCache.Mu.Lock() twtxtCache.Users[urls] = data - twtxtCache.Mu.Unlock() + data.Mu.Unlock() } remoteRegistries.List = dedupe(remoteRegistries.List) - iter.Release() errLog("Error while pulling DB into registry cache: ", iter.Error()) } diff --git a/svc/query.go b/svc/query.go index 25f0f44..6122850 100644 --- a/svc/query.go +++ b/svc/query.go @@ -43,7 +43,6 @@ func parseQueryOut(out []string) []byte { for i, e := range out { data = append(data, []byte(e)...) - if !strings.HasSuffix(e, "\n") && i != len(out)-1 { data = append(data, byte('\n')) } @@ -86,7 +85,6 @@ func apiEndpointQuery(w http.ResponseWriter, r *http.Request) error { out2, err = twtxtCache.QueryUser(urls) apiErrCheck(err, r) } - if query != "" && urls != "" { out = joinQueryOuts(out2) } @@ -108,11 +106,10 @@ func apiEndpointQuery(w http.ResponseWriter, r *http.Request) error { out = registry.ReduceToPage(page, out) data := parseQueryOut(out) - etag := fmt.Sprintf("%x", sha256.Sum256(data)) + w.Header().Set("ETag", etag) w.Header().Set("Content-Type", txtutf8) - _, err = w.Write(data) return err @@ -123,7 +120,6 @@ func joinQueryOuts(data ...[]string) []string { for _, e := range data { single = append(single, e...) } - return dedupe(single) } diff --git a/svc/sqlite.go b/svc/sqlite.go index b10e5ae..8a7b1a4 100644 --- a/svc/sqlite.go +++ b/svc/sqlite.go @@ -16,7 +16,6 @@ type dbSqlite struct { } func initSqlite() *dbSqlite { - confObj.Mu.RLock() dbpath := confObj.DBPath confObj.Mu.RUnlock() @@ -52,6 +51,8 @@ func (lite *dbSqlite) push() error { txst := tx.Stmt(lite.pushStmt) twtxtCache.Mu.RLock() + defer twtxtCache.Mu.RUnlock() + for i, e := range twtxtCache.Users { e.Mu.RLock() @@ -68,10 +69,8 @@ func (lite *dbSqlite) push() error { _, err = txst.Exec(i, true, k.Format(time.RFC3339), v) errLog("", err) } - e.Mu.RUnlock() } - twtxtCache.Mu.RUnlock() for _, e := range remoteRegistries.List { _, err = txst.Exec(e, false, "REMOTE REGISTRY", "NULL") @@ -83,13 +82,11 @@ func (lite *dbSqlite) push() error { errLog("", tx.Rollback()) return err } - return nil } func (lite *dbSqlite) pull() { errLog("Error pinging sqlite DB: ", lite.db.Ping()) - rows, err := lite.pullStmt.Query() errLog("", err) @@ -98,6 +95,8 @@ func (lite *dbSqlite) pull() { }(rows) twtxtCache.Mu.Lock() + defer twtxtCache.Mu.Unlock() + for rows.Next() { var uid int var urls string @@ -106,7 +105,6 @@ func (lite *dbSqlite) pull() { var dBlob []byte errLog("", rows.Scan(&uid, &urls, &isUser, &dataKey, &dBlob)) - if !isUser { remoteRegistries.List = append(remoteRegistries.List, urls) continue @@ -117,7 +115,6 @@ func (lite *dbSqlite) pull() { user = twtxtCache.Users[urls] } user.Mu.Lock() - switch dataKey { case "nickname": user.Nick = string(dBlob) @@ -132,11 +129,8 @@ func (lite *dbSqlite) pull() { errLog("While pulling statuses from SQLite: ", err) user.Status[thetime] = string(dBlob) } - twtxtCache.Users[urls] = user user.Mu.Unlock() } - twtxtCache.Mu.Unlock() - remoteRegistries.List = dedupe(remoteRegistries.List) } diff --git a/svc/svc.go b/svc/svc.go index 1748bf0..a7786d9 100644 --- a/svc/svc.go +++ b/svc/svc.go @@ -19,6 +19,9 @@ func Start() { // to serve the same content without duplicating // handlers/paths index := mux.NewRouter().StrictSlash(true) + setIndexRouting(index) + api := index.PathPrefix("/api").Subrouter() + setEndpointRouting(api) confObj.Mu.RLock() portnum := fmt.Sprintf(":%v", confObj.Port) @@ -30,13 +33,10 @@ func Start() { TLSKey := confObj.TLS.Key confObj.Mu.RUnlock() - setIndexRouting(index) - api := index.PathPrefix("/api").Subrouter() - setEndpointRouting(api) - server := newServer(portnum, index) log.Printf("*** Listening on %v\n", portnum) log.Printf("*** getwtxt %v Startup finished at %v, took %v\n\n", Vers, time.Now().Format(time.RFC3339), time.Since(before)) + if TLS { errLog("", server.ListenAndServeTLS(TLSCert, TLSKey)) } else { @@ -52,6 +52,7 @@ func Start() { func newServer(port string, index *mux.Router) *http.Server { // handlers.CompressHandler gzips all responses. + // ipMiddleware passes the request IP along. // Write/Read timeouts are self explanatory. return &http.Server{ Handler: handlers.CompressHandler(ipMiddleware(index)), @@ -65,11 +66,9 @@ func setIndexRouting(index *mux.Router) { index.Path("/"). Methods("GET", "HEAD"). HandlerFunc(staticHandler) - index.Path("/css"). Methods("GET", "HEAD"). HandlerFunc(staticHandler) - index.Path("/api"). Methods("GET", "HEAD"). HandlerFunc(apiBaseHandler) @@ -93,7 +92,6 @@ func setEndpointRouting(api *mux.Router) { api.Path("/{format:(?:plain)}/{endpoint:(?:mentions|users|tweets)}"). Methods("GET", "HEAD"). HandlerFunc(apiEndpointHandler) - api.Path("/{format:(?:plain)}/{endpoint:(?:mentions|users|tweets)}"). Queries("url", "{url}", "q", "{query}", "page", "{[0-9]+}"). Methods("GET", "HEAD"). @@ -105,14 +103,12 @@ func setEndpointRouting(api *mux.Router) { Queries("url", "{url}", "nickname", "{nickname:[a-zA-Z0-9_-]+}"). Methods("POST"). HandlerFunc(apiEndpointPOSTHandler) - // This is for submitting new users incorrectly // and letting the requester know about their error. api.Path("/{format:(?:plain)}/{endpoint:users}"). Queries("url", "{url}"). Methods("POST"). HandlerFunc(apiEndpointPOSTHandler) - // This is also for submitting new users incorrectly // and letting the requester know about their error. api.Path("/{format:(?:plain)}/{endpoint:users}"). @@ -124,7 +120,6 @@ func setEndpointRouting(api *mux.Router) { api.Path("/{format:(?:plain)}/tags"). Methods("GET", "HEAD"). HandlerFunc(apiTagsBaseHandler) - // Show Nth page of all observed tags api.Path("/{format:(?:plain)}/tags"). Queries("page", "{[0-9]+}"). @@ -135,7 +130,6 @@ func setEndpointRouting(api *mux.Router) { api.Path("/{format:(?:plain)}/tags/{tags:[a-zA-Z0-9_-]+}"). Methods("GET", "HEAD"). HandlerFunc(apiTagsHandler) - // Requests Nth page of statuses with a specific tag api.Path("/{format:(?:plain)}/tags/{tags:[a-zA-Z0-9_-]+}"). Queries("page", "{[0-9]+}"). -- cgit 1.4.1-2-gfad0 tik/mu/blame/mu_instructions?h=hlt&id=db469acb3ad1e996d41b842ca579def706c308dd'>^
fa805850 ^




21ff6d83 ^



db469acb ^



59391f2a ^
db469acb ^
59391f2a ^
db469acb ^
59391f2a ^
ab26c894 ^
fa805850 ^







59391f2a ^
fa805850 ^





ef845524 ^



fa805850 ^




48d96636 ^
fa805850 ^





13235878 ^
3f30e4c6 ^
13235878 ^

3f30e4c6 ^
















































































c3964ff6 ^















fa805850 ^






















































611e9f2e ^
8d32a9aa ^


ccadc6e6 ^










8d32a9aa ^

fa805850 ^

924ed08a ^
606c1ab4 ^
114641e2 ^
be19cb87 ^

114641e2 ^
985f7f79 ^

fee1bbd8 ^
d89af9bd ^


2715d377 ^
d89af9bd ^
fee1bbd8 ^
d89af9bd ^
2715d377 ^
d89af9bd ^
3cf03158 ^

d89af9bd ^
3cf03158 ^
d89af9bd ^
3cf03158 ^
fa805850 ^
fee1bbd8 ^
15676346 ^
d89af9bd ^



15676346 ^


27b1e19e ^
15676346 ^



















d89af9bd ^
606c1ab4 ^
8b85a07f ^



b3998440 ^
fa805850 ^
b3998440 ^
fa805850 ^
8b85a07f ^
5e0ae917 ^







af983921 ^


2715d377 ^

002f2609 ^


af983921 ^





0ef7f1d2 ^
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396