| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package gcpfirestore provides a docstore implementation backed by Google Cloud |
| 16 |
// Firestore. |
| 17 |
// Use OpenCollection to construct a *docstore.Collection. |
| 18 |
// |
| 19 |
// Docstore types not supported by the Go firestore client, cloud.google.com/go/firestore: |
| 20 |
// - unsigned integers: encoded is int64s |
| 21 |
// - arrays: encoded as Firestore array values |
| 22 |
// |
| 23 |
// Firestore types not supported by Docstore: |
| 24 |
// - Document reference (a pointer to another Firestore document) |
| 25 |
// |
| 26 |
// # URLs |
| 27 |
// |
| 28 |
// For docstore.OpenCollection, gcpfirestore registers for the scheme |
| 29 |
// "firestore". |
| 30 |
// The default URL opener will create a connection using default credentials |
| 31 |
// from the environment, as described in |
| 32 |
// https://cloud.google.com/docs/authentication/production. |
| 33 |
// To customize the URL opener, or for more details on the URL format, |
| 34 |
// see URLOpener. |
| 35 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 36 |
// |
| 37 |
// # As |
| 38 |
// |
| 39 |
// gcpfirestore exposes the following types for as functions. |
| 40 |
// The pb package is google.golang.org/genproto/googleapis/firestore/v1. |
| 41 |
// The firestore package is cloud.google.com/go/firestore/apiv1. |
| 42 |
// - Collection.As: *firestore.Client |
| 43 |
// - ActionList.BeforeDo: *pb.BatchGetDocumentsRequest or *pb.CommitRequest. |
| 44 |
// - Query.BeforeQuery: *pb.RunQueryRequest |
| 45 |
// - DocumentIterator: firestore.Firestore_RunQueryClient |
| 46 |
// - Error: *google.golang.org/grpc/status.Status |
| 47 |
// |
| 48 |
// # Queries |
| 49 |
// |
| 50 |
// Firestore allows only one field in a query to be compared with an inequality |
| 51 |
// operator (one other than "="). This driver selects the first field in a Where |
| 52 |
// clause with an inequality to pass to Firestore and handles the rest locally. For |
| 53 |
// example, if the query specifies the three clauses A > 1, B > 2 and A < 3, then |
| 54 |
// A > 1 and A < 3 will be sent to Firestore, and the results will be filtered by |
| 55 |
// B > 2 in this driver. |
| 56 |
// |
| 57 |
// Firestore requires a composite index if a query contains both an equality and an |
| 58 |
// inequality comparison. This driver returns an error if the necessary index does |
| 59 |
// not exist. You must create the index manually. See |
| 60 |
// https://cloud.google.com/firestore/docs/query-data/indexing for details. |
| 61 |
// |
| 62 |
// See https://cloud.google.com/firestore/docs/query-data/queries for more information on Firestore queries. |
| 63 |
package gcpfirestore // import "gocloud.dev/docstore/gcpfirestore" |
| 64 |
|
| 65 |
import ( |
| 66 |
"bytes" |
| 67 |
"context" |
| 68 |
"fmt" |
| 69 |
"io" |
| 70 |
"os" |
| 71 |
"reflect" |
| 72 |
"regexp" |
| 73 |
"strings" |
| 74 |
|
| 75 |
vkit "cloud.google.com/go/firestore/apiv1" |
| 76 |
pb "cloud.google.com/go/firestore/apiv1/firestorepb" |
| 77 |
"github.com/google/wire" |
| 78 |
"gocloud.dev/docstore" |
| 79 |
"gocloud.dev/docstore/driver" |
| 80 |
"gocloud.dev/gcerrors" |
| 81 |
"gocloud.dev/gcp" |
| 82 |
"gocloud.dev/internal/gcerr" |
| 83 |
"gocloud.dev/internal/useragent" |
| 84 |
"google.golang.org/api/option" |
| 85 |
"google.golang.org/grpc" |
| 86 |
"google.golang.org/grpc/credentials/insecure" |
| 87 |
"google.golang.org/grpc/metadata" |
| 88 |
"google.golang.org/grpc/status" |
| 89 |
"google.golang.org/protobuf/proto" |
| 90 |
tspb "google.golang.org/protobuf/types/known/timestamppb" |
| 91 |
) |
| 92 |
|
| 93 |
// Dial returns a client to use with Firestore and a clean-up function to close |
| 94 |
// the client after used. |
| 95 |
// If the 'FIRESTORE_EMULATOR_HOST' environment variable is set the client connects |
| 96 |
// to the GCP firestore emulator by overriding the default endpoint. |
| 97 |
func Dial(ctx context.Context, ts gcp.TokenSource) (*vkit.Client, func(), error) { |
| 98 |
opts := []option.ClientOption{ |
| 99 |
useragent.ClientOption("docstore"), |
| 100 |
} |
| 101 |
if host := os.Getenv("FIRESTORE_EMULATOR_HOST"); host != "" { |
| 102 |
conn, err := grpc.DialContext(ctx, host, |
| 103 |
grpc.WithTransportCredentials(insecure.NewCredentials())) |
| 104 |
if err != nil { |
| 105 |
return nil, nil, err |
| 106 |
} |
| 107 |
opts = append(opts, |
| 108 |
option.WithEndpoint(host), |
| 109 |
option.WithGRPCConn(conn), |
| 110 |
) |
| 111 |
} else { |
| 112 |
opts = append(opts, option.WithTokenSource(ts)) |
| 113 |
} |
| 114 |
c, err := vkit.NewClient(ctx, opts...) |
| 115 |
return c, func() { c.Close() }, err |
| 116 |
} |
| 117 |
|
| 118 |
// Set holds Wire providers for this package. |
| 119 |
var Set = wire.NewSet( |
| 120 |
Dial, |
| 121 |
wire.Struct(new(URLOpener), "Client"), |
| 122 |
) |
| 123 |
|
| 124 |
type collection struct { |
| 125 |
nameField string |
| 126 |
nameFunc func(docstore.Document) string |
| 127 |
client *vkit.Client |
| 128 |
dbPath string // e.g. "projects/P/databases/(default)" |
| 129 |
collPath string // e.g. "projects/P/databases/(default)/documents/States/Wisconsin/cities" |
| 130 |
opts *Options |
| 131 |
} |
| 132 |
|
| 133 |
// Options contains optional arguments to the OpenCollection functions. |
| 134 |
type Options struct { |
| 135 |
// If true, allow queries that require client-side evaluation of filters (Where clauses) |
| 136 |
// to run. |
| 137 |
AllowLocalFilters bool |
| 138 |
// The name of the field holding the document revision. |
| 139 |
// Defaults to docstore.DefaultRevisionField. |
| 140 |
RevisionField string |
| 141 |
|
| 142 |
// The maximum number of RPCs that can be in progress for a single call to |
| 143 |
// ActionList.Do. |
| 144 |
// If less than 1, there is no limit. |
| 145 |
MaxOutstandingActionRPCs int |
| 146 |
} |
| 147 |
|
| 148 |
// CollectionResourceID constructs a resource ID for a collection from the project ID and the collection path. |
| 149 |
// See the OpenCollection example for use. |
| 150 |
func CollectionResourceID(projectID, collPath string) string { |
| 151 |
return fmt.Sprintf("projects/%s/databases/(default)/documents/%s", projectID, collPath) |
| 152 |
} |
| 153 |
|
| 154 |
// CollectResoureceIDWithDatabase constructs a resource ID for a collection from the project ID, database ID, and the collection path. |
| 155 |
// See the OpenCollection example for use. |
| 156 |
func CollectionResourceIDWithDatabase(projectID, databaseID, collPath string) string { |
| 157 |
return fmt.Sprintf("projects/%s/databases/%s/documents/%s", projectID, databaseID, collPath) |
| 158 |
} |
| 159 |
|
| 160 |
// OpenCollection creates a *docstore.Collection representing a Firestore collection. |
| 161 |
// |
| 162 |
// collResourceID must be of the form "project/<projectID>/databases/(default)/documents/<collPath>". |
| 163 |
// <collPath> may be a top-level collection, like "States", or it may be a path to a nested |
| 164 |
// collection, like "States/Wisconsin/Cities". |
| 165 |
// See https://cloud.google.com/firestore/docs/reference/rest/ for more detail. |
| 166 |
// |
| 167 |
// gcpfirestore requires that a single field, nameField, be designated the primary |
| 168 |
// key. Its values must be strings, and must be unique over all documents in the |
| 169 |
// collection. The primary key must be provided to retrieve a document. |
| 170 |
func OpenCollection(client *vkit.Client, collResourceID, nameField string, opts *Options) (*docstore.Collection, error) { |
| 171 |
c, err := newCollection(client, collResourceID, nameField, nil, opts) |
| 172 |
if err != nil { |
| 173 |
return nil, err |
| 174 |
} |
| 175 |
return docstore.NewCollection(c), nil |
| 176 |
} |
| 177 |
|
| 178 |
// OpenCollectionWithNameFunc creates a *docstore.Collection representing a Firestore collection. |
| 179 |
// |
| 180 |
// collResourceID must be of the form "project/<projectID>/databases/(default)/documents/<collPath>". |
| 181 |
// <collPath> may be a top-level collection, like "States", or it may be a path to a nested |
| 182 |
// collection, like "States/Wisconsin/Cities". |
| 183 |
// |
| 184 |
// The nameFunc argument is function that accepts a document and returns the value to |
| 185 |
// be used for the document's primary key. It should return the empty string if the |
| 186 |
// document is missing the information to construct a name. This will cause all |
| 187 |
// actions, even Create, to fail. |
| 188 |
// |
| 189 |
// Providing a function to construct the primary key is useful in two situations: if |
| 190 |
// your desired primary key field is not a string, or if there is more than one field |
| 191 |
// you want to use as a primary key. |
| 192 |
// |
| 193 |
// For the collection to be usable with Query.Delete and Query.Update, nameFunc |
| 194 |
// must work with both map and struct types representing the same underlying |
| 195 |
// data structure. See gocloud.dev/docstore/drivertest.HighScoreKey for an example. |
| 196 |
func OpenCollectionWithNameFunc(client *vkit.Client, collResourceID string, nameFunc func(docstore.Document) string, opts *Options) (*docstore.Collection, error) { |
| 197 |
c, err := newCollection(client, collResourceID, "", nameFunc, opts) |
| 198 |
if err != nil { |
| 199 |
return nil, err |
| 200 |
} |
| 201 |
return docstore.NewCollection(c), nil |
| 202 |
} |
| 203 |
|
| 204 |
var resourceIDRE = regexp.MustCompile(`^(projects/[^/]+/databases/[^/]+)/documents/.+`) |
| 205 |
|
| 206 |
func newCollection(client *vkit.Client, collResourceID, nameField string, nameFunc func(docstore.Document) string, opts *Options) (*collection, error) { |
| 207 |
if nameField == "" && nameFunc == nil { |
| 208 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "one of nameField or nameFunc must be provided") |
| 209 |
} |
| 210 |
matches := resourceIDRE.FindStringSubmatch(collResourceID) |
| 211 |
if matches == nil { |
| 212 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "bad collection resource ID %q; must match %v", |
| 213 |
collResourceID, resourceIDRE) |
| 214 |
} |
| 215 |
dbPath := matches[1] |
| 216 |
if opts == nil { |
| 217 |
opts = &Options{} |
| 218 |
} |
| 219 |
if opts.RevisionField == "" { |
| 220 |
opts.RevisionField = docstore.DefaultRevisionField |
| 221 |
} |
| 222 |
return &collection{ |
| 223 |
client: client, |
| 224 |
nameField: nameField, |
| 225 |
nameFunc: nameFunc, |
| 226 |
dbPath: dbPath, |
| 227 |
collPath: collResourceID, |
| 228 |
opts: opts, |
| 229 |
}, nil |
| 230 |
} |
| 231 |
|
| 232 |
// Key returns the document key, if present. This is either the value of the field |
| 233 |
// called c.nameField, or the result of calling c.nameFunc. |
| 234 |
func (c *collection) Key(doc driver.Document) (any, error) { |
| 235 |
if c.nameField != "" { |
| 236 |
name, err := doc.GetField(c.nameField) |
| 237 |
vn := reflect.ValueOf(name) |
| 238 |
if err != nil || name == nil || driver.IsEmptyValue(vn) { |
| 239 |
// missing field is not an error |
| 240 |
return nil, nil |
| 241 |
} |
| 242 |
// Check that the reflect kind is String so we can support any type whose underlying type |
| 243 |
// is string. E.g. "type DocName string". |
| 244 |
if vn.Kind() != reflect.String { |
| 245 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "key field %q with value %v is not a string", |
| 246 |
c.nameField, name) |
| 247 |
} |
| 248 |
sname := vn.String() |
| 249 |
if sname == "" { // empty string is the same as missing |
| 250 |
return nil, nil |
| 251 |
} |
| 252 |
return sname, nil |
| 253 |
} |
| 254 |
sname := c.nameFunc(doc.Origin) |
| 255 |
if sname == "" { |
| 256 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "missing document key") |
| 257 |
} |
| 258 |
return sname, nil |
| 259 |
} |
| 260 |
|
| 261 |
func (c *collection) RevisionField() string { |
| 262 |
return c.opts.RevisionField |
| 263 |
} |
| 264 |
|
| 265 |
// RunActions implements driver.RunActions. |
| 266 |
func (c *collection) RunActions(ctx context.Context, actions []*driver.Action, opts *driver.RunActionsOptions) driver.ActionListError { |
| 267 |
errs := make([]error, len(actions)) |
| 268 |
beforeGets, gets, writes, writesTx, afterGets := driver.GroupActions(actions) |
| 269 |
calls := c.buildCommitCalls(writes, errs) |
| 270 |
atomicWritesCall := c.buildAtomicWritesCommitCall(writesTx, errs) |
| 271 |
// runGets does not issue concurrent RPCs, so it doesn't need a throttle. |
| 272 |
c.runGets(ctx, beforeGets, errs, opts) |
| 273 |
t := driver.NewThrottle(c.opts.MaxOutstandingActionRPCs) |
| 274 |
for _, call := range calls { |
| 275 |
t.Acquire() |
| 276 |
go func() { |
| 277 |
defer t.Release() |
| 278 |
c.doCommitCall(ctx, call, errs, opts) |
| 279 |
}() |
| 280 |
} |
| 281 |
// commit the atomic writes |
| 282 |
if atomicWritesCall != nil && len(atomicWritesCall.actions) > 0 { |
| 283 |
t.Acquire() |
| 284 |
go func() { |
| 285 |
defer t.Release() |
| 286 |
c.doCommitCall(ctx, atomicWritesCall, errs, opts) |
| 287 |
}() |
| 288 |
} |
| 289 |
|
| 290 |
t.Acquire() |
| 291 |
c.runGets(ctx, gets, errs, opts) |
| 292 |
t.Release() |
| 293 |
t.Wait() |
| 294 |
c.runGets(ctx, afterGets, errs, opts) |
| 295 |
return driver.NewActionListError(errs) |
| 296 |
} |
| 297 |
|
| 298 |
// runGets executes a group of Get actions by calling the BatchGetDocuments RPC. |
| 299 |
// It may make several calls, because all gets in a single RPC must have the same set of field paths. |
| 300 |
func (c *collection) runGets(ctx context.Context, actions []*driver.Action, errs []error, opts *driver.RunActionsOptions) { |
| 301 |
for _, group := range driver.GroupByFieldPath(actions) { |
| 302 |
c.batchGet(ctx, group, errs, opts) |
| 303 |
} |
| 304 |
} |
| 305 |
|
| 306 |
// Run a single BatchGet RPC with the given Get actions, all of which have the same set of field paths. |
| 307 |
// Populate errs, a slice of per-action errors indexed by the original action list position. |
| 308 |
func (c *collection) batchGet(ctx context.Context, gets []*driver.Action, errs []error, opts *driver.RunActionsOptions) { |
| 309 |
setErr := func(err error) { |
| 310 |
for _, g := range gets { |
| 311 |
errs[g.Index] = err |
| 312 |
} |
| 313 |
} |
| 314 |
|
| 315 |
req, err := c.newGetRequest(gets) |
| 316 |
if err != nil { |
| 317 |
setErr(err) |
| 318 |
return |
| 319 |
} |
| 320 |
indexByPath := map[string]int{} // from document path to index in gets |
| 321 |
for i, path := range req.Documents { |
| 322 |
indexByPath[path] = i |
| 323 |
} |
| 324 |
if opts.BeforeDo != nil { |
| 325 |
if err := opts.BeforeDo(driver.AsFunc(req)); err != nil { |
| 326 |
setErr(err) |
| 327 |
return |
| 328 |
} |
| 329 |
} |
| 330 |
streamClient, err := c.client.BatchGetDocuments(withResourceHeader(ctx, req.Database), req) |
| 331 |
if err != nil { |
| 332 |
setErr(err) |
| 333 |
return |
| 334 |
} |
| 335 |
for { |
| 336 |
resp, err := streamClient.Recv() |
| 337 |
if err == io.EOF { |
| 338 |
break |
| 339 |
} |
| 340 |
if err != nil { |
| 341 |
setErr(err) |
| 342 |
return |
| 343 |
} |
| 344 |
switch r := resp.Result.(type) { |
| 345 |
case *pb.BatchGetDocumentsResponse_Found: |
| 346 |
pdoc := r.Found |
| 347 |
i, ok := indexByPath[pdoc.Name] |
| 348 |
if !ok { |
| 349 |
setErr(gcerr.Newf(gcerr.Internal, nil, "no index for path %s", pdoc.Name)) |
| 350 |
} else { |
| 351 |
errs[gets[i].Index] = decodeDoc(pdoc, gets[i].Doc, c.nameField, c.opts.RevisionField) |
| 352 |
} |
| 353 |
case *pb.BatchGetDocumentsResponse_Missing: |
| 354 |
i := indexByPath[r.Missing] |
| 355 |
errs[gets[i].Index] = gcerr.Newf(gcerr.NotFound, nil, "document at path %q is missing", r.Missing) |
| 356 |
default: |
| 357 |
setErr(gcerr.Newf(gcerr.Internal, nil, "unknown BatchGetDocumentsResponse result type")) |
| 358 |
return |
| 359 |
} |
| 360 |
} |
| 361 |
} |
| 362 |
|
| 363 |
func (c *collection) newGetRequest(gets []*driver.Action) (*pb.BatchGetDocumentsRequest, error) { |
| 364 |
req := &pb.BatchGetDocumentsRequest{Database: c.dbPath} |
| 365 |
for _, a := range gets { |
| 366 |
req.Documents = append(req.Documents, c.collPath+"/"+a.Key.(string)) |
| 367 |
} |
| 368 |
// groupActions has already made sure that all the actions have the same field paths, |
| 369 |
// so just use the first one. |
| 370 |
var fps []string // field paths that will go in the mask |
| 371 |
for _, fp := range gets[0].FieldPaths { |
| 372 |
fps = append(fps, toServiceFieldPath(fp)) |
| 373 |
} |
| 374 |
if fps != nil { |
| 375 |
req.Mask = &pb.DocumentMask{FieldPaths: fps} |
| 376 |
} |
| 377 |
return req, nil |
| 378 |
} |
| 379 |
|
| 380 |
// commitCall holds information needed to make a Commit RPC and to follow up after it is done. |
| 381 |
type commitCall struct { |
| 382 |
writes []*pb.Write // writes to commit |
| 383 |
actions []*driver.Action // actions corresponding to those writes |
| 384 |
newNames []string // new names for Create; parallel to actions |
| 385 |
} |
| 386 |
|
| 387 |
// Construct a set of concurrently runnable calls to Commit. |
| 388 |
func (c *collection) buildCommitCalls(actions []*driver.Action, errs []error) []*commitCall { |
| 389 |
// Convert each action to one or more writes, collecting names for newly created |
| 390 |
// documents along the way. Divide writes into those with preconditions and those without. |
| 391 |
// Writes without preconditions can't fail, so we can execute them all in one Commit RPC. |
| 392 |
// All other writes must be run as separate Commits. |
| 393 |
var ( |
| 394 |
nCall = &commitCall{} // for writes without preconditions |
| 395 |
pCalls []*commitCall // for writes with preconditions |
| 396 |
) |
| 397 |
for _, a := range actions { |
| 398 |
ws, nn, err := c.actionToWrites(a) |
| 399 |
if err != nil { |
| 400 |
errs[a.Index] = err |
| 401 |
} else if ws[0].CurrentDocument == nil { // no precondition |
| 402 |
nCall.writes = append(nCall.writes, ws...) |
| 403 |
nCall.actions = append(nCall.actions, a) |
| 404 |
nCall.newNames = append(nCall.newNames, nn) |
| 405 |
} else { // writes have a precondition |
| 406 |
pCalls = append(pCalls, &commitCall{ |
| 407 |
writes: ws, |
| 408 |
actions: []*driver.Action{a}, |
| 409 |
newNames: []string{nn}, |
| 410 |
}) |
| 411 |
} |
| 412 |
} |
| 413 |
if len(nCall.writes) == 0 { |
| 414 |
return pCalls |
| 415 |
} |
| 416 |
return append(pCalls, nCall) |
| 417 |
} |
| 418 |
|
| 419 |
// Construct a commit call with all the atomic writes |
| 420 |
func (c *collection) buildAtomicWritesCommitCall(actions []*driver.Action, errs []error) *commitCall { |
| 421 |
atomicWritesCommitCall := &commitCall{} |
| 422 |
for _, a := range actions { |
| 423 |
ws, nn, err := c.actionToWrites(a) |
| 424 |
if err != nil { |
| 425 |
errs[a.Index] = err |
| 426 |
return nil |
| 427 |
} else { |
| 428 |
atomicWritesCommitCall.writes = append(atomicWritesCommitCall.writes, ws...) |
| 429 |
atomicWritesCommitCall.actions = append(atomicWritesCommitCall.actions, a) |
| 430 |
atomicWritesCommitCall.newNames = append(atomicWritesCommitCall.newNames, nn) |
| 431 |
} |
| 432 |
} |
| 433 |
return atomicWritesCommitCall |
| 434 |
} |
| 435 |
|
| 436 |
// Convert an action to one or more Firestore Write protos. |
| 437 |
func (c *collection) actionToWrites(a *driver.Action) ([]*pb.Write, string, error) { |
| 438 |
var ( |
| 439 |
w *pb.Write |
| 440 |
ws []*pb.Write |
| 441 |
err error |
| 442 |
docName string |
| 443 |
newName string // for Create with no name |
| 444 |
) |
| 445 |
if a.Key != nil { |
| 446 |
docName = a.Key.(string) |
| 447 |
} |
| 448 |
switch a.Kind { |
| 449 |
case driver.Create: |
| 450 |
// Make a name for this document if it doesn't have one. |
| 451 |
if a.Key == nil { |
| 452 |
docName = driver.UniqueString() |
| 453 |
newName = docName |
| 454 |
} |
| 455 |
w, err = c.putWrite(a.Doc, docName, &pb.Precondition{ConditionType: &pb.Precondition_Exists{Exists: false}}) |
| 456 |
|
| 457 |
case driver.Replace: |
| 458 |
// If the given document has a revision, use it as the precondition (it implies existence). |
| 459 |
pc, perr := c.revisionPrecondition(a.Doc) |
| 460 |
if perr != nil { |
| 461 |
return nil, "", perr |
| 462 |
} |
| 463 |
// Otherwise, just require that the document exists. |
| 464 |
if pc == nil { |
| 465 |
pc = &pb.Precondition{ConditionType: &pb.Precondition_Exists{Exists: true}} |
| 466 |
} |
| 467 |
w, err = c.putWrite(a.Doc, docName, pc) |
| 468 |
|
| 469 |
case driver.Put: |
| 470 |
pc, perr := c.revisionPrecondition(a.Doc) |
| 471 |
if perr != nil { |
| 472 |
return nil, "", perr |
| 473 |
} |
| 474 |
w, err = c.putWrite(a.Doc, docName, pc) |
| 475 |
|
| 476 |
case driver.Update: |
| 477 |
ws, err = c.updateWrites(a.Doc, docName, a.Mods) |
| 478 |
|
| 479 |
case driver.Delete: |
| 480 |
w, err = c.deleteWrite(a.Doc, docName) |
| 481 |
|
| 482 |
default: |
| 483 |
err = gcerr.Newf(gcerr.Internal, nil, "bad action %+v", a) |
| 484 |
} |
| 485 |
if err != nil { |
| 486 |
return nil, "", err |
| 487 |
} |
| 488 |
if ws == nil { |
| 489 |
ws = []*pb.Write{w} |
| 490 |
} |
| 491 |
return ws, newName, nil |
| 492 |
} |
| 493 |
|
| 494 |
func (c *collection) putWrite(doc driver.Document, docName string, pc *pb.Precondition) (*pb.Write, error) { |
| 495 |
pdoc, err := encodeDoc(doc, c.nameField) |
| 496 |
if err != nil { |
| 497 |
return nil, err |
| 498 |
} |
| 499 |
pdoc.Name = c.collPath + "/" + docName |
| 500 |
return &pb.Write{ |
| 501 |
Operation: &pb.Write_Update{Update: pdoc}, |
| 502 |
CurrentDocument: pc, |
| 503 |
}, nil |
| 504 |
} |
| 505 |
|
| 506 |
func (c *collection) deleteWrite(doc driver.Document, docName string) (*pb.Write, error) { |
| 507 |
pc, err := c.revisionPrecondition(doc) |
| 508 |
if err != nil { |
| 509 |
return nil, err |
| 510 |
} |
| 511 |
return &pb.Write{ |
| 512 |
Operation: &pb.Write_Delete{Delete: c.collPath + "/" + docName}, |
| 513 |
CurrentDocument: pc, |
| 514 |
}, nil |
| 515 |
} |
| 516 |
|
| 517 |
// updateWrites returns a slice of writes because we may need two: one for setting |
| 518 |
// and deleting values, the other for transforms. |
| 519 |
func (c *collection) updateWrites(doc driver.Document, docName string, mods []driver.Mod) ([]*pb.Write, error) { |
| 520 |
ts, err := c.revisionTimestamp(doc) |
| 521 |
if err != nil { |
| 522 |
return nil, err |
| 523 |
} |
| 524 |
fields, paths, transforms, err := processMods(mods) |
| 525 |
if err != nil { |
| 526 |
return nil, err |
| 527 |
} |
| 528 |
return newUpdateWrites(c.collPath+"/"+docName, ts, fields, paths, transforms) |
| 529 |
} |
| 530 |
|
| 531 |
func newUpdateWrites(docPath string, ts *tspb.Timestamp, fields map[string]*pb.Value, paths []string, transforms []*pb.DocumentTransform_FieldTransform) ([]*pb.Write, error) { |
| 532 |
pc := preconditionFromTimestamp(ts) |
| 533 |
// If there is no revision in the document, add a precondition that the document exists. |
| 534 |
if pc == nil { |
| 535 |
pc = &pb.Precondition{ConditionType: &pb.Precondition_Exists{Exists: true}} |
| 536 |
} |
| 537 |
var ws []*pb.Write |
| 538 |
if len(fields) > 0 || len(paths) > 0 { |
| 539 |
ws = []*pb.Write{{ |
| 540 |
Operation: &pb.Write_Update{Update: &pb.Document{ |
| 541 |
Name: docPath, |
| 542 |
Fields: fields, |
| 543 |
}}, |
| 544 |
UpdateMask: &pb.DocumentMask{FieldPaths: paths}, |
| 545 |
CurrentDocument: pc, |
| 546 |
}} |
| 547 |
pc = nil // If the precondition is in the write, we don't need it in the transform. |
| 548 |
} |
| 549 |
if len(transforms) > 0 { |
| 550 |
ws = append(ws, &pb.Write{ |
| 551 |
Operation: &pb.Write_Transform{ |
| 552 |
Transform: &pb.DocumentTransform{ |
| 553 |
Document: docPath, |
| 554 |
FieldTransforms: transforms, |
| 555 |
}, |
| 556 |
}, |
| 557 |
CurrentDocument: pc, |
| 558 |
}) |
| 559 |
} |
| 560 |
return ws, nil |
| 561 |
} |
| 562 |
|
| 563 |
// To update a document, we need to send: |
| 564 |
// - A document with all the fields we want to add or change. |
| 565 |
// - A mask with the field paths of all the fields we want to add, change or delete. |
| 566 |
// processMods converts the mods into the fields for the document, and a list of |
| 567 |
// valid Firestore field paths for the mask. |
| 568 |
func processMods(mods []driver.Mod) (fields map[string]*pb.Value, maskPaths []string, transforms []*pb.DocumentTransform_FieldTransform, err error) { |
| 569 |
fields = map[string]*pb.Value{} |
| 570 |
for _, m := range mods { |
| 571 |
sfp := toServiceFieldPath(m.FieldPath) |
| 572 |
// If m.Value is nil, we want to delete it. In that case, we put the field in |
| 573 |
// the mask but not in the doc. |
| 574 |
if inc, ok := m.Value.(driver.IncOp); ok { |
| 575 |
pv, err := encodeValue(inc.Amount) |
| 576 |
if err != nil { |
| 577 |
return nil, nil, nil, err |
| 578 |
} |
| 579 |
transforms = append(transforms, &pb.DocumentTransform_FieldTransform{ |
| 580 |
FieldPath: sfp, |
| 581 |
TransformType: &pb.DocumentTransform_FieldTransform_Increment{ |
| 582 |
Increment: pv, |
| 583 |
}, |
| 584 |
}) |
| 585 |
} else { |
| 586 |
// The field path of every other mod belongs in the mask. |
| 587 |
maskPaths = append(maskPaths, sfp) |
| 588 |
if m.Value != nil { |
| 589 |
pv, err := encodeValue(m.Value) |
| 590 |
if err != nil { |
| 591 |
return nil, nil, nil, err |
| 592 |
} |
| 593 |
if err := setAtFieldPath(fields, m.FieldPath, pv); err != nil { |
| 594 |
return nil, nil, nil, err |
| 595 |
} |
| 596 |
} |
| 597 |
} |
| 598 |
} |
| 599 |
return fields, maskPaths, transforms, nil |
| 600 |
} |
| 601 |
|
| 602 |
// doCommitCall Calls the Commit RPC with a list of writes, and handles the results. |
| 603 |
func (c *collection) doCommitCall(ctx context.Context, call *commitCall, errs []error, opts *driver.RunActionsOptions) { |
| 604 |
wrs, err := c.commit(ctx, call.writes, opts) |
| 605 |
if err != nil { |
| 606 |
for _, a := range call.actions { |
| 607 |
errs[a.Index] = err |
| 608 |
} |
| 609 |
return |
| 610 |
} |
| 611 |
// Set the revision fields of the documents. |
| 612 |
// The actions and writes may not correspond, because Update actions may require |
| 613 |
// two writes. We can tell which writes correspond to actions by the type of write. |
| 614 |
j := 0 |
| 615 |
for i, a := range call.actions { |
| 616 |
wr := wrs[j] |
| 617 |
if a.Doc.HasField(c.opts.RevisionField) { |
| 618 |
if err := a.Doc.SetField(c.opts.RevisionField, wr.UpdateTime); err != nil { |
| 619 |
errs[a.Index] = err |
| 620 |
} |
| 621 |
} |
| 622 |
if call.newNames[i] != "" { |
| 623 |
// c.nameField should not be empty since we only create new names when there |
| 624 |
// is a nameField. |
| 625 |
_ = a.Doc.SetField(c.nameField, call.newNames[i]) |
| 626 |
} |
| 627 |
if hasFollowingTransform(call.writes, j) { |
| 628 |
j = j + 2 |
| 629 |
} else { |
| 630 |
j++ |
| 631 |
} |
| 632 |
} |
| 633 |
} |
| 634 |
|
| 635 |
func hasFollowingTransform(writes []*pb.Write, i int) bool { |
| 636 |
if i >= len(writes)-1 { |
| 637 |
return false |
| 638 |
} |
| 639 |
curr, ok := writes[i].Operation.(*pb.Write_Update) |
| 640 |
if !ok { |
| 641 |
return false |
| 642 |
} |
| 643 |
next, ok := writes[i+1].Operation.(*pb.Write_Transform) |
| 644 |
if !ok { |
| 645 |
return false |
| 646 |
} |
| 647 |
return curr.Update.Name == next.Transform.Document |
| 648 |
} |
| 649 |
|
| 650 |
func (c *collection) commit(ctx context.Context, ws []*pb.Write, opts *driver.RunActionsOptions) ([]*pb.WriteResult, error) { |
| 651 |
req := &pb.CommitRequest{ |
| 652 |
Database: c.dbPath, |
| 653 |
Writes: ws, |
| 654 |
} |
| 655 |
if opts.BeforeDo != nil { |
| 656 |
if err := opts.BeforeDo(driver.AsFunc(req)); err != nil { |
| 657 |
return nil, err |
| 658 |
} |
| 659 |
} |
| 660 |
res, err := c.client.Commit(withResourceHeader(ctx, req.Database), req) |
| 661 |
if err != nil { |
| 662 |
return nil, err |
| 663 |
} |
| 664 |
if len(res.WriteResults) != len(ws) { |
| 665 |
return nil, gcerr.Newf(gcerr.Internal, nil, "wrong number of WriteResults from firestore commit") |
| 666 |
} |
| 667 |
return res.WriteResults, nil |
| 668 |
} |
| 669 |
|
| 670 |
/////////////// |
| 671 |
// From memdocstore/mem.go. |
| 672 |
|
| 673 |
// setAtFieldPath sets m's value at fp to val. It creates intermediate maps as |
| 674 |
// needed. It returns an error if a non-final component of fp does not denote a map. |
| 675 |
func setAtFieldPath(m map[string]*pb.Value, fp []string, val *pb.Value) error { |
| 676 |
m2, err := getParentMap(m, fp, true) |
| 677 |
if err != nil { |
| 678 |
return err |
| 679 |
} |
| 680 |
m2[fp[len(fp)-1]] = val |
| 681 |
return nil |
| 682 |
} |
| 683 |
|
| 684 |
// getParentMap returns the map that directly contains the given field path; |
| 685 |
// that is, the value of m at the field path that excludes the last component |
| 686 |
// of fp. If a non-map is encountered along the way, an InvalidArgument error is |
| 687 |
// returned. If nil is encountered, nil is returned unless create is true, in |
| 688 |
// which case a map is added at that point. |
| 689 |
func getParentMap(m map[string]*pb.Value, fp []string, create bool) (map[string]*pb.Value, error) { |
| 690 |
for _, k := range fp[:len(fp)-1] { |
| 691 |
if m[k] == nil { |
| 692 |
if !create { |
| 693 |
return nil, nil |
| 694 |
} |
| 695 |
m[k] = &pb.Value{ValueType: &pb.Value_MapValue{&pb.MapValue{Fields: map[string]*pb.Value{}}}} |
| 696 |
} |
| 697 |
mv := m[k].GetMapValue() |
| 698 |
if mv == nil { |
| 699 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "invalid field path %q at %q", strings.Join(fp, "."), k) |
| 700 |
} |
| 701 |
m = mv.Fields |
| 702 |
} |
| 703 |
return m, nil |
| 704 |
} |
| 705 |
|
| 706 |
//////////////// |
| 707 |
// From fieldpath.go in cloud.google.com/go/firestore. |
| 708 |
|
| 709 |
// Convert a docstore field path, which is a []string, into the kind of field path |
| 710 |
// that the Firestore service expects: a string of dot-separated components, some of |
| 711 |
// which may be quoted. |
| 712 |
func toServiceFieldPath(fp []string) string { |
| 713 |
cs := make([]string, len(fp)) |
| 714 |
for i, c := range fp { |
| 715 |
cs[i] = toServiceFieldPathComponent(c) |
| 716 |
} |
| 717 |
return strings.Join(cs, ".") |
| 718 |
} |
| 719 |
|
| 720 |
// Google SQL syntax for an unquoted field. |
| 721 |
var unquotedFieldRE = regexp.MustCompile("^[A-Za-z_][A-Za-z_0-9]*$") |
| 722 |
|
| 723 |
// toServiceFieldPathComponent returns a string that represents key and is a valid |
| 724 |
// Firestore field path component. Components must be quoted with backticks if |
| 725 |
// they don't match the above regexp. |
| 726 |
func toServiceFieldPathComponent(key string) string { |
| 727 |
if unquotedFieldRE.MatchString(key) { |
| 728 |
return key |
| 729 |
} |
| 730 |
var buf bytes.Buffer |
| 731 |
buf.WriteRune('`') |
| 732 |
for _, r := range key { |
| 733 |
if r == '`' || r == '\\' { |
| 734 |
buf.WriteRune('\\') |
| 735 |
} |
| 736 |
buf.WriteRune(r) |
| 737 |
} |
| 738 |
buf.WriteRune('`') |
| 739 |
return buf.String() |
| 740 |
} |
| 741 |
|
| 742 |
// revisionPrecondition returns a Firestore precondition that asserts that the stored document's |
| 743 |
// revision matches the revision of doc. |
| 744 |
func (c *collection) revisionPrecondition(doc driver.Document) (*pb.Precondition, error) { |
| 745 |
rev, err := c.revisionTimestamp(doc) |
| 746 |
if err != nil { |
| 747 |
return nil, err |
| 748 |
} |
| 749 |
return preconditionFromTimestamp(rev), nil |
| 750 |
} |
| 751 |
|
| 752 |
// revisionTimestamp extracts the timestamp from the revision field of doc, if there is one. |
| 753 |
// It only returns an error if the revision field is present and does not contain the right type. |
| 754 |
func (c *collection) revisionTimestamp(doc driver.Document) (*tspb.Timestamp, error) { |
| 755 |
v, err := doc.GetField(c.opts.RevisionField) |
| 756 |
if err != nil { // revision field not present |
| 757 |
return nil, nil |
| 758 |
} |
| 759 |
if v == nil { // revision field is present, but nil |
| 760 |
return nil, nil |
| 761 |
} |
| 762 |
rev, ok := v.(*tspb.Timestamp) |
| 763 |
if !ok { |
| 764 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, |
| 765 |
"%s field contains wrong type: got %T, want proto Timestamp", |
| 766 |
c.opts.RevisionField, v) |
| 767 |
} |
| 768 |
return rev, nil |
| 769 |
} |
| 770 |
|
| 771 |
func preconditionFromTimestamp(ts *tspb.Timestamp) *pb.Precondition { |
| 772 |
if ts == nil || (ts.Seconds == 0 && ts.Nanos == 0) { // ignore a missing or zero revision |
| 773 |
return nil |
| 774 |
} |
| 775 |
return &pb.Precondition{ConditionType: &pb.Precondition_UpdateTime{ts}} |
| 776 |
} |
| 777 |
|
| 778 |
func (c *collection) ErrorCode(err error) gcerrors.ErrorCode { |
| 779 |
return gcerr.GRPCCode(err) |
| 780 |
} |
| 781 |
|
| 782 |
// resourcePrefixHeader is the name of the metadata header used to indicate |
| 783 |
// the resource being operated on. |
| 784 |
const resourcePrefixHeader = "google-cloud-resource-prefix" |
| 785 |
|
| 786 |
// withResourceHeader returns a new context that includes resource in a special header. |
| 787 |
// Firestore uses the resource header for routing. |
| 788 |
func withResourceHeader(ctx context.Context, resource string) context.Context { |
| 789 |
md, _ := metadata.FromOutgoingContext(ctx) |
| 790 |
md = md.Copy() |
| 791 |
md[resourcePrefixHeader] = []string{resource} |
| 792 |
return metadata.NewOutgoingContext(ctx, md) |
| 793 |
} |
| 794 |
|
| 795 |
// RevisionToBytes implements driver.RevisionToBytes. |
| 796 |
func (c *collection) RevisionToBytes(rev any) ([]byte, error) { |
| 797 |
r, ok := rev.(*tspb.Timestamp) |
| 798 |
if !ok { |
| 799 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "revision %v of type %[1]T is not a proto Timestamp", rev) |
| 800 |
} |
| 801 |
return proto.Marshal(r) |
| 802 |
} |
| 803 |
|
| 804 |
// BytesToRevision implements driver.BytesToRevision. |
| 805 |
func (c *collection) BytesToRevision(b []byte) (any, error) { |
| 806 |
var ts tspb.Timestamp |
| 807 |
if err := proto.Unmarshal(b, &ts); err != nil { |
| 808 |
return nil, err |
| 809 |
} |
| 810 |
return &ts, nil |
| 811 |
} |
| 812 |
|
| 813 |
func (c *collection) As(i any) bool { |
| 814 |
p, ok := i.(**vkit.Client) |
| 815 |
if !ok { |
| 816 |
return false |
| 817 |
} |
| 818 |
*p = c.client |
| 819 |
return true |
| 820 |
} |
| 821 |
|
| 822 |
// ErrorAs implements driver.Collection.ErrorAs. |
| 823 |
func (c *collection) ErrorAs(err error, i any) bool { |
| 824 |
s, ok := status.FromError(err) |
| 825 |
if !ok { |
| 826 |
return false |
| 827 |
} |
| 828 |
p, ok := i.(**status.Status) |
| 829 |
if !ok { |
| 830 |
return false |
| 831 |
} |
| 832 |
*p = s |
| 833 |
return true |
| 834 |
} |
| 835 |
|
| 836 |
// Close implements driver.Collection.Close. |
| 837 |
func (c *collection) Close() error { return nil } |