-
Notifications
You must be signed in to change notification settings - Fork 246
/
watch.go
361 lines (304 loc) · 10.1 KB
/
watch.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
package crdb
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/authzed/spicedb/internal/datastore/common"
"github.com/authzed/spicedb/internal/datastore/crdb/pool"
pgxcommon "github.com/authzed/spicedb/internal/datastore/postgres/common"
"github.com/authzed/spicedb/internal/datastore/revisions"
"github.com/authzed/spicedb/pkg/datastore"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
"github.com/authzed/spicedb/pkg/spiceerrors"
)
const (
queryChangefeed = "EXPERIMENTAL CHANGEFEED FOR %s WITH updated, cursor = '%s', resolved = '%s', min_checkpoint_frequency = '0';"
queryChangefeedPreV22 = "EXPERIMENTAL CHANGEFEED FOR %s WITH updated, cursor = '%s', resolved = '%s';"
)
var retryHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: "spicedb",
Subsystem: "datastore",
Name: "crdb_watch_retries",
Help: "watch retry distribution",
Buckets: []float64{0, 1, 2, 5, 10, 20, 50},
})
func init() {
prometheus.MustRegister(retryHistogram)
}
type changeDetails struct {
Resolved string
Updated string
After *struct {
Namespace string `json:"namespace"`
SerializedNamespaceConfig string `json:"serialized_config"`
CaveatName string `json:"name"`
SerializedCaveatDefinition string `json:"definition"`
RelationshipCaveatContext map[string]any `json:"caveat_context"`
RelationshipCaveatName string `json:"caveat_name"`
}
}
func (cds *crdbDatastore) Watch(ctx context.Context, afterRevision datastore.Revision, options datastore.WatchOptions) (<-chan *datastore.RevisionChanges, <-chan error) {
watchBufferLength := options.WatchBufferLength
if watchBufferLength <= 0 {
watchBufferLength = cds.watchBufferLength
}
updates := make(chan *datastore.RevisionChanges, watchBufferLength)
errs := make(chan error, 1)
features, err := cds.Features(ctx)
if err != nil {
errs <- err
return updates, errs
}
if !features.Watch.Enabled {
errs <- datastore.NewWatchDisabledErr(fmt.Sprintf("%s. See https://spicedb.dev/d/enable-watch-api-crdb", features.Watch.Reason))
return updates, errs
}
go cds.watch(ctx, afterRevision, options, updates, errs)
return updates, errs
}
func (cds *crdbDatastore) watch(
ctx context.Context,
afterRevision datastore.Revision,
opts datastore.WatchOptions,
updates chan *datastore.RevisionChanges,
errs chan error,
) {
defer close(updates)
defer close(errs)
// get non-pooled connection for watch
// "applications should explicitly create dedicated connections to consume
// changefeed data, instead of using a connection pool as most client
// drivers do by default."
// see: https://www.cockroachlabs.com/docs/v22.2/changefeed-for#considerations
conn, err := pgxcommon.ConnectWithInstrumentation(ctx, cds.dburl)
if err != nil {
errs <- err
return
}
defer func() { _ = conn.Close(ctx) }()
tableNames := make([]string, 0, 3)
if opts.Content&datastore.WatchRelationships == datastore.WatchRelationships {
tableNames = append(tableNames, tableTuple)
}
if opts.Content&datastore.WatchSchema == datastore.WatchSchema {
tableNames = append(tableNames, tableNamespace)
tableNames = append(tableNames, tableCaveat)
}
if len(tableNames) == 0 {
errs <- fmt.Errorf("at least relationships or schema must be specified")
return
}
if opts.CheckpointInterval < 0 {
errs <- fmt.Errorf("invalid checkpoint interval given")
return
}
// Default: 1s
resolvedDuration := 1 * time.Second
if opts.CheckpointInterval > 0 {
resolvedDuration = opts.CheckpointInterval
}
resolvedDurationString := strconv.FormatInt(resolvedDuration.Milliseconds(), 10) + "ms"
interpolated := fmt.Sprintf(cds.beginChangefeedQuery, strings.Join(tableNames, ","), afterRevision, resolvedDurationString)
sendError := func(err error) {
if errors.Is(ctx.Err(), context.Canceled) {
errs <- datastore.NewWatchCanceledErr()
return
}
if pool.IsResettableError(ctx, err) || pool.IsRetryableError(ctx, err) {
errs <- datastore.NewWatchTemporaryErr(err)
return
}
errs <- err
}
watchBufferWriteTimeout := opts.WatchBufferWriteTimeout
if watchBufferWriteTimeout <= 0 {
watchBufferWriteTimeout = cds.watchBufferWriteTimeout
}
sendChange := func(change *datastore.RevisionChanges) bool {
select {
case updates <- change:
return true
default:
// If we cannot immediately write, setup the timer and try again.
}
timer := time.NewTimer(watchBufferWriteTimeout)
defer timer.Stop()
select {
case updates <- change:
return true
case <-timer.C:
errs <- datastore.NewWatchDisconnectedErr()
return false
}
}
changes, err := conn.Query(ctx, interpolated)
if err != nil {
sendError(err)
return
}
// We call Close async here because it can be slow and blocks closing the channels. There is
// no return value so we're not really losing anything.
defer func() { go changes.Close() }()
tracked := common.NewChanges(revisions.HLCKeyFunc, opts.Content)
for changes.Next() {
var tableNameBytes []byte
var changeJSON []byte
var primaryKeyValuesJSON []byte
// Pull in the table name, the primary key(s) and change information.
if err := changes.Scan(&tableNameBytes, &primaryKeyValuesJSON, &changeJSON); err != nil {
sendError(err)
return
}
var details changeDetails
if err := json.Unmarshal(changeJSON, &details); err != nil {
sendError(err)
return
}
// Resolved indicates that the specified revision is "complete"; no additional updates can come in before or at it.
// Therefore, at this point, we issue tracked updates from before that time, and the checkpoint update.
if details.Resolved != "" {
rev, err := revisions.HLCRevisionFromString(details.Resolved)
if err != nil {
sendError(fmt.Errorf("malformed resolved timestamp: %w", err))
return
}
for _, revChange := range tracked.FilterAndRemoveRevisionChanges(revisions.HLCKeyLessThanFunc, rev) {
revChange := revChange
if !sendChange(&revChange) {
return
}
}
if opts.Content&datastore.WatchCheckpoints == datastore.WatchCheckpoints {
if !sendChange(&datastore.RevisionChanges{
Revision: rev,
IsCheckpoint: true,
}) {
return
}
}
continue
}
// Otherwise, this a notification of a row change.
tableName := string(tableNameBytes)
var pkValues []string
if err := json.Unmarshal(primaryKeyValuesJSON, &pkValues); err != nil {
sendError(err)
return
}
switch tableName {
case tableTuple:
var caveatName string
var caveatContext map[string]any
if details.After != nil && details.After.RelationshipCaveatName != "" {
caveatName = details.After.RelationshipCaveatName
caveatContext = details.After.RelationshipCaveatContext
}
ctxCaveat, err := common.ContextualizedCaveatFrom(caveatName, caveatContext)
if err != nil {
sendError(err)
return
}
tuple := &core.RelationTuple{
ResourceAndRelation: &core.ObjectAndRelation{
Namespace: pkValues[0],
ObjectId: pkValues[1],
Relation: pkValues[2],
},
Subject: &core.ObjectAndRelation{
Namespace: pkValues[3],
ObjectId: pkValues[4],
Relation: pkValues[5],
},
Caveat: ctxCaveat,
}
rev, err := revisions.HLCRevisionFromString(details.Updated)
if err != nil {
sendError(fmt.Errorf("malformed update timestamp: %w", err))
return
}
if details.After == nil {
if err := tracked.AddRelationshipChange(ctx, rev, tuple, core.RelationTupleUpdate_DELETE); err != nil {
sendError(err)
return
}
} else {
if err := tracked.AddRelationshipChange(ctx, rev, tuple, core.RelationTupleUpdate_TOUCH); err != nil {
sendError(err)
return
}
}
case tableNamespace:
if len(pkValues) != 1 {
sendError(spiceerrors.MustBugf("expected a single definition name for the primary key in change feed. found: %s", string(primaryKeyValuesJSON)))
return
}
definitionName := pkValues[0]
rev, err := revisions.HLCRevisionFromString(details.Updated)
if err != nil {
sendError(fmt.Errorf("malformed update timestamp: %w", err))
return
}
if details.After != nil && details.After.SerializedNamespaceConfig != "" {
namespaceDef := &core.NamespaceDefinition{}
defBytes, err := hex.DecodeString(details.After.SerializedNamespaceConfig[2:]) // drop the \x
if err != nil {
sendError(fmt.Errorf("could not decode namespace definition: %w", err))
return
}
if err := namespaceDef.UnmarshalVT(defBytes); err != nil {
sendError(fmt.Errorf("could not unmarshal namespace definition: %w", err))
return
}
tracked.AddChangedDefinition(ctx, rev, namespaceDef)
} else {
tracked.AddDeletedNamespace(ctx, rev, definitionName)
}
case tableCaveat:
if len(pkValues) != 1 {
sendError(spiceerrors.MustBugf("expected a single definition name for the primary key in change feed. found: %s", string(primaryKeyValuesJSON)))
return
}
definitionName := pkValues[0]
rev, err := revisions.HLCRevisionFromString(details.Updated)
if err != nil {
sendError(fmt.Errorf("malformed update timestamp: %w", err))
return
}
if details.After != nil && details.After.SerializedCaveatDefinition != "" {
caveatDef := &core.CaveatDefinition{}
defBytes, err := hex.DecodeString(details.After.SerializedCaveatDefinition[2:]) // drop the \x
if err != nil {
sendError(fmt.Errorf("could not decode caveat definition: %w", err))
return
}
if err := caveatDef.UnmarshalVT(defBytes); err != nil {
sendError(fmt.Errorf("could not unmarshal caveat definition: %w", err))
return
}
tracked.AddChangedDefinition(ctx, rev, caveatDef)
} else {
tracked.AddDeletedCaveat(ctx, rev, definitionName)
}
}
}
if changes.Err() != nil {
if errors.Is(ctx.Err(), context.Canceled) {
closeCtx, closeCancel := context.WithTimeout(context.Background(), 5*time.Second)
defer closeCancel()
if err := conn.Close(closeCtx); err != nil {
errs <- err
return
}
errs <- datastore.NewWatchCanceledErr()
} else {
errs <- changes.Err()
}
return
}
}