-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcollection_watcher.go
More file actions
188 lines (160 loc) · 4.96 KB
/
collection_watcher.go
File metadata and controls
188 lines (160 loc) · 4.96 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
package mongo_watcher
import (
"context"
"github.com/techpro-studio/gomongo"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
"log"
"time"
)
type MongoSchema[T any] interface {
GetId() bson.ObjectID
gomongo.ModelConverted[T]
}
type MongoEvent string
const MongoEventInsert MongoEvent = "insert"
const MongoEventUpdate MongoEvent = "update"
const MongoEventDelete MongoEvent = "delete"
const MongoEventReplace MongoEvent = "replace"
type Event[T any] struct {
Type MongoEvent
FullDocument *T
FullDocumentBeforeChange *T
Key string
}
type EventHandler[T any] interface {
Setup(ctx context.Context, collection *mongo.Collection)
HandleEvent(ctx context.Context, event *Event[T]) error
}
type eventHandlerFunction[T any] func(ctx context.Context, event *Event[T]) error
func FunctionEventHandler[T any](function func(ctx context.Context, event *Event[T]) error) EventHandler[T] {
return eventHandlerFunction[T](function)
}
func (s eventHandlerFunction[T]) Setup(ctx context.Context, collection *mongo.Collection) {}
func (s eventHandlerFunction[T]) HandleEvent(ctx context.Context, event *Event[T]) error {
return s(ctx, event)
}
type CollectionWatcher[T any, M MongoSchema[T]] struct {
collection *mongo.Collection
eventHandlers []EventHandler[T]
allowedEvents []MongoEvent
}
func NewCollectionWatcher[T any, M MongoSchema[T]](
collection *mongo.Collection,
eventHandlers []EventHandler[T],
allowedEvents []MongoEvent,
) *CollectionWatcher[T, M] {
if len(allowedEvents) == 0 {
allowedEvents = []MongoEvent{MongoEventUpdate, MongoEventReplace, MongoEventInsert, MongoEventDelete}
}
for _, handler := range eventHandlers {
handler.Setup(context.Background(), collection)
}
return &CollectionWatcher[T, M]{
collection: collection,
eventHandlers: eventHandlers,
allowedEvents: allowedEvents,
}
}
func (c *CollectionWatcher[T, M]) Watch(ctx context.Context) {
var resumeToken bson.Raw
pipeline := mongo.Pipeline{
{{"$match", bson.D{
{"operationType", bson.D{{"$in", c.allowedEvents}}},
}}},
}
for {
select {
case <-ctx.Done():
log.Printf("Watcher for %s stopping: context cancelled", c.collection.Name())
return
default:
}
err := c.runStream(ctx, pipeline, &resumeToken)
if err != nil {
log.Printf("Change stream error on %s: %v", c.collection.Name(), err)
}
// If context was cancelled, stop retrying
if ctx.Err() != nil {
log.Printf("Watcher for %s stopping: context cancelled", c.collection.Name())
return
}
log.Printf("Reconnecting watcher for %s in 3s...", c.collection.Name())
select {
case <-ctx.Done():
return
case <-time.After(3 * time.Second):
}
}
}
func (c *CollectionWatcher[T, M]) runStream(ctx context.Context, pipeline mongo.Pipeline, resumeToken *bson.Raw) error {
opts := options.ChangeStream().
SetFullDocument(options.UpdateLookup).
SetFullDocumentBeforeChange(options.WhenAvailable)
// Resume from where we left off if we have a token
if *resumeToken != nil {
opts.SetResumeAfter(*resumeToken)
}
changeStream, err := c.collection.Watch(ctx, pipeline, opts)
if err != nil {
return err
}
defer func() {
closeCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if cerr := changeStream.Close(closeCtx); cerr != nil {
log.Printf("Error closing change stream: %v\n", cerr)
}
}()
log.Printf("Watching %s (resuming: %v)", c.collection.Name(), *resumeToken != nil)
for changeStream.Next(ctx) {
*resumeToken = changeStream.ResumeToken()
var raw struct {
FullDocument M `bson:"fullDocument"`
FullDocumentBeforeChange *M `bson:"fullDocumentBeforeChange"`
Type string `bson:"operationType"`
DocumentKey struct {
ID bson.ObjectID `bson:"_id"`
} `bson:"documentKey"`
}
if err := changeStream.Decode(&raw); err != nil {
log.Printf("error decoding change stream: %v\n", err)
continue
}
event := c.buildEvent(raw.Type, raw.DocumentKey.ID.Hex(), raw.FullDocument, raw.FullDocumentBeforeChange)
if event == nil {
continue
}
for _, handler := range c.eventHandlers {
if err := handler.HandleEvent(ctx, event); err != nil {
log.Printf("Error handling event: %v\n", err)
}
}
}
return changeStream.Err()
}
func (c *CollectionWatcher[T, M]) buildEvent(opType string, key string, doc M, beforeDoc *M) *Event[T] {
switch MongoEvent(opType) {
case MongoEventInsert, MongoEventUpdate, MongoEventReplace:
data := *doc.ToModel()
var before *T
if beforeDoc != nil {
before = (*beforeDoc).ToModel()
}
return &Event[T]{
Type: MongoEvent(opType),
FullDocument: &data,
FullDocumentBeforeChange: before,
Key: key,
}
case MongoEventDelete:
return &Event[T]{
Type: MongoEventDelete,
Key: key,
}
default:
log.Printf("Unhandled operationType: %s", opType)
return nil
}
}