/
bulk.go
424 lines (392 loc) · 11.6 KB
/
bulk.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
package couchdb
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/cozy/cozy-stack/pkg/config/config"
"github.com/cozy/cozy-stack/pkg/couchdb/revision"
"github.com/cozy/cozy-stack/pkg/logger"
"github.com/cozy/cozy-stack/pkg/prefixer"
"github.com/cozy/cozy-stack/pkg/realtime"
"github.com/google/go-querystring/query"
)
// AllDocsRequest is used to build a _all_docs request
type AllDocsRequest struct {
Descending bool `url:"descending,omitempty"`
Limit int `url:"limit,omitempty"`
Skip int `url:"skip,omitempty"`
StartKey string `url:"startkey,omitempty"`
EndKey string `url:"endkey,omitempty"`
Keys []string `url:"keys,omitempty"`
}
// AllDocsResponse is the response we receive from an _all_docs request
type AllDocsResponse struct {
Offset int `json:"offset"`
TotalRows int `json:"total_rows"`
Rows []AllDocsRow `json:"rows"`
}
// AllDocsRow is a row inside the _all_docs response
type AllDocsRow struct {
ID string `json:"id"`
Doc json.RawMessage `json:"doc"`
}
// IDRev is used for the payload of POST _bulk_get
type IDRev struct {
ID string `json:"id"`
Rev string `json:"rev,omitempty"`
}
// BulkGetResponse is the response we receive from a _bulk_get request
type BulkGetResponse struct {
Results []struct {
Docs []struct {
OK map[string]interface{} `json:"ok"`
} `json:"docs"`
} `json:"results"`
}
// CountAllDocs returns the number of documents of the given doctype.
func CountAllDocs(db prefixer.Prefixer, doctype string) (int, error) {
var response AllDocsResponse
url := "_all_docs?limit=0"
err := makeRequest(db, doctype, http.MethodGet, url, nil, &response)
if err != nil {
return 0, err
}
return response.TotalRows, nil
}
// CountNormalDocs returns the number of documents of the given doctype,
// and excludes the design docs from the count.
func CountNormalDocs(db prefixer.Prefixer, doctype string) (int, error) {
var designRes ViewResponse
err := makeRequest(db, doctype, http.MethodGet, "_design_docs", nil, &designRes)
if err != nil {
return 0, err
}
total := designRes.Total
// CouchDB response for the total_rows on the _design_docs endpoint:
// - is the total number of documents on CouchDB 2.2 (and before)
// - is the total number of design documents on CouchDB 2.3+
// See https://github.com/apache/couchdb/issues/1603
if total == len(designRes.Rows) {
if total, err = CountAllDocs(db, doctype); err != nil {
return 0, err
}
}
return total - len(designRes.Rows), nil
}
// GetAllDocs returns all documents of a specified doctype. It filters
// out the possible _design document.
func GetAllDocs(db prefixer.Prefixer, doctype string, req *AllDocsRequest, results interface{}) (err error) {
return getAllDocs(db, doctype, req, results, false)
}
// GetDesignDocs does the same as GetAllDocs, but it keeps the design docs.
func GetDesignDocs(db prefixer.Prefixer, doctype string, req *AllDocsRequest, results interface{}) (err error) {
return getAllDocs(db, doctype, req, results, true)
}
func getAllDocs(db prefixer.Prefixer, doctype string, req *AllDocsRequest, results interface{}, includeDesignDocs bool) (err error) {
var v url.Values
if req != nil {
v, err = req.Values()
if err != nil {
return err
}
} else {
v = make(url.Values)
}
v.Add("include_docs", "true")
var response AllDocsResponse
if req == nil || len(req.Keys) == 0 {
url := "_all_docs?" + v.Encode()
err = makeRequest(db, doctype, http.MethodGet, url, nil, &response)
} else {
v.Del("keys")
url := "_all_docs?" + v.Encode()
body := struct {
Keys []string `json:"keys"`
}{
Keys: req.Keys,
}
err = makeRequest(db, doctype, http.MethodPost, url, body, &response)
}
if err != nil {
return err
}
var docs []json.RawMessage
for _, row := range response.Rows {
if includeDesignDocs || !strings.HasPrefix(row.ID, "_design") {
docs = append(docs, row.Doc)
}
}
data, err := json.Marshal(docs)
if err != nil {
return err
}
return json.Unmarshal(data, results)
}
func MakeAllDocsRequest(db prefixer.Prefixer, doctype string, params *AllDocsRequest) (io.ReadCloser, error) {
if len(params.Keys) > 0 {
return nil, errors.New("keys is not supported by MakeAllDocsRequest")
}
var v url.Values
var err error
if params != nil {
v, err = params.Values()
if err != nil {
return nil, err
}
} else {
v = make(url.Values)
}
v.Add("include_docs", "true")
path := "_all_docs?" + v.Encode()
method := http.MethodGet
log := logger.WithDomain(db.DomainName()).WithNamespace("couchdb")
if log.IsDebug() {
log.Debugf("request: %s %s %s", method, path, "")
}
req, err := buildCouchRequest(db, doctype, method, path, nil, nil)
if err != nil {
log.Error(err.Error())
return nil, err
}
start := time.Now()
resp, err := config.CouchClient().Do(req)
elapsed := time.Since(start)
// Possible err = mostly connection failure
if err != nil {
err = newConnectionError(err)
log.Error(err.Error())
return nil, err
}
if elapsed.Seconds() >= 10 {
log.Infof("slow request on %s %s (%s)", method, path, elapsed)
}
if err = handleResponseError(db, resp); err != nil {
return nil, err
}
return resp.Body, nil
}
// ForeachDocs traverse all the documents from the given database with the
// specified doctype and calls a function for each document.
func ForeachDocs(db prefixer.Prefixer, doctype string, fn func(id string, doc json.RawMessage) error) error {
return ForeachDocsWithCustomPagination(db, doctype, 100, fn)
}
// ForeachDocsWithCustomPagination traverse all the documents from the given
// database, and calls a function for each document. The documents are fetched
// from CouchDB with a pagination with a custom number of items per page.
func ForeachDocsWithCustomPagination(db prefixer.Prefixer, doctype string, limit int, fn func(id string, doc json.RawMessage) error) error {
var startKey string
for {
skip := 0
if startKey != "" {
skip = 1
}
req := &AllDocsRequest{
StartKey: `"` + startKey + `"`,
Skip: skip,
Limit: limit,
}
v, err := query.Values(req)
if err != nil {
return err
}
v.Add("include_docs", "true")
var res AllDocsResponse
url := "_all_docs?" + v.Encode()
err = makeRequest(db, doctype, http.MethodGet, url, nil, &res)
if err != nil {
return err
}
startKey = ""
for _, row := range res.Rows {
if !strings.HasPrefix(row.ID, "_design") {
if err = fn(row.ID, row.Doc); err != nil {
return err
}
}
startKey = row.ID
}
if len(res.Rows) < limit {
break
}
}
return nil
}
// BulkGetDocs returns the documents with the given id at the given revision
func BulkGetDocs(db prefixer.Prefixer, doctype string, payload []IDRev) ([]map[string]interface{}, error) {
path := "_bulk_get?revs=true"
body := struct {
Docs []IDRev `json:"docs"`
}{
Docs: payload,
}
var response BulkGetResponse
err := makeRequest(db, doctype, http.MethodPost, path, body, &response)
if err != nil {
return nil, err
}
results := make([]map[string]interface{}, 0, len(response.Results))
for _, r := range response.Results {
for _, doc := range r.Docs {
if doc.OK != nil {
results = append(results, doc.OK)
}
}
}
return results, nil
}
// BulkUpdateDocs is used to update several docs in one call, as a bulk.
// olddocs parameter is used for realtime / event triggers.
func BulkUpdateDocs(db prefixer.Prefixer, doctype string, docs, olddocs []interface{}) error {
if len(docs) == 0 {
return nil
}
remaining := docs
olds := olddocs
for len(remaining) > 0 {
n := 1000
if len(remaining) < n {
n = len(remaining)
}
bulkDocs := remaining[:n]
remaining = remaining[n:]
bulkOlds := olds[:n]
olds = olds[n:]
if err := bulkUpdateDocs(db, doctype, bulkDocs, bulkOlds); err != nil {
if IsNoDatabaseError(err) {
if err := EnsureDBExist(db, doctype); err != nil {
return err
}
}
// If it fails once, try again
time.Sleep(1 * time.Second)
if err := bulkUpdateDocs(db, doctype, bulkDocs, bulkOlds); err != nil {
return err
}
}
}
return nil
}
func bulkUpdateDocs(db prefixer.Prefixer, doctype string, docs, olddocs []interface{}) error {
body := struct {
Docs []interface{} `json:"docs"`
}{
Docs: docs,
}
var res []UpdateResponse
if err := makeRequest(db, doctype, http.MethodPost, "_bulk_docs", body, &res); err != nil {
return err
}
if len(res) != len(docs) {
return errors.New("BulkUpdateDoc receive an unexpected number of responses")
}
logBulk(db, "BulkUpdateDocs", doctype, res)
for i, doc := range docs {
if d, ok := doc.(Doc); ok {
update := res[i]
if update.Error != "" {
logger.WithDomain(db.DomainName()).WithNamespace("couchdb").
Warnf("bulkUpdateDocs error for %s %s: %s - %s", doctype, update.ID, update.Error, update.Reason)
}
if update.ID == "" || update.Rev == "" || !update.Ok {
continue
}
event := realtime.EventUpdate
if d.Rev() == "" {
event = realtime.EventCreate
d.SetID(update.ID)
}
d.SetRev(update.Rev)
if old, ok := olddocs[i].(Doc); ok {
RTEvent(db, realtime.EventUpdate, d, old)
} else {
RTEvent(db, event, d, nil)
}
}
}
return nil
}
// BulkDeleteDocs is used to delete serveral documents in one call.
func BulkDeleteDocs(db prefixer.Prefixer, doctype string, docs []Doc) error {
if len(docs) == 0 {
return nil
}
body := struct {
Docs []json.RawMessage `json:"docs"`
}{
Docs: make([]json.RawMessage, 0, len(docs)),
}
for _, doc := range docs {
body.Docs = append(body.Docs, json.RawMessage(
fmt.Sprintf(`{"_id":"%s","_rev":"%s","_deleted":true}`, doc.ID(), doc.Rev()),
))
}
var res []UpdateResponse
if err := makeRequest(db, doctype, http.MethodPost, "_bulk_docs", body, &res); err != nil {
return err
}
for i, doc := range docs {
doc.SetRev(res[i].Rev)
RTEvent(db, realtime.EventDelete, doc, nil)
}
logBulk(db, "BulkDeleteDocs", doctype, docs)
return nil
}
// BulkForceUpdateDocs is used to update several docs in one call, and to force
// the revisions history. It is used by replications.
func BulkForceUpdateDocs(db prefixer.Prefixer, doctype string, docs []map[string]interface{}) error {
if len(docs) == 0 {
return nil
}
body := struct {
NewEdits bool `json:"new_edits"`
Docs []map[string]interface{} `json:"docs"`
}{
NewEdits: false,
Docs: docs,
}
logBulk(db, "BulkForceUpdateDocs", doctype, docs)
// XXX CouchDB returns just an empty array when new_edits is false, so we
// ignore the response
return makeRequest(db, doctype, http.MethodPost, "_bulk_docs", body, nil)
}
func logBulk(db prefixer.Prefixer, prefix, doctype string, docs interface{}) {
extracted := make([]string, 0, 1000)
if documents, ok := docs.([]Doc); ok {
for _, doc := range documents {
id := doc.ID()
rev := revision.Generation(doc.Rev())
extracted = append(extracted, fmt.Sprintf("%s (%d)", id, rev))
}
} else if updates, ok := docs.([]UpdateResponse); ok {
for _, update := range updates {
id := update.ID
rev := revision.Generation(update.Rev)
extracted = append(extracted, fmt.Sprintf("%s (%d)", id, rev))
}
} else if maps, ok := docs.([]map[string]interface{}); ok {
for _, doc := range maps {
id, _ := doc["_id"].(string)
extracted = append(extracted, id)
}
}
var messages []string
for len(extracted) > 0 {
nb := len(extracted)
// We limit the number of ids per log to avoid the line width limit.
if nb > 50 {
nb = 50
}
msg := strings.Join(extracted[:nb], " ")
messages = append(messages, msg)
extracted = extracted[nb:]
}
for _, msg := range messages {
logger.WithDomain(db.DomainName()).WithNamespace("couchdb").
Infof("%s for %s: %s", prefix, doctype, msg)
}
}