| 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 awsdynamodb provides a docstore implementation backed by Amazon |
| 16 |
// DynamoDB. |
| 17 |
// Use OpenCollection to construct a *docstore.Collection. |
| 18 |
// |
| 19 |
// # URLs |
| 20 |
// |
| 21 |
// For docstore.OpenCollection, awsdynamodb registers for the scheme |
| 22 |
// "dynamodb". The default URL opener will use an AWS session with the default |
| 23 |
// credentials and configuration; see |
| 24 |
// https://docs.aws.amazon.com/sdk-for-go/v2/developer-guide/configure-gosdk.html for more details. |
| 25 |
// To customize the URL opener, or for more details on the URL format, see |
| 26 |
// URLOpener. |
| 27 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 28 |
// |
| 29 |
// # As |
| 30 |
// |
| 31 |
// awsdynamodb exposes the following types for As: |
| 32 |
// - Collection.As: *dynamodb.DynamoDB |
| 33 |
// - ActionList.BeforeDo: *dynamodb.BatchGetItemInput or *dynamodb.PutItemInput or *dynamodb.DeleteItemInput |
| 34 |
// or *dynamodb.UpdateItemInput |
| 35 |
// - Query.BeforeQuery: *dynamodb.QueryInput or *dynamodb.ScanInput |
| 36 |
// - DocumentIterator: *dynamodb.QueryOutput or *dynamodb.ScanOutput |
| 37 |
// - ErrorAs: smithy.OperationError |
| 38 |
package awsdynamodb |
| 39 |
|
| 40 |
import ( |
| 41 |
"context" |
| 42 |
"errors" |
| 43 |
"fmt" |
| 44 |
"reflect" |
| 45 |
"strings" |
| 46 |
|
| 47 |
"github.com/aws/aws-sdk-go-v2/aws" |
| 48 |
"github.com/aws/aws-sdk-go-v2/feature/dynamodb/expression" |
| 49 |
dyn "github.com/aws/aws-sdk-go-v2/service/dynamodb" |
| 50 |
dyn2Types "github.com/aws/aws-sdk-go-v2/service/dynamodb/types" |
| 51 |
"github.com/aws/smithy-go" |
| 52 |
"github.com/google/wire" |
| 53 |
"gocloud.dev/docstore" |
| 54 |
"gocloud.dev/docstore/driver" |
| 55 |
"gocloud.dev/gcerrors" |
| 56 |
"gocloud.dev/internal/gcerr" |
| 57 |
) |
| 58 |
|
| 59 |
// Set holds Wire providers for this package. |
| 60 |
var Set = wire.NewSet( |
| 61 |
wire.Struct(new(URLOpener)), |
| 62 |
) |
| 63 |
|
| 64 |
type collection struct { |
| 65 |
db *dyn.Client |
| 66 |
table string // DynamoDB table name |
| 67 |
partitionKey string |
| 68 |
sortKey string |
| 69 |
description *dyn2Types.TableDescription |
| 70 |
opts *Options |
| 71 |
} |
| 72 |
|
| 73 |
// FallbackFunc is a function for executing queries that cannot be run by the built-in |
| 74 |
// awsdynamodb logic. See Options.RunQueryFunc for details. |
| 75 |
type FallbackFunc func(context.Context, *driver.Query, RunQueryFunc) (driver.DocumentIterator, error) |
| 76 |
|
| 77 |
// Options holds various options. |
| 78 |
type Options struct { |
| 79 |
// If false, queries that can only be executed by scanning the entire table |
| 80 |
// return an error instead (with the exception of a query with no filters). |
| 81 |
AllowScans bool |
| 82 |
|
| 83 |
// The name of the field holding the document revision. |
| 84 |
// Defaults to docstore.DefaultRevisionField. |
| 85 |
RevisionField string |
| 86 |
|
| 87 |
// If set, call this function on queries that we cannot execute at all (for |
| 88 |
// example, a query with an OrderBy clause that lacks an equality filter on a |
| 89 |
// partition key). The function should execute the query however it wishes, and |
| 90 |
// return an iterator over the results. It can use the RunQueryFunc passed as its |
| 91 |
// third argument to have the DynamoDB driver run a query, for instance a |
| 92 |
// modified version of the original query. |
| 93 |
// |
| 94 |
// If RunQueryFallback is nil, queries that cannot be executed will fail with a |
| 95 |
// error that has code Unimplemented. |
| 96 |
RunQueryFallback FallbackFunc |
| 97 |
|
| 98 |
// The maximum number of concurrent goroutines started for a single call to |
| 99 |
// ActionList.Do. If less than 1, there is no limit. |
| 100 |
MaxOutstandingActionRPCs int |
| 101 |
|
| 102 |
// If true, a strongly consistent read is used whenever possible, including |
| 103 |
// get, query, scan, etc.; default to false, where an eventually consistent |
| 104 |
// read is used. |
| 105 |
// |
| 106 |
// Not all read operations support this mode however, such as querying against |
| 107 |
// a global secondary index, the operation will return an InvalidArgument error |
| 108 |
// in such case, please check the official DynamoDB documentation for more |
| 109 |
// details. |
| 110 |
// |
| 111 |
// The native client for DynamoDB uses this option in a per-action basis, if |
| 112 |
// you need the flexibility to run both modes on the same collection, create |
| 113 |
// two collections with different mode. |
| 114 |
ConsistentRead bool |
| 115 |
} |
| 116 |
|
| 117 |
// RunQueryFunc is the type of the function passed to RunQueryFallback. |
| 118 |
type RunQueryFunc func(context.Context, *driver.Query) (driver.DocumentIterator, error) |
| 119 |
|
| 120 |
// OpenCollection creates a *docstore.Collection representing a DynamoDB collection. |
| 121 |
func OpenCollection(db *dyn.Client, tableName, partitionKey, sortKey string, opts *Options) (*docstore.Collection, error) { |
| 122 |
c, err := newCollection(db, tableName, partitionKey, sortKey, opts) |
| 123 |
if err != nil { |
| 124 |
return nil, err |
| 125 |
} |
| 126 |
return docstore.NewCollection(c), nil |
| 127 |
} |
| 128 |
|
| 129 |
func newCollection(db *dyn.Client, tableName, partitionKey, sortKey string, opts *Options) (*collection, error) { |
| 130 |
out, err := db.DescribeTable(context.Background(), &dyn.DescribeTableInput{TableName: &tableName}) |
| 131 |
if err != nil { |
| 132 |
return nil, err |
| 133 |
} |
| 134 |
if opts == nil { |
| 135 |
opts = &Options{} |
| 136 |
} |
| 137 |
if opts.RevisionField == "" { |
| 138 |
opts.RevisionField = docstore.DefaultRevisionField |
| 139 |
} |
| 140 |
return &collection{ |
| 141 |
db: db, |
| 142 |
table: tableName, |
| 143 |
partitionKey: partitionKey, |
| 144 |
sortKey: sortKey, |
| 145 |
description: out.Table, |
| 146 |
opts: opts, |
| 147 |
}, nil |
| 148 |
} |
| 149 |
|
| 150 |
// Key returns a two-element array with the partition key and sort key, if any. |
| 151 |
func (c *collection) Key(doc driver.Document) (any, error) { |
| 152 |
pkey, err := doc.GetField(c.partitionKey) |
| 153 |
if err != nil || pkey == nil || driver.IsEmptyValue(reflect.ValueOf(pkey)) { |
| 154 |
return nil, nil // missing key is not an error |
| 155 |
} |
| 156 |
keys := [2]any{pkey} |
| 157 |
if c.sortKey != "" { |
| 158 |
keys[1], _ = doc.GetField(c.sortKey) // ignore error since keys[1] is nil in that case |
| 159 |
} |
| 160 |
return keys, nil |
| 161 |
} |
| 162 |
|
| 163 |
func (c *collection) RevisionField() string { return c.opts.RevisionField } |
| 164 |
|
| 165 |
func (c *collection) RunActions(ctx context.Context, actions []*driver.Action, opts *driver.RunActionsOptions) driver.ActionListError { |
| 166 |
errs := make([]error, len(actions)) |
| 167 |
beforeGets, gets, writes, writesTx, afterGets := driver.GroupActions(actions) |
| 168 |
c.runGets(ctx, beforeGets, errs, opts) |
| 169 |
ch := make(chan struct{}) |
| 170 |
ch2 := make(chan struct{}) |
| 171 |
go func() { defer close(ch); c.runWrites(ctx, writes, errs, opts) }() |
| 172 |
go func() { defer close(ch2); c.transactWrite(ctx, writesTx, errs, opts) }() |
| 173 |
c.runGets(ctx, gets, errs, opts) |
| 174 |
<-ch |
| 175 |
<-ch2 |
| 176 |
c.runGets(ctx, afterGets, errs, opts) |
| 177 |
return driver.NewActionListError(errs) |
| 178 |
} |
| 179 |
|
| 180 |
func (c *collection) runGets(ctx context.Context, actions []*driver.Action, errs []error, opts *driver.RunActionsOptions) { |
| 181 |
const batchSize = 100 |
| 182 |
t := driver.NewThrottle(c.opts.MaxOutstandingActionRPCs) |
| 183 |
for _, group := range driver.GroupByFieldPath(actions) { |
| 184 |
n := len(group) / batchSize |
| 185 |
for i := range n { |
| 186 |
t.Acquire() |
| 187 |
go func(group []*driver.Action) { |
| 188 |
defer t.Release() |
| 189 |
c.batchGet(ctx, group, errs, opts, batchSize*i, batchSize*(i+1)-1) |
| 190 |
}(group) |
| 191 |
} |
| 192 |
if n*batchSize < len(group) { |
| 193 |
t.Acquire() |
| 194 |
go func(group []*driver.Action) { |
| 195 |
defer t.Release() |
| 196 |
c.batchGet(ctx, group, errs, opts, batchSize*n, len(group)-1) |
| 197 |
}(group) |
| 198 |
} |
| 199 |
} |
| 200 |
t.Wait() |
| 201 |
} |
| 202 |
|
| 203 |
func (c *collection) batchGet(ctx context.Context, gets []*driver.Action, errs []error, opts *driver.RunActionsOptions, start, end int) { |
| 204 |
// errors need to be mapped to the actions' indices. |
| 205 |
setErr := func(err error) { |
| 206 |
for i := start; i <= end; i++ { |
| 207 |
errs[gets[i].Index] = err |
| 208 |
} |
| 209 |
} |
| 210 |
|
| 211 |
keys := make([]map[string]dyn2Types.AttributeValue, 0, end-start+1) |
| 212 |
for i := start; i <= end; i++ { |
| 213 |
av, err := encodeDocKeyFields(gets[i].Doc, c.partitionKey, c.sortKey) |
| 214 |
if err != nil { |
| 215 |
errs[gets[i].Index] = err |
| 216 |
} |
| 217 |
|
| 218 |
keys = append(keys, av.Value) |
| 219 |
} |
| 220 |
ka := dyn2Types.KeysAndAttributes{ |
| 221 |
Keys: keys, |
| 222 |
ConsistentRead: aws.Bool(c.opts.ConsistentRead), |
| 223 |
} |
| 224 |
if len(gets[start].FieldPaths) != 0 { |
| 225 |
// We need to add the key fields if the user doesn't include them. The |
| 226 |
// BatchGet API doesn't return them otherwise. |
| 227 |
var hasP, hasS bool |
| 228 |
var nbs []expression.NameBuilder |
| 229 |
for _, fp := range gets[start].FieldPaths { |
| 230 |
p := strings.Join(fp, ".") |
| 231 |
nbs = append(nbs, expression.Name(p)) |
| 232 |
if p == c.partitionKey { |
| 233 |
hasP = true |
| 234 |
} else if p == c.sortKey { |
| 235 |
hasS = true |
| 236 |
} |
| 237 |
} |
| 238 |
if !hasP { |
| 239 |
nbs = append(nbs, expression.Name(c.partitionKey)) |
| 240 |
} |
| 241 |
if c.sortKey != "" && !hasS { |
| 242 |
nbs = append(nbs, expression.Name(c.sortKey)) |
| 243 |
} |
| 244 |
expr, err := expression.NewBuilder(). |
| 245 |
WithProjection(expression.AddNames(expression.ProjectionBuilder{}, nbs...)). |
| 246 |
Build() |
| 247 |
if err != nil { |
| 248 |
setErr(err) |
| 249 |
return |
| 250 |
} |
| 251 |
ka.ProjectionExpression = expr.Projection() |
| 252 |
ka.ExpressionAttributeNames = expr.Names() |
| 253 |
} |
| 254 |
in := &dyn.BatchGetItemInput{RequestItems: map[string]dyn2Types.KeysAndAttributes{c.table: ka}} |
| 255 |
if opts.BeforeDo != nil { |
| 256 |
if err := opts.BeforeDo(driver.AsFunc(in)); err != nil { |
| 257 |
setErr(err) |
| 258 |
return |
| 259 |
} |
| 260 |
} |
| 261 |
out, err := c.db.BatchGetItem(ctx, in) |
| 262 |
if err != nil { |
| 263 |
setErr(err) |
| 264 |
return |
| 265 |
} |
| 266 |
found := make([]bool, end-start+1) |
| 267 |
am := mapActionIndices(gets, start, end) |
| 268 |
for _, item := range out.Responses[c.table] { |
| 269 |
if item != nil { |
| 270 |
key := map[string]any{c.partitionKey: nil} |
| 271 |
if c.sortKey != "" { |
| 272 |
key[c.sortKey] = nil |
| 273 |
} |
| 274 |
keysOnly, err := driver.NewDocument(key) |
| 275 |
if err != nil { |
| 276 |
panic(err) |
| 277 |
} |
| 278 |
err = decodeDoc(&dyn2Types.AttributeValueMemberM{Value: item}, keysOnly) |
| 279 |
if err != nil { |
| 280 |
continue |
| 281 |
} |
| 282 |
decKey, err := c.Key(keysOnly) |
| 283 |
if err != nil { |
| 284 |
continue |
| 285 |
} |
| 286 |
i := am[decKey] |
| 287 |
errs[gets[i].Index] = decodeDoc(&dyn2Types.AttributeValueMemberM{Value: item}, gets[i].Doc) |
| 288 |
found[i-start] = true |
| 289 |
} |
| 290 |
} |
| 291 |
for delta, f := range found { |
| 292 |
if !f { |
| 293 |
errs[gets[start+delta].Index] = gcerr.Newf(gcerr.NotFound, nil, "item %v not found", gets[start+delta].Doc) |
| 294 |
} |
| 295 |
} |
| 296 |
} |
| 297 |
|
| 298 |
func mapActionIndices(actions []*driver.Action, start, end int) map[any]int { |
| 299 |
m := make(map[any]int) |
| 300 |
for i := start; i <= end; i++ { |
| 301 |
m[actions[i].Key] = i |
| 302 |
} |
| 303 |
return m |
| 304 |
} |
| 305 |
|
| 306 |
// runWrites executes all the writes as separate RPCs, concurrently. |
| 307 |
func (c *collection) runWrites(ctx context.Context, writes []*driver.Action, errs []error, opts *driver.RunActionsOptions) { |
| 308 |
var ops []*writeOp |
| 309 |
for _, w := range writes { |
| 310 |
op, err := c.newWriteOp(w, opts) |
| 311 |
if err != nil { |
| 312 |
errs[w.Index] = err |
| 313 |
} else { |
| 314 |
ops = append(ops, op) |
| 315 |
} |
| 316 |
} |
| 317 |
|
| 318 |
t := driver.NewThrottle(c.opts.MaxOutstandingActionRPCs) |
| 319 |
for _, op := range ops { |
| 320 |
t.Acquire() |
| 321 |
go func() { |
| 322 |
defer t.Release() |
| 323 |
err := op.run(ctx) |
| 324 |
a := op.action |
| 325 |
if err != nil { |
| 326 |
errs[a.Index] = err |
| 327 |
} else { |
| 328 |
errs[a.Index] = c.onSuccess(op) |
| 329 |
} |
| 330 |
}() |
| 331 |
} |
| 332 |
t.Wait() |
| 333 |
} |
| 334 |
|
| 335 |
// A writeOp describes a single write to DynamoDB. The write can be executed |
| 336 |
// on its own, or included as part of a transaction. |
| 337 |
type writeOp struct { |
| 338 |
action *driver.Action |
| 339 |
writeItem dyn2Types.TransactWriteItem // for inclusion in a transaction |
| 340 |
newPartitionKey string // for a Create on a document without a partition key |
| 341 |
newRevision string |
| 342 |
run func(context.Context) error // run as a single RPC |
| 343 |
} |
| 344 |
|
| 345 |
func (c *collection) newWriteOp(a *driver.Action, opts *driver.RunActionsOptions) (*writeOp, error) { |
| 346 |
switch a.Kind { |
| 347 |
case driver.Create, driver.Replace, driver.Put: |
| 348 |
return c.newPut(a, opts) |
| 349 |
case driver.Update: |
| 350 |
return c.newUpdate(a, opts) |
| 351 |
case driver.Delete: |
| 352 |
return c.newDelete(a, opts) |
| 353 |
default: |
| 354 |
panic("bad write kind") |
| 355 |
} |
| 356 |
} |
| 357 |
|
| 358 |
func (c *collection) newPut(a *driver.Action, opts *driver.RunActionsOptions) (*writeOp, error) { |
| 359 |
av, err := encodeDoc(a.Doc) |
| 360 |
if err != nil { |
| 361 |
return nil, err |
| 362 |
} |
| 363 |
avm, ok := av.(*dyn2Types.AttributeValueMemberM) |
| 364 |
if !ok { |
| 365 |
// should never happen, but handle |
| 366 |
return nil, fmt.Errorf("unable to put document, unable to encode to map") |
| 367 |
} |
| 368 |
mf := c.missingKeyField(avm.Value) |
| 369 |
if a.Kind != driver.Create && mf != "" { |
| 370 |
return nil, fmt.Errorf("missing key field %q", mf) |
| 371 |
} |
| 372 |
var newPartitionKey string |
| 373 |
if mf == c.partitionKey { |
| 374 |
newPartitionKey = driver.UniqueString() |
| 375 |
avm.Value[c.partitionKey] = &dyn2Types.AttributeValueMemberS{Value: newPartitionKey} |
| 376 |
} |
| 377 |
if c.sortKey != "" && mf == c.sortKey { |
| 378 |
// It doesn't make sense to generate a random sort key. |
| 379 |
return nil, fmt.Errorf("missing sort key %q", c.sortKey) |
| 380 |
} |
| 381 |
var rev string |
| 382 |
if a.Doc.HasField(c.opts.RevisionField) { |
| 383 |
rev = driver.UniqueString() |
| 384 |
if avm.Value[c.opts.RevisionField], err = encodeValue(rev); err != nil { |
| 385 |
return nil, err |
| 386 |
} |
| 387 |
} |
| 388 |
dput := &dyn2Types.Put{ |
| 389 |
TableName: &c.table, |
| 390 |
Item: avm.Value, |
| 391 |
} |
| 392 |
cb, err := c.precondition(a) |
| 393 |
if err != nil { |
| 394 |
return nil, err |
| 395 |
} |
| 396 |
if cb != nil { |
| 397 |
ce, err := expression.NewBuilder().WithCondition(*cb).Build() |
| 398 |
if err != nil { |
| 399 |
return nil, err |
| 400 |
} |
| 401 |
dput.ExpressionAttributeNames = ce.Names() |
| 402 |
dput.ExpressionAttributeValues = ce.Values() |
| 403 |
dput.ConditionExpression = ce.Condition() |
| 404 |
} |
| 405 |
return &writeOp{ |
| 406 |
action: a, |
| 407 |
writeItem: dyn2Types.TransactWriteItem{Put: dput}, |
| 408 |
newPartitionKey: newPartitionKey, |
| 409 |
newRevision: rev, |
| 410 |
run: func(ctx context.Context) error { |
| 411 |
return c.runPut(ctx, dput, a, opts) |
| 412 |
}, |
| 413 |
}, nil |
| 414 |
} |
| 415 |
|
| 416 |
func (c *collection) runPut(ctx context.Context, dput *dyn2Types.Put, a *driver.Action, opts *driver.RunActionsOptions) error { |
| 417 |
in := &dyn.PutItemInput{ |
| 418 |
TableName: dput.TableName, |
| 419 |
Item: dput.Item, |
| 420 |
ConditionExpression: dput.ConditionExpression, |
| 421 |
ExpressionAttributeNames: dput.ExpressionAttributeNames, |
| 422 |
ExpressionAttributeValues: dput.ExpressionAttributeValues, |
| 423 |
} |
| 424 |
if opts.BeforeDo != nil { |
| 425 |
if err := opts.BeforeDo(driver.AsFunc(in)); err != nil { |
| 426 |
return err |
| 427 |
} |
| 428 |
} |
| 429 |
_, err := c.db.PutItem(ctx, in) |
| 430 |
var ccf *dyn2Types.ConditionalCheckFailedException |
| 431 |
if errors.As(err, &ccf) { |
| 432 |
if a.Kind == driver.Create { |
| 433 |
err = gcerr.Newf(gcerr.AlreadyExists, err, "document already exists") |
| 434 |
} |
| 435 |
if rev, _ := a.Doc.GetField(c.opts.RevisionField); rev == nil && a.Kind == driver.Replace { |
| 436 |
err = gcerr.Newf(gcerr.NotFound, nil, "document not found") |
| 437 |
} |
| 438 |
} |
| 439 |
return err |
| 440 |
} |
| 441 |
|
| 442 |
func (c *collection) newDelete(a *driver.Action, opts *driver.RunActionsOptions) (*writeOp, error) { |
| 443 |
av, err := encodeDocKeyFields(a.Doc, c.partitionKey, c.sortKey) |
| 444 |
if err != nil { |
| 445 |
return nil, err |
| 446 |
} |
| 447 |
|
| 448 |
del := &dyn2Types.Delete{ |
| 449 |
TableName: &c.table, |
| 450 |
Key: av.Value, |
| 451 |
} |
| 452 |
cb, err := c.precondition(a) |
| 453 |
if err != nil { |
| 454 |
return nil, err |
| 455 |
} |
| 456 |
if cb != nil { |
| 457 |
ce, err := expression.NewBuilder().WithCondition(*cb).Build() |
| 458 |
if err != nil { |
| 459 |
return nil, err |
| 460 |
} |
| 461 |
del.ExpressionAttributeNames = ce.Names() |
| 462 |
del.ExpressionAttributeValues = ce.Values() |
| 463 |
del.ConditionExpression = ce.Condition() |
| 464 |
} |
| 465 |
return &writeOp{ |
| 466 |
action: a, |
| 467 |
writeItem: dyn2Types.TransactWriteItem{Delete: del}, |
| 468 |
run: func(ctx context.Context) error { |
| 469 |
in := &dyn.DeleteItemInput{ |
| 470 |
TableName: del.TableName, |
| 471 |
Key: del.Key, |
| 472 |
ConditionExpression: del.ConditionExpression, |
| 473 |
ExpressionAttributeNames: del.ExpressionAttributeNames, |
| 474 |
ExpressionAttributeValues: del.ExpressionAttributeValues, |
| 475 |
} |
| 476 |
if opts.BeforeDo != nil { |
| 477 |
if err := opts.BeforeDo(driver.AsFunc(in)); err != nil { |
| 478 |
return err |
| 479 |
} |
| 480 |
} |
| 481 |
_, err := c.db.DeleteItem(ctx, in) |
| 482 |
return err |
| 483 |
}, |
| 484 |
}, nil |
| 485 |
} |
| 486 |
|
| 487 |
func (c *collection) newUpdate(a *driver.Action, opts *driver.RunActionsOptions) (*writeOp, error) { |
| 488 |
av, err := encodeDocKeyFields(a.Doc, c.partitionKey, c.sortKey) |
| 489 |
if err != nil { |
| 490 |
return nil, err |
| 491 |
} |
| 492 |
|
| 493 |
var ub expression.UpdateBuilder |
| 494 |
for _, m := range a.Mods { |
| 495 |
// TODO(shantuo): check for invalid field paths |
| 496 |
fp := expression.Name(strings.Join(m.FieldPath, ".")) |
| 497 |
if inc, ok := m.Value.(driver.IncOp); ok { |
| 498 |
ub = ub.Add(fp, expression.Value(inc.Amount)) |
| 499 |
} else if m.Value == nil { |
| 500 |
ub = ub.Remove(fp) |
| 501 |
} else { |
| 502 |
ub = ub.Set(fp, expression.Value(m.Value)) |
| 503 |
} |
| 504 |
} |
| 505 |
var rev string |
| 506 |
if a.Doc.HasField(c.opts.RevisionField) { |
| 507 |
rev = driver.UniqueString() |
| 508 |
ub = ub.Set(expression.Name(c.opts.RevisionField), expression.Value(rev)) |
| 509 |
} |
| 510 |
cb, err := c.precondition(a) |
| 511 |
if err != nil { |
| 512 |
return nil, err |
| 513 |
} |
| 514 |
ce, err := expression.NewBuilder().WithCondition(*cb).WithUpdate(ub).Build() |
| 515 |
if err != nil { |
| 516 |
return nil, err |
| 517 |
} |
| 518 |
up := &dyn2Types.Update{ |
| 519 |
TableName: &c.table, |
| 520 |
Key: av.Value, |
| 521 |
ConditionExpression: ce.Condition(), |
| 522 |
UpdateExpression: ce.Update(), |
| 523 |
ExpressionAttributeNames: ce.Names(), |
| 524 |
ExpressionAttributeValues: ce.Values(), |
| 525 |
} |
| 526 |
return &writeOp{ |
| 527 |
action: a, |
| 528 |
writeItem: dyn2Types.TransactWriteItem{Update: up}, |
| 529 |
newRevision: rev, |
| 530 |
run: func(ctx context.Context) error { |
| 531 |
in := &dyn.UpdateItemInput{ |
| 532 |
TableName: up.TableName, |
| 533 |
Key: up.Key, |
| 534 |
ConditionExpression: up.ConditionExpression, |
| 535 |
UpdateExpression: up.UpdateExpression, |
| 536 |
ExpressionAttributeNames: up.ExpressionAttributeNames, |
| 537 |
ExpressionAttributeValues: up.ExpressionAttributeValues, |
| 538 |
} |
| 539 |
if opts.BeforeDo != nil { |
| 540 |
if err := opts.BeforeDo(driver.AsFunc(in)); err != nil { |
| 541 |
return err |
| 542 |
} |
| 543 |
} |
| 544 |
_, err := c.db.UpdateItem(ctx, in) |
| 545 |
return err |
| 546 |
}, |
| 547 |
}, nil |
| 548 |
} |
| 549 |
|
| 550 |
// Handle the effects of successful execution. |
| 551 |
func (c *collection) onSuccess(op *writeOp) error { |
| 552 |
// Set the new partition key (if any) and the new revision into the user's document. |
| 553 |
if op.newPartitionKey != "" { |
| 554 |
_ = op.action.Doc.SetField(c.partitionKey, op.newPartitionKey) // cannot fail |
| 555 |
} |
| 556 |
if op.newRevision != "" { |
| 557 |
return op.action.Doc.SetField(c.opts.RevisionField, op.newRevision) |
| 558 |
} |
| 559 |
return nil |
| 560 |
} |
| 561 |
|
| 562 |
func (c *collection) missingKeyField(m map[string]dyn2Types.AttributeValue) string { |
| 563 |
v, ok := m[c.partitionKey] |
| 564 |
if !ok { |
| 565 |
return c.partitionKey |
| 566 |
} |
| 567 |
if n, ok := v.(*dyn2Types.AttributeValueMemberNULL); ok && n.Value { |
| 568 |
return c.partitionKey |
| 569 |
} |
| 570 |
|
| 571 |
if c.sortKey != "" { |
| 572 |
v, ok := m[c.sortKey] |
| 573 |
if !ok { |
| 574 |
return c.sortKey |
| 575 |
} |
| 576 |
if n, ok := v.(*dyn2Types.AttributeValueMemberNULL); ok && n.Value { |
| 577 |
return c.sortKey |
| 578 |
} |
| 579 |
} |
| 580 |
|
| 581 |
return "" |
| 582 |
} |
| 583 |
|
| 584 |
// Construct the precondition for the action. |
| 585 |
func (c *collection) precondition(a *driver.Action) (*expression.ConditionBuilder, error) { |
| 586 |
switch a.Kind { |
| 587 |
case driver.Create: |
| 588 |
// Precondition: the document doesn't already exist. (Precisely: the partitionKey |
| 589 |
// field is not on the document.) |
| 590 |
c := expression.AttributeNotExists(expression.Name(c.partitionKey)) |
| 591 |
return &c, nil |
| 592 |
case driver.Replace, driver.Update: |
| 593 |
// Precondition: the revision matches, or if there is no revision, then |
| 594 |
// the document exists. |
| 595 |
cb, err := revisionPrecondition(a.Doc, c.opts.RevisionField) |
| 596 |
if err != nil { |
| 597 |
return nil, err |
| 598 |
} |
| 599 |
if cb == nil { |
| 600 |
c := expression.AttributeExists(expression.Name(c.partitionKey)) |
| 601 |
cb = &c |
| 602 |
} |
| 603 |
return cb, nil |
| 604 |
case driver.Put, driver.Delete: |
| 605 |
// Precondition: the revision matches, if any. |
| 606 |
return revisionPrecondition(a.Doc, c.opts.RevisionField) |
| 607 |
case driver.Get: |
| 608 |
// No preconditions on a Get. |
| 609 |
return nil, nil |
| 610 |
default: |
| 611 |
panic("bad action kind") |
| 612 |
} |
| 613 |
} |
| 614 |
|
| 615 |
// revisionPrecondition returns a DynamoDB expression that asserts that the |
| 616 |
// stored document's revision matches the revision of doc. |
| 617 |
func revisionPrecondition(doc driver.Document, revField string) (*expression.ConditionBuilder, error) { |
| 618 |
v, err := doc.GetField(revField) |
| 619 |
if err != nil { // field not present |
| 620 |
return nil, nil |
| 621 |
} |
| 622 |
if v == nil { // field is present, but nil |
| 623 |
return nil, nil |
| 624 |
} |
| 625 |
rev, ok := v.(string) |
| 626 |
if !ok { |
| 627 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, |
| 628 |
"%s field contains wrong type: got %T, want string", |
| 629 |
revField, v) |
| 630 |
} |
| 631 |
if rev == "" { |
| 632 |
return nil, nil |
| 633 |
} |
| 634 |
// Value encodes rev to an attribute value. |
| 635 |
cb := expression.Name(revField).Equal(expression.Value(rev)) |
| 636 |
return &cb, nil |
| 637 |
} |
| 638 |
|
| 639 |
// transactWrite executes the write actions atomically: either they all succeed or they all fail together. |
| 640 |
func (c *collection) transactWrite(ctx context.Context, actions []*driver.Action, errs []error, opts *driver.RunActionsOptions) { |
| 641 |
if len(actions) == 0 { |
| 642 |
return |
| 643 |
} |
| 644 |
// all actions will fail atomically even if a single action fails |
| 645 |
setErr := func(err error) { |
| 646 |
for _, a := range actions { |
| 647 |
errs[a.Index] = err |
| 648 |
} |
| 649 |
} |
| 650 |
|
| 651 |
tws := make([]dyn2Types.TransactWriteItem, 0, len(actions)) |
| 652 |
var ops []*writeOp |
| 653 |
for _, w := range actions { |
| 654 |
op, err := c.newWriteOp(w, opts) |
| 655 |
if err != nil { |
| 656 |
setErr(err) |
| 657 |
return |
| 658 |
} else { |
| 659 |
ops = append(ops, op) |
| 660 |
tws = append(tws, op.writeItem) |
| 661 |
} |
| 662 |
} |
| 663 |
|
| 664 |
in := &dyn.TransactWriteItemsInput{ |
| 665 |
ClientRequestToken: aws.String(driver.UniqueString()), |
| 666 |
TransactItems: tws, |
| 667 |
} |
| 668 |
|
| 669 |
if opts.BeforeDo != nil { |
| 670 |
asFunc := func(i any) bool { |
| 671 |
p, ok := i.(**dyn.TransactWriteItemsInput) |
| 672 |
if !ok { |
| 673 |
return false |
| 674 |
} |
| 675 |
*p = in |
| 676 |
return true |
| 677 |
} |
| 678 |
if err := opts.BeforeDo(asFunc); err != nil { |
| 679 |
setErr(err) |
| 680 |
return |
| 681 |
} |
| 682 |
} |
| 683 |
if _, err := c.db.TransactWriteItems(ctx, in); err != nil { |
| 684 |
setErr(err) |
| 685 |
return |
| 686 |
} |
| 687 |
for _, op := range ops { |
| 688 |
errs[op.action.Index] = c.onSuccess(op) |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
// RevisionToBytes implements driver.RevisionToBytes. |
| 693 |
func (c *collection) RevisionToBytes(rev any) ([]byte, error) { |
| 694 |
s, ok := rev.(string) |
| 695 |
if !ok { |
| 696 |
return nil, gcerr.Newf(gcerr.InvalidArgument, nil, "revision %v of type %[1]T is not a string", rev) |
| 697 |
} |
| 698 |
return []byte(s), nil |
| 699 |
} |
| 700 |
|
| 701 |
// BytesToRevision implements driver.BytesToRevision. |
| 702 |
func (c *collection) BytesToRevision(b []byte) (any, error) { |
| 703 |
return string(b), nil |
| 704 |
} |
| 705 |
|
| 706 |
func (c *collection) As(i any) bool { |
| 707 |
p, ok := i.(**dyn.Client) |
| 708 |
if !ok { |
| 709 |
return false |
| 710 |
} |
| 711 |
*p = c.db |
| 712 |
return true |
| 713 |
} |
| 714 |
|
| 715 |
// ErrorAs implements driver.Collection.ErrorAs. |
| 716 |
func (c *collection) ErrorAs(err error, i any) bool { |
| 717 |
e, ok := err.(*smithy.OperationError) |
| 718 |
if !ok { |
| 719 |
return false |
| 720 |
} |
| 721 |
p, ok := i.(*smithy.OperationError) |
| 722 |
if !ok { |
| 723 |
return false |
| 724 |
} |
| 725 |
*p = *e |
| 726 |
return true |
| 727 |
} |
| 728 |
|
| 729 |
func (c *collection) ErrorCode(err error) gcerrors.ErrorCode { |
| 730 |
|
| 731 |
var ( |
| 732 |
conditionalCheckFailedException *dyn2Types.ConditionalCheckFailedException |
| 733 |
idempotentParameterMismatchException *dyn2Types.IdempotentParameterMismatchException |
| 734 |
internalServerError *dyn2Types.InternalServerError |
| 735 |
itemCollectionSizeLimitExceededException *dyn2Types.ItemCollectionSizeLimitExceededException |
| 736 |
provisionedThroughputExceededException *dyn2Types.ProvisionedThroughputExceededException |
| 737 |
requestLimitExceeded *dyn2Types.RequestLimitExceeded |
| 738 |
resourceNotFoundException *dyn2Types.ResourceNotFoundException |
| 739 |
transactionCanceledException *dyn2Types.TransactionCanceledException |
| 740 |
transactionConflictException *dyn2Types.TransactionConflictException |
| 741 |
transactionInProgressException *dyn2Types.TransactionInProgressException |
| 742 |
) |
| 743 |
|
| 744 |
switch { |
| 745 |
case errors.As(err, &conditionalCheckFailedException): |
| 746 |
return gcerrors.FailedPrecondition |
| 747 |
case errors.As(err, &idempotentParameterMismatchException): |
| 748 |
return gcerrors.InvalidArgument |
| 749 |
case errors.As(err, &internalServerError): |
| 750 |
return gcerrors.Internal |
| 751 |
case errors.As(err, &itemCollectionSizeLimitExceededException): |
| 752 |
return gcerrors.ResourceExhausted |
| 753 |
case errors.As(err, &provisionedThroughputExceededException): |
| 754 |
return gcerrors.ResourceExhausted |
| 755 |
case errors.As(err, &requestLimitExceeded): |
| 756 |
return gcerrors.ResourceExhausted |
| 757 |
case errors.As(err, &resourceNotFoundException): |
| 758 |
return gcerrors.NotFound |
| 759 |
case errors.As(err, &transactionCanceledException): |
| 760 |
return gcerrors.FailedPrecondition |
| 761 |
case errors.As(err, &transactionConflictException): |
| 762 |
return gcerrors.Internal |
| 763 |
case errors.As(err, &transactionInProgressException): |
| 764 |
return gcerrors.InvalidArgument |
| 765 |
} |
| 766 |
|
| 767 |
for k, errCode := range errorCodeMap { |
| 768 |
if strings.Contains(err.Error(), k) { |
| 769 |
return errCode |
| 770 |
} |
| 771 |
} |
| 772 |
|
| 773 |
return gcerrors.Unknown |
| 774 |
} |
| 775 |
|
| 776 |
var errorCodeMap = map[string]gcerrors.ErrorCode{ |
| 777 |
// handled by type above |
| 778 |
// "ConditionalCheckFailedException": gcerrors.FailedPrecondition, |
| 779 |
// "IdempotentParameterMismatchException": gcerrors.InvalidArgument, |
| 780 |
// "InternalServerErrorException": gcerrors.Internal, |
| 781 |
// "ItemCollectionSizeLimitExceededException": gcerrors.ResourceExhausted, |
| 782 |
// "ProvisionedThroughputExceededException": gcerrors.ResourceExhausted, |
| 783 |
// "RequestLimitExceededException": gcerrors.ResourceExhausted, |
| 784 |
// "ResourceNotFoundException": gcerrors.NotFound, |
| 785 |
// "TransactionCanceledException": gcerrors.FailedPrecondition, |
| 786 |
// "TransactionConflictException": gcerrors.Internal, |
| 787 |
// "TransactionInProgressException": gcerrors.InvalidArgument, |
| 788 |
|
| 789 |
// V2 doesn't have a type for this, inspect message instead |
| 790 |
"ValidationException": gcerrors.InvalidArgument, |
| 791 |
} |
| 792 |
|
| 793 |
// Close implements driver.Collection.Close. |
| 794 |
func (c *collection) Close() error { return nil } |