Repository navigation
Expand file tree
/
Copy pathfeeds.go
More file actions
515 lines (464 loc) · 16.1 KB
/
Copy pathfeeds.go
File metadata and controls
515 lines (464 loc) · 16.1 KB
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
// 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"
"encoding/json"
"errors"
"expvar"
"fmt"
"sync/atomic"
"time"
sgbucket "github.com/couchbase/sg-bucket"
)
var activeFeedCount int32 // for tests
//////// BUCKET API: (sgbucket.MutationFeedStore interface)
func (bucket *Bucket) StartDCPFeed(ctx context.Context, args sgbucket.FeedArguments, callback sgbucket.FeedEventCallbackFunc, dbStats *expvar.Map) error {
traceEnter("StartDCPFeed", "bucket=%s, args=%+v", bucket.GetName(), args)
// Validate requested collections exist before starting feeds. No scopes means the default
// collection, if it exists. A collection named twice gets one feed.
requestedCollections := map[*Collection]struct{}{}
if len(args.Scopes) == 0 {
collection, err := bucket.getCollection(defaultDataStoreName)
if err != nil {
return err
}
requestedCollections[collection] = struct{}{}
}
for scopeName, collections := range args.Scopes {
for _, collectionName := range collections {
collection, err := bucket.getCollection(sgbucket.DataStoreNameImpl{Scope: scopeName, Collection: collectionName})
if err != nil {
return fmt.Errorf("couldn't open collection %s:%s for DCP feed: %w", scopeName, collectionName, err)
}
requestedCollections[collection] = struct{}{}
}
}
doneChan := args.DoneChan
doneChans := make(map[*Collection]chan struct{}, len(requestedCollections))
startedFeeds := make([]*dcpFeed, 0, len(requestedCollections))
for collection := range requestedCollections {
// Not bothering to remove scopes from args for the single collection feeds
// here because it's ignored by Collection.startDCPFeed
collectionID := collection.GetCollectionID()
collectionAwareCallback := func(event sgbucket.FeedEvent) bool {
event.CollectionID = collectionID
return callback(event)
}
// have each collection maintain its own doneChan
doneChans[collection] = make(chan struct{})
argsCopy := args
argsCopy.DoneChan = doneChans[collection]
feed, err := collection.startDCPFeed(ctx, argsCopy, collectionAwareCallback, dbStats)
if err != nil {
// Stop the feeds that did start: no doneChan of theirs is coalesced into the caller's now.
for _, started := range startedFeeds {
started.stop()
}
return fmt.Errorf("couldn't start DCP feed on %s: %w", collection.DataStoreNameImpl, err)
}
startedFeeds = append(startedFeeds, feed)
}
// coalesce doneChans
go func() {
for _, done := range doneChans {
<-done
}
// The collections share one checkpoint document, so a dump saves it once they have all stopped.
if args.Dump {
_ = saveDumpCheckpoint(startedFeeds)
}
if doneChan != nil {
close(doneChan)
}
}()
return nil
}
//////// COLLECTION API:
// startDCPFeed starts a feed and returns it, so that a caller starting feeds on several collections can stop
// the ones it already started.
func (c *Collection) startDCPFeed(ctx context.Context, args sgbucket.FeedArguments, callback sgbucket.FeedEventCallbackFunc, dbStats *expvar.Map) (*dcpFeed, error) {
traceEnter("startDCPFeed", "collection=%s, args=%+v", c, args)
// Refuse up front on a closed bucket, so no backfill work is done for a feed that can't be registered:
if c.bucket.isClosed() {
return nil, ErrBucketClosed
}
feed := &dcpFeed{
ctx: ctx,
collection: c,
metadataStore: args.MetadataStore,
args: args,
callback: callback,
}
feed.events.init()
if args.Backfill != sgbucket.FeedNoBackfill {
startCas := args.Backfill
if args.Backfill == sgbucket.FeedResume {
if args.CheckpointPrefix == "" {
return nil, fmt.Errorf("feed's Backfill is FeedResume but no CheckpointPrefix given")
}
if args.MetadataStore == nil {
return nil, fmt.Errorf("feed's Backfill is FeedResume but no MetadataStore given")
}
if err := feed.readCheckpoint(); err != nil {
return nil, fmt.Errorf("couldn't read DCP feed checkpoint: %w", err)
}
startCas = feed.lastCas + 1
}
debug("%s starting backfill from CAS 0x%x", feed, startCas)
feed.events.push(&event{opcode: sgbucket.FeedOpBeginBackfill})
err := c.enqueueBackfillEvents(startCas, args.FeedContent, &feed.events)
if err != nil {
return nil, err
}
debug("%s ended backfill", feed)
feed.events.push(&event{opcode: sgbucket.FeedOpEndBackfill})
}
if args.Dump {
feed.events.push(nil) // push an eof
} else {
// Register the feed with the collection for future notifications. Registering on a closed copy of the
// bucket would leave a feed nothing can stop: Close only stops the feeds the copy holds when it closes.
c.bucket.mutex.Lock()
if c.bucket._closed {
c.bucket.mutex.Unlock()
return nil, ErrBucketClosed
}
c.bucket.collectionFeeds[c.DataStoreNameImpl] = append(c.bucket.collectionFeeds[c.DataStoreNameImpl], feed)
c.bucket.mutex.Unlock()
}
go feed.run()
return feed, nil
}
func (c *Collection) enqueueBackfillEvents(startCas uint64, feedContent sgbucket.FeedContent, q *eventQueue) error {
needsValue := feedContent != sgbucket.FeedContentKeysOnly && feedContent != sgbucket.FeedContentXattrOnly
needsXattrs := feedContent != sgbucket.FeedContentKeysOnly && feedContent != sgbucket.FeedContentBodyOnly
sql := fmt.Sprintf(`SELECT key, %s, %s, isJSON, cas, tombstone, revSeqNo FROM documents
WHERE collection=?1 AND cas >= ?2
ORDER BY cas`,
ifelse(needsValue, `value`, `null`),
ifelse(needsXattrs, `xattrs`, `null`))
rows, err := c.db().Query(sql, c.id, startCas)
if err != nil {
return err
}
for rows.Next() {
var e event
if err := rows.Scan(&e.key, &e.value, &e.xattrs, &e.isJSON, &e.cas, &e.isDeletion, &e.revSeqNo); err != nil {
return err
}
e.opcode = ifelse(e.isDeletion, sgbucket.FeedOpDeletion, sgbucket.FeedOpMutation)
q.push(&e)
}
return rows.Close()
}
// postNewEvent pushes a new live event to all registered feeds. The full event (body + xattrs) is
// always sent; FeedContent filtering is applied consumer-side in asFeedEvent. Only backfill events
// are filtered at the SQL level in enqueueBackfillEvents.
func (c *Collection) postNewEvent(e *event) {
info("DCP: %s cas 0x%x: %q = %#.50q ---- xattrs %#q", c, e.cas, e.key, e.value, e.xattrs)
e.opcode = ifelse(e.isDeletion, sgbucket.FeedOpDeletion, sgbucket.FeedOpMutation)
c.postEvent(e)
c.bucket.expManager.scheduleExpirationAtOrBefore(e.exp)
}
func (c *Collection) postEvent(e *event) {
c.bucket.mutex.Lock()
feeds := c.bucket.collectionFeeds[c.DataStoreNameImpl]
c.bucket.mutex.Unlock()
for _, feed := range feeds {
if feed != nil {
eCopy := *e // each feed gets its own copy to avoid cross-feed event mutations and data races
feed.events.push(&eCopy)
}
}
}
// stops all feeds. Caller MUST hold the bucket's lock.
func (c *Collection) _stopFeeds() {
for _, feed := range c.bucket.collectionFeeds[c.DataStoreNameImpl] {
feed.close()
}
delete(c.bucket.collectionFeeds, c.DataStoreNameImpl)
}
//////// DCPFEED:
type eventQueue = queue[*event]
type checkpoint struct {
LastCas map[uint32]uint64 `json:"last_cas"`
}
type dcpFeed struct {
ctx context.Context // TODO: Use this
collection *Collection
metadataStore sgbucket.DataStore
args sgbucket.FeedArguments
callback sgbucket.FeedEventCallbackFunc
events eventQueue
lastCas CAS
lastCasChanged bool
// completed reports that the feed drained to its end-of-feed marker, rather than being terminated.
completed atomic.Bool
}
func (feed *dcpFeed) String() string {
return fmt.Sprintf("Feed(%s %s)", feed.collection, feed.args.ID)
}
func (feed *dcpFeed) checkpointKey() string {
return feed.args.CheckpointPrefix
}
// usesCheckpoint reports whether the feed has somewhere to keep a checkpoint.
func (feed *dcpFeed) usesCheckpoint() bool {
return feed.args.CheckpointPrefix != "" && feed.metadataStore != nil
}
// Reads the feed's lastCas from the checkpoint document, if there is one.
func (feed *dcpFeed) readCheckpoint() (err error) {
if !feed.usesCheckpoint() {
return
}
key := feed.checkpointKey()
var checkpt checkpoint
if _, err = feed.metadataStore.Get(feed.ctx, key, &checkpt); err != nil {
if _, ok := errors.AsType[sgbucket.MissingError](err); ok {
err = nil
debug("%s checkpoint %q missing", feed, key)
} else {
logError("%s failed to read lastCas from %q: %v", feed, key, err)
}
return
}
if checkpt.LastCas != nil {
colID := feed.collection.GetCollectionID()
feed.lastCas = checkpt.LastCas[colID]
}
debug("%s read lastCas 0x%x from %q", feed, feed.lastCas, key)
return
}
// Writes the feed's lastCas to the checkpoint document, if there is one.
func (feed *dcpFeed) writeCheckpoint() error {
if !feed.lastCasChanged {
return nil
}
return updateCheckpoint([]*dcpFeed{feed}, false)
}
// saveDumpCheckpoint records a dump's progress. A resumed dump whose collections all streamed to the end has
// nothing left to resume, so it removes their entries instead.
func saveDumpCheckpoint(feeds []*dcpFeed) error {
if len(feeds) == 0 {
return nil
}
remove := feeds[0].args.Backfill == sgbucket.FeedResume && allFeedsCompleted(feeds)
return updateCheckpoint(feeds, remove)
}
// updateCheckpoint writes each feed's lastCas to their shared checkpoint document in one update. With remove,
// it drops the feeds' entries instead, and deletes the document once none are left.
func updateCheckpoint(feeds []*dcpFeed, remove bool) error {
feed := feeds[0]
if !feed.usesCheckpoint() {
return nil
}
key := feed.checkpointKey()
_, err := feed.metadataStore.Update(feed.ctx, key, 0, func(current []byte) (updated []byte, expiry *uint32, del bool, err error) {
var checkpt checkpoint
if current != nil {
if err := json.Unmarshal(current, &checkpt); err != nil {
return nil, nil, false, fmt.Errorf("failed to unmarshal checkpoint: %w", err)
}
}
if checkpt.LastCas == nil {
checkpt.LastCas = make(map[uint32]uint64)
}
changed := false
for _, f := range feeds {
colID := f.collection.GetCollectionID()
if remove {
_, found := checkpt.LastCas[colID]
changed = changed || found
delete(checkpt.LastCas, colID)
} else if f.lastCasChanged {
checkpt.LastCas[colID] = f.lastCas
changed = true
}
}
if !changed {
return nil, nil, false, nil // cancels the update
}
if len(checkpt.LastCas) == 0 {
return nil, nil, true, nil
}
updated, err = json.Marshal(checkpt)
if err != nil {
return nil, nil, false, fmt.Errorf("failed to marshal checkpoint: %w", err)
}
return updated, nil, false, nil
})
if err == nil {
debug("%s updated checkpoint %q, remove=%v", feed, key, remove)
} else {
logError("%s failed to update checkpoint %q: %v", feed, key, err)
}
return err
}
func (feed *dcpFeed) run() {
atomic.AddInt32(&activeFeedCount, 1)
defer atomic.AddInt32(&activeFeedCount, -1)
if feed.args.Terminator != nil {
go func() {
<-feed.args.Terminator
debug("%s terminator closed", feed)
feed.events.close()
}()
}
if feed.args.DoneChan != nil {
defer close(feed.args.DoneChan)
}
collectionID := feed.collection.GetCollectionID()
feedContent := feed.args.FeedContent
for {
// Stop before the next event once the Terminator is closed, without waiting for the goroutine above.
if feed.terminated() {
break
}
e, ok := feed.events.pull()
if !ok {
break // terminated
}
if e == nil {
// Stored before the deferred close of DoneChan, so a waiter sees a settled value.
feed.completed.Store(true)
break
}
feedEvent, err := e.asFeedEvent(collectionID, feedContent)
if err != nil {
logError("Fatal error converting %s event to feed event: %v", feed, err)
break
}
feed.callback(*feedEvent)
if feedEvent.Cas > feed.lastCas {
feed.lastCas = feedEvent.Cas
feed.lastCasChanged = true
debug("%s lastCas = 0x%x", feed, feed.lastCas)
// TODO: Set a timer to write the checkpoint "soon"
}
}
debug("%s stopping", feed)
// A dump saves its checkpoint in StartDCPFeed, once all of its collections stop.
if !feed.args.Dump {
_ = feed.writeCheckpoint()
}
}
// terminated reports whether the feed's Terminator is closed. A feed with no Terminator is never terminated.
func (feed *dcpFeed) terminated() bool {
select {
case <-feed.args.Terminator:
return true
default:
return false
}
}
// allFeedsCompleted reports whether every feed drained to its end-of-feed marker.
func allFeedsCompleted(feeds []*dcpFeed) bool {
for _, feed := range feeds {
if !feed.completed.Load() {
return false
}
}
return true
}
func (feed *dcpFeed) close() {
feed.events.close()
}
// stop closes the feed and removes it from its collection's registered feeds, so that nothing keeps pushing
// events to it. Must not be called with the bucket's lock held.
func (feed *dcpFeed) stop() {
feed.close()
c := feed.collection
c.bucket.mutex.Lock()
defer c.bucket.mutex.Unlock()
feeds := c.bucket.collectionFeeds[c.DataStoreNameImpl]
// A new slice, rather than deleting in place: postEvent iterates the old one without the lock.
remaining := make([]*dcpFeed, 0, len(feeds))
for _, f := range feeds {
if f != feed {
remaining = append(remaining, f)
}
}
if len(remaining) == 0 {
delete(c.bucket.collectionFeeds, c.DataStoreNameImpl)
} else {
c.bucket.collectionFeeds[c.DataStoreNameImpl] = remaining
}
}
//////// EVENTS
type event struct {
opcode sgbucket.FeedOpcode // FeedOpMutation, FeedOpDeletion, or sentinel opcodes
key string // Doc ID
value []byte // Raw data content, or nil if deleted
isDeletion bool // True if it's a deletion event (used for SQL scan)
isJSON bool // Is the data a JSON document?
xattrs []byte // Extended attributes (JSON-encoded)
cas CAS // Sequence in collection
exp Exp // Expiration time
revSeqNo uint64 // Revision sequence number
}
func (e *event) asFeedEvent(collectionID uint32, feedContent sgbucket.FeedContent) (*sgbucket.FeedEvent, error) {
// Sentinel events (backfill markers) have no document data
if e.opcode == sgbucket.FeedOpBeginBackfill || e.opcode == sgbucket.FeedOpEndBackfill {
return &sgbucket.FeedEvent{Opcode: e.opcode}, nil
}
if e.exp != absoluteExpiry(e.exp) {
panic(fmt.Sprintf("expiry %d isn't absolute", e.exp)) // caller forgot absoluteExpiry()
}
if e.revSeqNo == 0 {
panic("event missing revSeqNo")
}
feedEvent := sgbucket.FeedEvent{
Opcode: e.opcode,
CollectionID: collectionID,
Key: []byte(e.key),
Cas: e.cas,
Expiry: e.exp,
DataType: ifelse(e.isJSON, sgbucket.FeedDataTypeJSON, sgbucket.FeedDataTypeRaw),
RevNo: e.revSeqNo,
TimeReceived: time.Now(),
}
switch feedContent {
case sgbucket.FeedContentKeysOnly:
// No value or xattrs needed
case sgbucket.FeedContentBodyOnly:
feedEvent.Value = e.value
case sgbucket.FeedContentXattrOnly:
if len(e.xattrs) > 0 {
xattrs, err := e.parseXattrs()
if err != nil {
return nil, fmt.Errorf("couldn't parse xattrs for key %q: %w", e.key, err)
}
feedEvent.Value = sgbucket.EncodeValueWithXattrs(nil, xattrs...)
feedEvent.DataType |= sgbucket.FeedDataTypeXattr
}
default: // FeedContentDefault
if len(e.xattrs) > 0 {
xattrs, err := e.parseXattrs()
if err != nil {
return nil, fmt.Errorf("couldn't parse xattrs for key %q: %w", e.key, err)
}
feedEvent.Value = sgbucket.EncodeValueWithXattrs(e.value, xattrs...)
feedEvent.DataType |= sgbucket.FeedDataTypeXattr
} else {
feedEvent.Value = e.value
}
}
return &feedEvent, nil
}
// parseXattrs decodes the JSON-encoded xattrs into sgbucket.Xattr slice.
func (e *event) parseXattrs() ([]sgbucket.Xattr, error) {
var xattrMap map[string]json.RawMessage
if err := json.Unmarshal(e.xattrs, &xattrMap); err != nil {
return nil, err
}
xattrs := make([]sgbucket.Xattr, 0, len(xattrMap))
for k, v := range xattrMap {
xattrs = append(xattrs, sgbucket.Xattr{Name: k, Value: v})
}
return xattrs, nil
}