/
db.go
224 lines (205 loc) · 6.57 KB
/
db.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
/*
* Copyright 2021 National Library of Norway.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package database
import (
"context"
"fmt"
configV1 "github.com/nlnwa/veidemann-api/go/config/v1"
"github.com/nlnwa/veidemann-api/go/contentwriter/v1"
"github.com/rs/zerolog"
zlog "github.com/rs/zerolog/log"
r "gopkg.in/rethinkdb/rethinkdb-go.v6"
"time"
)
// RethinkDbConnection holds the database connection
type RethinkDbConnection struct {
connectOpts r.ConnectOpts
session r.QueryExecutor
maxRetries int
waitTimeout time.Duration
queryTimeout time.Duration
batchSize int
logger zerolog.Logger
}
type Options struct {
Username string
Password string
Database string
UseOpenTracing bool
Address string
QueryTimeout time.Duration
MaxRetries int
MaxOpenConnections int
}
// NewRethinkDbConnection creates a new RethinkDbConnection object
func NewRethinkDbConnection(opts Options) *RethinkDbConnection {
return &RethinkDbConnection{
connectOpts: r.ConnectOpts{
Address: opts.Address,
Username: opts.Username,
Password: opts.Password,
Database: opts.Database,
InitialCap: 2,
MaxOpen: opts.MaxOpenConnections,
UseOpentracing: opts.UseOpenTracing,
NumRetries: 10,
Timeout: 10 * time.Second,
},
maxRetries: opts.MaxRetries,
waitTimeout: 60 * time.Second,
queryTimeout: opts.QueryTimeout,
batchSize: 200,
logger: zlog.With().Str("component", "rethinkdb").Logger(),
}
}
// Connect establishes connections
func (c *RethinkDbConnection) Connect() error {
log := c.logger
var err error
// Set up database RethinkDbConnection
c.session, err = r.Connect(c.connectOpts)
if err != nil {
return fmt.Errorf("failed to connect to RethinkDB at %s: %w", c.connectOpts.Address, err)
}
log.Info().Msgf("Connected to RethinkDB at %s", c.connectOpts.Address)
return nil
}
// Close closes the RethinkDbConnection
func (c *RethinkDbConnection) Close() error {
log := c.logger
log.Info().Msgf("Closing connection to RethinkDB")
return c.session.(*r.Session).Close()
}
// GetConfigObject fetches a config.ConfigObject referenced by a config.ConfigRef
func (c *RethinkDbConnection) GetConfigObject(ctx context.Context, ref *configV1.ConfigRef) (*configV1.ConfigObject, error) {
term := r.Table("config").Get(ref.Id)
res, err := c.execRead(ctx, "get-config-object", &term)
if err != nil {
return nil, err
}
var result configV1.ConfigObject
err = res.One(&result)
if err != nil {
return nil, err
}
return &result, nil
}
func (c *RethinkDbConnection) HasCrawledContent(ctx context.Context, payloadDigest string) (*contentwriter.CrawledContent, error) {
if payloadDigest == "" {
return nil, fmt.Errorf("The required field 'digest' is missing from: 'crawledContent'")
}
term := r.Table("crawled_content").Get(payloadDigest)
response, err := c.execRead(ctx, "db-hasCrawledContent", &term)
if err != nil {
return nil, err
}
if response.IsNil() {
return nil, nil
} else {
var res contentwriter.CrawledContent
err := response.One(&res)
return &res, err
}
}
func (c *RethinkDbConnection) WriteCrawledContent(ctx context.Context, crawledContent *contentwriter.CrawledContent) error {
if crawledContent.Digest == "" {
return fmt.Errorf("The required field 'digest' is missing from: 'crawledContent'")
}
if crawledContent.WarcId == "" {
return fmt.Errorf("The required field 'warc_id' is missing from: 'crawledContent'")
}
if crawledContent.TargetUri == "" {
return fmt.Errorf("The required field 'target_uri' is missing from: 'crawledContent'")
}
if crawledContent.Date == nil {
return fmt.Errorf("The required field 'date' is missing from: 'crawledContent'")
}
term := r.Table("crawled_content").Insert(crawledContent)
err := c.execWrite(ctx, "db-writeCrawledContent", &term)
if err != nil {
return err
}
return nil
}
// execRead executes the given read term with a timeout
func (c *RethinkDbConnection) execRead(ctx context.Context, name string, term *r.Term) (*r.Cursor, error) {
q := func(ctx context.Context) (*r.Cursor, error) {
runOpts := r.RunOpts{
Context: ctx,
}
return term.Run(c.session, runOpts)
}
return c.execWithRetry(ctx, name, q)
}
// execWrite executes the given write term with a timeout
func (c *RethinkDbConnection) execWrite(ctx context.Context, name string, term *r.Term) error {
q := func(ctx context.Context) (*r.Cursor, error) {
runOpts := r.RunOpts{
Context: ctx,
Durability: "soft",
}
_, err := (*term).RunWrite(c.session, runOpts)
return nil, err
}
_, err := c.execWithRetry(ctx, name, q)
return err
}
// execWithRetry executes given query function repeatedly until successful or max retry limit is reached
func (c *RethinkDbConnection) execWithRetry(ctx context.Context, name string, q func(ctx context.Context) (*r.Cursor, error)) (cursor *r.Cursor, err error) {
attempts := 0
log := c.logger.With().Str("operation", name).Logger()
out:
for {
attempts++
cursor, err = c.exec(ctx, q)
if err == nil {
return
}
log.Warn().Err(err).Int("retries", attempts-1).Msg("Failed to execute query")
switch err {
case r.ErrQueryTimeout:
err := c.wait()
if err != nil {
log.Warn().Err(err).Msg("Timed out waiting for database to be ready")
}
case r.ErrConnectionClosed:
err := c.Connect()
if err != nil {
log.Warn().Err(err).Msg("Failed to reconnect database")
}
default:
break out
}
if attempts > c.maxRetries {
break
}
}
return nil, fmt.Errorf("failed to %s after %d of %d attempts: %w", name, attempts, c.maxRetries+1, err)
}
// exec executes the given query with a timeout
func (c *RethinkDbConnection) exec(ctx context.Context, q func(ctx context.Context) (*r.Cursor, error)) (*r.Cursor, error) {
ctx, cancel := context.WithTimeout(ctx, c.queryTimeout)
defer cancel()
return q(ctx)
}
// wait waits for database to be fully up date and ready for read/write
func (c *RethinkDbConnection) wait() error {
waitOpts := r.WaitOpts{
Timeout: c.waitTimeout,
}
_, err := r.DB(c.connectOpts.Database).Wait(waitOpts).Run(c.session)
return err
}