-
Notifications
You must be signed in to change notification settings - Fork 402
/
usedserials.go
71 lines (53 loc) · 1.93 KB
/
usedserials.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
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package storagenodedb
import (
"context"
"time"
"github.com/zeebo/errs"
"storj.io/storj/pkg/storj"
"storj.io/storj/storagenode/piecestore"
)
// ErrUsedSerials represents errors from the used serials database.
var ErrUsedSerials = errs.Class("usedserialsdb error")
// UsedSerialsDBName represents the database name.
const UsedSerialsDBName = "used_serial"
type usedSerialsDB struct {
migratableDB
}
// Add adds a serial to the database.
func (db *usedSerialsDB) Add(ctx context.Context, satelliteID storj.NodeID, serialNumber storj.SerialNumber, expiration time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = db.Exec(`
INSERT INTO
used_serial_(satellite_id, serial_number, expiration)
VALUES(?, ?, ?)`, satelliteID, serialNumber, expiration.UTC())
return ErrUsedSerials.Wrap(err)
}
// DeleteExpired deletes expired serial numbers
func (db *usedSerialsDB) DeleteExpired(ctx context.Context, now time.Time) (err error) {
defer mon.Task()(&ctx)(&err)
_, err = db.Exec(`DELETE FROM used_serial_ WHERE expiration < ?`, now.UTC())
return ErrUsedSerials.Wrap(err)
}
// IterateAll iterates all serials.
// Note, this will lock the database and should only be used during startup.
func (db *usedSerialsDB) IterateAll(ctx context.Context, fn piecestore.SerialNumberFn) (err error) {
defer mon.Task()(&ctx)(&err)
rows, err := db.Query(`SELECT satellite_id, serial_number, expiration FROM used_serial_`)
if err != nil {
return ErrUsedSerials.Wrap(err)
}
defer func() { err = errs.Combine(err, ErrUsedSerials.Wrap(rows.Close())) }()
for rows.Next() {
var satelliteID storj.NodeID
var serialNumber storj.SerialNumber
var expiration time.Time
err := rows.Scan(&satelliteID, &serialNumber, &expiration)
if err != nil {
return ErrUsedSerials.Wrap(err)
}
fn(satelliteID, serialNumber, expiration)
}
return ErrUsedSerials.Wrap(rows.Err())
}