-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.go
383 lines (344 loc) · 11.2 KB
/
views.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
// Copyright 2023-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package rosmar
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"time"
sgbucket "github.com/couchbase/sg-bucket"
)
// A single view stored in a Bucket.
type rosmarView struct {
fullName string // "collection/designdoc/name"
id int64 // Database primary key (views.id)
mapFnSource string // Map function source code
reduceFnSource string // Reduce function (if any)
lastCas uint64 // Collection's lastCas when indexed
mapFunction *sgbucket.JSMapFunction // The compiled map function
}
type viewKey struct {
designDoc string
name string
}
func (vn *viewKey) String() string { return vn.designDoc + "/" + vn.name }
const kMapFnTimeout = 5 * time.Second
//////// API:
func (c *Collection) View(ctx context.Context, designDoc string, viewName string, params map[string]interface{}) (result sgbucket.ViewResult, err error) {
debug("View(%q, %q, %+v)", designDoc, viewName, params)
return c.view(ctx, designDoc, viewName, params)
}
func (c *Collection) ViewQuery(ctx context.Context, designDoc string, viewName string, params map[string]interface{}) (sgbucket.QueryResultIterator, error) {
debug("ViewQuery(%q, %q, %+v)", designDoc, viewName, params)
viewResult, err := c.view(ctx, designDoc, viewName, params)
return &viewResult, err
}
func (c *Collection) ViewCustom(ctx context.Context, designDoc string, viewName string, params map[string]interface{}, vres interface{}) error {
debug("ViewCustom(%q, %q, %+v)", designDoc, viewName, params)
result, err := c.view(ctx, designDoc, viewName, params)
if err != nil {
return err
}
marshaled, _ := json.Marshal(result)
return json.Unmarshal(marshaled, vres)
}
func (c *Collection) GetStatsVbSeqno(maxVbno uint16, useAbsHighSeqNo bool) (uuids map[uint16]uint64, highSeqnos map[uint16]uint64, err error) {
err = &ErrUnimplemented{reason: "Rosmar does not implement GetStatsVbSeqno"}
return
}
//////// IMPLEMENTATION:
func (c *Collection) view(
ctx context.Context,
designDoc string,
viewName string,
jsonParams map[string]interface{},
) (result sgbucket.ViewResult, err error) {
params, err := sgbucket.ParseViewParams(jsonParams)
if err != nil {
return
}
// Look up the view and its index:
view, err := c.findView(ctx, c.db(), designDoc, viewName)
if err != nil {
return result, err
}
lastCas, err := c.getLastCas(c.db())
if err != nil {
return
}
// Update the view index if it's out of date:
if view.lastCas != lastCas {
var staleVal any
if jsonParams != nil {
staleVal = jsonParams["stale"]
}
if staleVal == "updateAfter" {
go func() {
debug("\t{updating view in background...}")
_, _ = c.updateView(ctx, designDoc, viewName)
debug("\t{...done updating view in background}")
}()
} else if staleVal != true && staleVal != "ok" {
if view, err = c.updateView(ctx, designDoc, viewName); err != nil {
return
}
}
}
// Fetch the view index:
if result, err = c.getViewRows(view, ¶ms); err != nil {
return
}
// Filter and reduce:
err = result.ProcessParsed(params, c, view.reduceFnSource)
debug("\tView --> %d rows", result.TotalRows)
return
}
// Returns an up-to-date `rosmarView` for a given view name.
func (c *Collection) findView(ctx context.Context, q queryable, designDoc string, viewName string) (view *rosmarView, err error) {
key := viewKey{designDoc, viewName}
row := q.QueryRow(`SELECT views.id, views.mapFn, views.reduceFn, views.lastCas
FROM views JOIN designDocs ON views.designDoc=designDocs.id
WHERE designDocs.collection=?1 AND designDocs.name=?2 AND views.name=?3`,
c.id, designDoc, viewName)
view = &rosmarView{
fullName: fmt.Sprintf("%s/%s/%s", c, designDoc, viewName),
}
err = scan(row, &view.id, &view.mapFnSource, &view.reduceFnSource, &view.lastCas)
if err != nil {
if err == sql.ErrNoRows {
err = sgbucket.MissingError{Key: key.String()}
delete(c.viewCache, key) // Remove any cached copy
}
return
}
c.mutex.Lock()
defer c.mutex.Unlock()
if cachedView, found := c.viewCache[key]; found {
// Reuse cached compiled map function:
if cachedView.mapFnSource == view.mapFnSource {
view.mapFunction = cachedView.mapFunction
}
}
if view.mapFunction == nil {
view.mapFunction = sgbucket.NewJSMapFunction(ctx, view.mapFnSource, kMapFnTimeout)
}
// Cache it:
if c.viewCache == nil {
c.viewCache = map[viewKey]*rosmarView{}
}
c.viewCache[key] = view
return
}
// Remove in-memory view objects for a design doc: [Collection must be locked]
func (c *Collection) forgetCachedViews(designDoc string) {
for name := range c.viewCache {
if name.designDoc == designDoc {
delete(c.viewCache, name)
}
}
}
type mapInput struct {
doc_id int64
sgbucket.JSMapFunctionInput
}
type mapOutput struct {
docID string
doc_id int64
rows []mapRow
err error
}
type mapRow struct {
key, value []byte
}
// Updates the view index if necessary.
func (c *Collection) updateView(ctx context.Context, designDoc string, viewName string) (view *rosmarView, err error) {
err = c.bucket.inTransaction(func(txn *sql.Tx) error {
// Read the view to ensure we get the current lastCas, mapFn, reduceFn:
view, err = c.findView(ctx, txn, designDoc, viewName)
if err != nil {
return err
}
latestCas, err := c.getLastCas(txn)
if err != nil || latestCas == view.lastCas {
return err
}
info("Updating view %s index to cas %d (from %d)", view.fullName, latestCas, view.lastCas)
// First delete all obsolete index rows, i.e. those whose source doc has been
// updated since view.lastCas:
_, err = txn.Exec(`DELETE FROM mapped WHERE view=?1 AND doc IN
(SELECT id FROM documents WHERE collection=?2 AND cas > ?3)`,
view.id, c.id, view.lastCas)
if err != nil {
return err
}
// Now iterate over all those updated docs:
rows, err := txn.Query(`SELECT id, key, value, cas, isJSON, xattrs FROM documents
WHERE collection=?1 AND cas > ?2
AND (value NOT NULL OR xattrs NOT NULL)`,
c.id, view.lastCas)
if err != nil {
return err
}
defer rows.Close()
// One goroutine reads documents from the db:
mapInputChan := make(chan *mapInput, 100)
go func() {
defer close(mapInputChan)
for rows.Next() {
// Read the document from the query row:
var input mapInput
var value []byte
var isJSON bool
var rawXattrs []byte
if err := rows.Scan(&input.doc_id, &input.DocID, &value, &input.VbSeq, &isJSON, &rawXattrs); err != nil {
logError("Error reading doc %q for view: %s", input.DocID, err)
continue
}
input.VbNo = sgbucket.VBHash(input.DocID, kNumVbuckets)
if isJSON && value != nil {
input.Doc = string(value)
} else {
input.Doc = "{}"
}
if len(rawXattrs) > 0 {
var semiParsed semiParsedXattrs
err = json.Unmarshal(rawXattrs, &semiParsed)
if err != nil {
logError("Error unmarshaling xattrs of doc %q: %s", input.DocID, err)
continue
} else {
input.Xattrs = make(map[string][]byte, len(semiParsed))
for key, val := range semiParsed {
input.Xattrs[key] = val
}
}
}
mapInputChan <- &input
}
}()
// Another goroutine pool calls the map function on the docs:
mapOutputChan := parallelize(mapInputChan, 0, func(input *mapInput) (out mapOutput) {
// Call the map function:
viewRows, err := view.mapFunction.CallFunction(ctx, &input.JSMapFunctionInput)
if err == nil {
// Marshal each key and value:
jsonRows := make([]mapRow, len(viewRows))
for i, row := range viewRows {
if jsonRows[i].key, err = json.Marshal(row.Key); err != nil {
break
} else if jsonRows[i].value, err = json.Marshal(row.Value); err != nil {
break
}
}
if err == nil {
out.rows = jsonRows
}
}
if err != nil {
logError("Error running map function on doc %q: %s", input.DocID, err)
}
out.docID = input.DocID
out.doc_id = input.doc_id
return
})
// And finally we read the emitted rows and write them to the db:
for docRows := range mapOutputChan {
if docRows.err != nil {
continue
}
// Insert each emitted row into the `mapped` table:
for _, row := range docRows.rows {
//trace("\tEMIT %s , %s (doc %d %q)", row.key, row.value, docRows.doc_id, docRows.docID)
_, err := txn.Exec(`INSERT INTO mapped (view,doc,key,value)
VALUES (?1, ?2, ?3, ?4)`,
view.id, docRows.doc_id, string(row.key), string(row.value))
if err != nil {
return err
}
}
}
if err = rows.Close(); err != nil {
return err
}
_, err = txn.Exec(`UPDATE views SET lastCas=?1 WHERE id=?2`, latestCas, view.id)
if err == nil {
view.lastCas = latestCas
}
return err
})
return view, err
}
// Returns all the view rows from the database.
// Handles key ranges, descending order and limit (and clears the corresponding params)
// but does not reduce.
func (c *Collection) getViewRows(view *rosmarView, params *sgbucket.ViewParams) (result sgbucket.ViewResult, err error) {
args := []any{sql.Named(`VIEW`, view.id)}
sel := `SELECT documents.key, mapped.key, mapped.value, `
sel += ifelse(params.IncludeDocs, `documents.value `, `null `)
sel += `FROM mapped INNER JOIN documents ON mapped.doc=documents.id WHERE mapped.view=$VIEW `
setMinMax := func(minmax *any, inclusive bool, cmp string, arg string) error {
if *minmax != nil {
sel += `AND mapped.key ` + cmp
if inclusive {
sel += `=`
}
sel += ` $` + arg + ` `
if jsonKey, jsonErr := json.Marshal(*minmax); jsonErr == nil {
args = append(args, sql.Named(arg, string(jsonKey)))
} else {
return jsonErr
}
*minmax = nil
}
return nil
}
if err = setMinMax(¶ms.MinKey, params.IncludeMinKey, `>`, "MINKEY"); err != nil {
return
}
if err = setMinMax(¶ms.MaxKey, params.IncludeMaxKey, `<`, "MAXKEY"); err != nil {
return
}
if params.Descending {
sel += `ORDER BY mapped.key DESC, documents.key DESC `
params.Descending = false
} else {
sel += `ORDER BY mapped.key, documents.key `
}
if params.Limit != nil {
sel += fmt.Sprintf(`LIMIT %d `, *params.Limit)
params.Limit = nil
}
rows, err := c.db().Query(sel, args...)
if err != nil {
return
}
for rows.Next() {
var viewRow sgbucket.ViewRow
var jsonKey, jsonValue, jsonDoc []byte
if err = rows.Scan(&viewRow.ID, &jsonKey, &jsonValue, &jsonDoc); err != nil {
return
} else if err = json.Unmarshal(jsonKey, &viewRow.Key); err != nil {
return
} else if err = json.Unmarshal(jsonValue, &viewRow.Value); err != nil {
return
}
if params.IncludeDocs {
if err = json.Unmarshal(jsonDoc, &viewRow.Doc); err != nil {
return
}
}
result.Rows = append(result.Rows, &viewRow)
//trace("\tRow --> %s = %s (doc %q)", jsonKey, jsonValue, viewRow.ID)
}
err = rows.Close()
result.TotalRows = len(result.Rows)
params.IncludeDocs = false // we already did it
info("Queried view %s --> %d rows", view.fullName, result.TotalRows)
return
}