-
Notifications
You must be signed in to change notification settings - Fork 245
/
spanner.go
228 lines (189 loc) · 6.73 KB
/
spanner.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
package spanner
import (
"context"
"fmt"
"os"
"regexp"
"strconv"
"time"
"cloud.google.com/go/spanner"
sq "github.com/Masterminds/squirrel"
"go.opentelemetry.io/otel"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"github.com/authzed/spicedb/internal/datastore/common"
"github.com/authzed/spicedb/internal/datastore/common/revisions"
"github.com/authzed/spicedb/internal/datastore/spanner/migrations"
log "github.com/authzed/spicedb/internal/logging"
"github.com/authzed/spicedb/pkg/datastore"
"github.com/authzed/spicedb/pkg/datastore/revision"
core "github.com/authzed/spicedb/pkg/proto/core/v1"
)
func init() {
datastore.Engines = append(datastore.Engines, Engine)
}
const (
Engine = "spanner"
errUnableToInstantiate = "unable to instantiate spanner client: %w"
errRevision = "unable to load revision: %w"
errUnableToWriteRelationships = "unable to write relationships: %w"
errUnableToDeleteRelationships = "unable to delete relationships: %w"
errUnableToWriteConfig = "unable to write namespace config: %w"
errUnableToReadConfig = "unable to read namespace config: %w"
errUnableToDeleteConfig = "unable to delete namespace config: %w"
errUnableToListNamespaces = "unable to list namespaces: %w"
errUnableToReadCaveat = "unable to read caveat: %w"
errUnableToWriteCaveat = "unable to write caveat: %w"
errUnableToListCaveats = "unable to list caveats: %w"
errUnableToDeleteCaveat = "unable to delete caveat: %w"
// Spanner requires a much smaller userset batch size than other datastores because of the
// limitation on the maximum number of function calls.
// https://cloud.google.com/spanner/quotas
// We can't share a default or config option with other datastore implementations.
usersetBatchsize = 100
)
var (
sql = sq.StatementBuilder.PlaceholderFormat(sq.AtP)
tracer = otel.Tracer("spicedb/internal/datastore/spanner")
alreadyExistsRegex = regexp.MustCompile(`^Table relation_tuple: Row {String\("([^\"]+)"\), String\("([^\"]+)"\), String\("([^\"]+)"\), String\("([^\"]+)"\), String\("([^\"]+)"\), String\("([^\"]+)"\)} already exists.$`)
)
type spannerDatastore struct {
*revisions.RemoteClockRevisions
revision.DecimalDecoder
client *spanner.Client
config spannerOptions
stopGC context.CancelFunc
}
// NewSpannerDatastore returns a datastore backed by cloud spanner
func NewSpannerDatastore(database string, opts ...Option) (datastore.Datastore, error) {
config, err := generateConfig(opts)
if err != nil {
return nil, fmt.Errorf(errUnableToInstantiate, err)
}
if len(config.emulatorHost) > 0 {
os.Setenv("SPANNER_EMULATOR_HOST", config.emulatorHost)
}
if len(os.Getenv("SPANNER_EMULATOR_HOST")) > 0 {
log.Info().Str("spanner-emulator-host", os.Getenv("SPANNER_EMULATOR_HOST")).Msg("running against spanner emulator")
}
config.gcInterval = common.WithJitter(0.2, config.gcInterval)
log.Info().Float64("factor", 0.2).Msg("gc configured with jitter")
client, err := spanner.NewClient(context.Background(), database, option.WithCredentialsFile(config.credentialsFilePath))
if err != nil {
return nil, fmt.Errorf(errUnableToInstantiate, err)
}
maxRevisionStaleness := time.Duration(float64(config.revisionQuantization.Nanoseconds())*
config.maxRevisionStalenessPercent) * time.Nanosecond
ds := spannerDatastore{
RemoteClockRevisions: revisions.NewRemoteClockRevisions(
config.gcWindow,
maxRevisionStaleness,
config.followerReadDelay,
config.revisionQuantization,
),
client: client,
config: config,
}
ds.RemoteClockRevisions.SetNowFunc(ds.headRevisionInternal)
if config.gcInterval > 0*time.Minute && config.gcEnabled {
ctx, cancel := context.WithCancel(context.Background())
if err := ds.runGC(ctx); err != nil {
cancel()
return nil, fmt.Errorf(errUnableToInstantiate, err)
}
ds.stopGC = cancel
} else {
log.Warn().Msg("datastore background garbage collection disabled")
}
return ds, nil
}
func (sd spannerDatastore) SnapshotReader(revisionRaw datastore.Revision) datastore.Reader {
revision := revisionRaw.(revision.Decimal)
txSource := func() readTX {
return sd.client.Single().WithTimestampBound(spanner.ReadTimestamp(timestampFromRevision(revision)))
}
querySplitter := common.TupleQuerySplitter{
Executor: queryExecutor(txSource),
UsersetBatchSize: usersetBatchsize,
}
return spannerReader{querySplitter, txSource}
}
func (sd spannerDatastore) ReadWriteTx(
ctx context.Context,
fn datastore.TxUserFunc,
) (datastore.Revision, error) {
ts, err := sd.client.ReadWriteTransaction(ctx, func(ctx context.Context, spannerRWT *spanner.ReadWriteTransaction) error {
txSource := func() readTX {
return spannerRWT
}
querySplitter := common.TupleQuerySplitter{
Executor: queryExecutor(txSource),
UsersetBatchSize: usersetBatchsize,
}
rwt := spannerReadWriteTXN{spannerReader{querySplitter, txSource}, spannerRWT}
return fn(rwt)
})
if err != nil {
if cerr := convertToWriteConstraintError(err); cerr != nil {
return datastore.NoRevision, cerr
}
return datastore.NoRevision, err
}
return revisionFromTimestamp(ts), nil
}
func (sd spannerDatastore) IsReady(ctx context.Context) (bool, error) {
headMigration, err := migrations.SpannerMigrations.HeadRevision()
if err != nil {
return false, fmt.Errorf("invalid head migration found for postgres: %w", err)
}
currentRevision, err := migrations.NewSpannerDriver(sd.client.DatabaseName(), sd.config.credentialsFilePath, sd.config.emulatorHost)
if err != nil {
return false, err
}
defer currentRevision.Close(ctx)
version, err := currentRevision.Version(ctx)
if err != nil {
return false, err
}
return version == headMigration, nil
}
func (sd spannerDatastore) Features(ctx context.Context) (*datastore.Features, error) {
return &datastore.Features{Watch: datastore.Feature{Enabled: true}}, nil
}
func (sd spannerDatastore) Close() error {
sd.stopGC()
sd.client.Close()
return nil
}
func statementFromSQL(sql string, args []interface{}) spanner.Statement {
params := make(map[string]interface{}, len(args))
for index, arg := range args {
params["p"+strconv.Itoa(index+1)] = arg
}
return spanner.Statement{
SQL: sql,
Params: params,
}
}
func convertToWriteConstraintError(err error) error {
if spanner.ErrCode(err) == codes.AlreadyExists {
description := spanner.ErrDesc(err)
found := alreadyExistsRegex.FindStringSubmatch(description)
if found != nil {
return common.NewCreateRelationshipExistsError(&core.RelationTuple{
ResourceAndRelation: &core.ObjectAndRelation{
Namespace: found[1],
ObjectId: found[2],
Relation: found[3],
},
Subject: &core.ObjectAndRelation{
Namespace: found[4],
ObjectId: found[5],
Relation: found[6],
},
})
}
return common.NewCreateRelationshipExistsError(nil)
}
return nil
}