This repository has been archived by the owner on Oct 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 74
/
dbInit.go
464 lines (405 loc) · 9.55 KB
/
dbInit.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
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
// Initializes and loads RethinkDB
package db
import (
"fmt"
"log"
"time"
"encoding/base64"
"encoding/hex"
"github.com/bakape/meguca/auth"
"github.com/bakape/meguca/config"
"github.com/bakape/meguca/util"
r "github.com/dancannon/gorethink"
)
const dbVersion = 19
var (
// Address of the RethinkDB cluster instance to connect to
Address = "localhost:28015"
// DBName is the name of the database to use
DBName = "meguca"
// IsTest can be overridden to not launch several infinite loops during tests
// or check DB version
IsTest bool
// RSession exports the RethinkDB connection session. Used globally by the
// entire server.
RSession *r.Session
// AllTables are all tables needed for meguca operation
AllTables = []string{
// Various global information
"main",
// Thread data
"threads",
// Post data
"posts",
// Thumbnailed upload data
"images",
// Tokens for claiming thumbnailed images from the "images" table
"imageTokens",
// Registered user accounts
"accounts",
// Board configurations
"boards",
}
// Map of simple secondary indices for tables
secondaryIndices = [...]struct {
table, index string
}{
{"imageTokens", "expires"},
{"threads", "board"},
{"posts", "op"},
{"posts", "board"},
{"posts", "editing"},
{"posts", "lastUpdated"},
}
// Query that increments the database version
incrementVersion = GetMain("info").Update(map[string]r.Term{
"dbVersion": r.Row.Field("dbVersion").Add(1),
})
)
// Document is a generic RethinkDB Document. For DRY-ness.
type Document struct {
ID string `gorethink:"id"`
}
// Central global information document
type infoDocument struct {
Document
DBVersion int `gorethink:"dbVersion"`
// Is incremented on each new post. Ensures post number uniqueness
PostCtr int64 `gorethink:"postCtr"`
}
// ConfigDocument holds the global server configurations
type ConfigDocument struct {
Document
config.Configs
}
// LoadDB establishes connections to RethinkDB and Redis and bootstraps both
// databases, if not yet done.
func LoadDB() (err error) {
if err := Connect(); err != nil {
return err
}
var isCreated bool
err = One(r.DBList().Contains(DBName), &isCreated)
if err != nil {
return util.WrapError("error checking, if database exists", err)
}
if isCreated {
RSession.Use(DBName)
if !IsTest {
if err := verifyDBVersion(); err != nil {
return err
}
}
} else if err := InitDB(); err != nil {
return err
}
if !IsTest {
go runCleanupTasks()
}
if err := loadConfigs(); err != nil {
return err
}
return loadBoardConfigs()
}
// Connect establishes a connection to RethinkDB. Address passed separately for
// easier testing.
func Connect() (err error) {
RSession, err = r.Connect(r.ConnectOpts{Address: Address})
if err != nil {
err = util.WrapError("error connecting to RethinkDB", err)
}
return
}
// Confirm database version is compatible, if not refuse to start, so we don't
// mess up the DB irreversibly.
func verifyDBVersion() error {
var version int
err := One(GetMain("info").Field("dbVersion"), &version)
if err != nil {
return util.WrapError("error reading database version", err)
}
switch version {
case dbVersion:
return nil
case 14:
if err := upgrade14to15(); err != nil {
return err
}
fallthrough
case 15:
if err := upgrade15to16(); err != nil {
return err
}
fallthrough
case 16:
err := WriteAll([]r.Term{
r.Table("posts").IndexCreate("lastUpdated"),
incrementVersion,
})
if err != nil {
return err
}
if err := waitForIndex("posts")(); err != nil {
return err
}
fallthrough
case 17:
if err := upgrade17to18(); err != nil {
return err
}
fallthrough
case 18:
if err := upgrade18to19(); err != nil {
return err
}
default:
return fmt.Errorf("incompatible database version: %d", version)
}
return nil
}
// Perform database upgrade from version 14 to 15. Inserts faux creation dates
// into all board documents.
func upgrade14to15() error {
qs := [...]r.Term{
r.Table("boards").Update(map[string]r.Term{
"created": r.Now(),
}),
incrementVersion,
}
for _, q := range qs {
if err := Write(q); err != nil {
return err
}
}
return nil
}
// Upgrade from version 15 to 16. Contains major structural changes to post
// storage.
func upgrade15to16() error {
q := r.Table("threads").Config().Update(map[string]string{
"name": "threads_old",
})
if err := Write(q); err != nil {
return err
}
qs := make([]r.Term, 0, 5)
qs = append(qs, createPostTables()...)
qs = append(qs,
// Copy all threads
r.
Table("threads").
Insert(r.Table("threads_old").Without("log", "posts")),
// Copy all posts
r.
Table("threads_old").
ForEach(func(t r.Term) r.Term {
return t.
Field("posts").
Values().
Map(func(p r.Term) r.Term {
return p.Merge(map[string]interface{}{
"op": t.Field("id"),
"board": t.Field("board"),
"lastUpdated": time.Now().Unix() - 60,
"log": [][]byte{},
})
}).
ForEach(func(p r.Term) r.Term {
return r.Table("posts").Insert(p)
})
}),
// Delete old table
r.TableDrop("threads_old"),
incrementVersion,
)
if err := WriteAll(qs); err != nil {
return err
}
return CreateIndices()
}
func upgrade17to18() error {
hexToBase64 := func(h string) (string, error) {
raw, err := hex.DecodeString(h)
if err != nil {
return "", fmt.Errorf("failed to decode hash: %s", h)
}
return base64.RawURLEncoding.EncodeToString(raw), nil
}
// Convert all hex MD5 to base64 MD5
var images []struct {
SHA1, MD5 string
}
q := r.Table("images").Pluck("SHA1", "MD5")
if err := All(q, &images); err != nil {
return err
}
for _, img := range images {
b64, err := hexToBase64(img.MD5)
if err != nil {
log.Println(err)
continue
}
q := r.Table("images").Get(img.SHA1).Update(map[string]string{
"MD5": b64,
})
if err := Write(q); err != nil {
return err
}
}
// And for posts themselves
var posts []struct {
ID int64
MD5 string
}
q = r.
Table("posts").
HasFields("image").
Map(func(p r.Term) map[string]r.Term {
return map[string]r.Term{
"id": p.Field("id"),
"MD5": p.Field("image").Field("MD5"),
}
})
if err := All(q, &posts); err != nil {
return err
}
for _, p := range posts {
b64, err := hexToBase64(p.MD5)
if err != nil {
log.Println(err)
continue
}
q := r.Table("posts").Get(p.ID).Update(map[string]map[string]string{
"image": {
"MD5": b64,
},
})
if err := Write(q); err != nil {
return err
}
}
return WriteAll([]r.Term{
r.Table("imageTokens").IndexCreate("expires"),
incrementVersion,
})
}
func upgrade18to19() error {
return WriteAll([]r.Term{
r.
Table("images").
Update(map[string]r.Term{
"thumbType": r.Branch(
r.Row.Field("fileType").Eq(0),
0,
1,
),
}),
r.
Table("posts").
HasFields("image").
Update(map[string]map[string]r.Term{
"image": {
"thumbType": r.Branch(
r.Row.Field("image").Field("fileType").Eq(0),
0,
1,
),
},
}),
incrementVersion,
})
}
// InitDB initialize a rethinkDB database
func InitDB() error {
log.Printf("initializing database '%s'", DBName)
if err := Write(r.DBCreate(DBName)); err != nil {
return util.WrapError("creating database", err)
}
RSession.Use(DBName)
if err := CreateTables(); err != nil {
return err
}
return populateDB()
}
// Populate DB with initial documents
func populateDB() error {
main := [...]interface{}{
infoDocument{Document{"info"}, dbVersion, 0},
ConfigDocument{
Document{"config"},
config.Defaults,
},
}
if err := Insert("main", main); err != nil {
return util.WrapError("initializing database", err)
}
if err := CreateAdminAccount(); err != nil {
return err
}
return CreateIndices()
}
// CreateTables creates all tables needed for meguca operation
func CreateTables() error {
qs := make([]r.Term, 0, len(AllTables))
for _, t := range AllTables {
switch t {
case "images", "threads", "posts":
default:
qs = append(qs, createTable(t))
}
}
qs = append(qs, createPostTables()...)
qs = append(qs, r.TableCreate("images", r.TableCreateOpts{
PrimaryKey: "SHA1",
}))
return WriteAll(qs)
}
func createPostTables() []r.Term {
fns := make([]r.Term, 2)
for i, t := range [...]string{"threads", "posts"} {
fns[i] = r.TableCreate(t, r.TableCreateOpts{
Durability: "soft",
})
}
return fns
}
func createTable(t string) r.Term {
return r.TableCreate(t)
}
// CreateIndices creates secondary indices for faster table queries
func CreateIndices() error {
fns := make([]func() error, 0, len(secondaryIndices)+len(AllTables))
for _, i := range secondaryIndices {
index := i // Capture variable
fns = append(fns, func() error {
return Write(r.Table(index.table).IndexCreate(index.index))
})
}
// Make sure all indices are ready to avoid the race condition of and index
// being accessed before its full creation.
for _, table := range AllTables {
fns = append(fns, waitForIndex(table))
}
return util.Waterfall(fns)
}
func waitForIndex(table string) func() error {
return func() error {
return Exec(r.Table(table).IndexWait())
}
}
// CreateAdminAccount writes a fresh admin account with the default password to
// the database
func CreateAdminAccount() error {
hash, err := auth.BcryptHash("password", 10)
if err != nil {
return err
}
return RegisterAccount("admin", hash)
}
// ClearTables deletes the contents of specified DB tables. Only used for tests.
func ClearTables(tables ...string) error {
q := r.Expr(tables).ForEach(func(table r.Term) r.Term {
return r.Table(table).Delete()
})
return Write(q)
}