You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

277 lines
9.2 KiB

  1. // Copyright 2017 Google LLC
  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. // http://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. package firestore
  15. import (
  16. "errors"
  17. pb "google.golang.org/genproto/googleapis/firestore/v1beta1"
  18. gax "github.com/googleapis/gax-go"
  19. "golang.org/x/net/context"
  20. "google.golang.org/grpc"
  21. "google.golang.org/grpc/codes"
  22. "google.golang.org/grpc/status"
  23. )
  24. // Transaction represents a Firestore transaction.
  25. type Transaction struct {
  26. c *Client
  27. ctx context.Context
  28. id []byte
  29. writes []*pb.Write
  30. maxAttempts int
  31. readOnly bool
  32. readAfterWrite bool
  33. }
  34. // A TransactionOption is an option passed to Client.Transaction.
  35. type TransactionOption interface {
  36. config(t *Transaction)
  37. }
  38. // MaxAttempts is a TransactionOption that configures the maximum number of times to
  39. // try a transaction. In defaults to DefaultTransactionMaxAttempts.
  40. func MaxAttempts(n int) maxAttempts { return maxAttempts(n) }
  41. type maxAttempts int
  42. func (m maxAttempts) config(t *Transaction) { t.maxAttempts = int(m) }
  43. // DefaultTransactionMaxAttempts is the default number of times to attempt a transaction.
  44. const DefaultTransactionMaxAttempts = 5
  45. // ReadOnly is a TransactionOption that makes the transaction read-only. Read-only
  46. // transactions cannot issue write operations, but are more efficient.
  47. var ReadOnly = ro{}
  48. type ro struct{}
  49. func (ro) config(t *Transaction) { t.readOnly = true }
  50. var (
  51. // ErrConcurrentTransaction is returned when a transaction is rolled back due
  52. // to a conflict with a concurrent transaction.
  53. ErrConcurrentTransaction = errors.New("firestore: concurrent transaction")
  54. // Defined here for testing.
  55. errReadAfterWrite = errors.New("firestore: read after write in transaction")
  56. errWriteReadOnly = errors.New("firestore: write in read-only transaction")
  57. errNonTransactionalOp = errors.New("firestore: non-transactional operation inside a transaction")
  58. errNestedTransaction = errors.New("firestore: nested transaction")
  59. )
  60. type transactionInProgressKey struct{}
  61. func checkTransaction(ctx context.Context) error {
  62. if ctx.Value(transactionInProgressKey{}) != nil {
  63. return errNonTransactionalOp
  64. }
  65. return nil
  66. }
  67. // RunTransaction runs f in a transaction. f should use the transaction it is given
  68. // for all Firestore operations. For any operation requiring a context, f should use
  69. // the context it is passed, not the first argument to RunTransaction.
  70. //
  71. // f must not call Commit or Rollback on the provided Transaction.
  72. //
  73. // If f returns nil, RunTransaction commits the transaction. If the commit fails due
  74. // to a conflicting transaction, RunTransaction retries f. It gives up and returns
  75. // ErrConcurrentTransaction after a number of attempts that can be configured with
  76. // the MaxAttempts option. If the commit succeeds, RunTransaction returns a nil error.
  77. //
  78. // If f returns non-nil, then the transaction will be rolled back and
  79. // this method will return the same error. The function f is not retried.
  80. //
  81. // Note that when f returns, the transaction is not committed. Calling code
  82. // must not assume that any of f's changes have been committed until
  83. // RunTransaction returns nil.
  84. //
  85. // Since f may be called more than once, f should usually be idempotent – that is, it
  86. // should have the same result when called multiple times.
  87. func (c *Client) RunTransaction(ctx context.Context, f func(context.Context, *Transaction) error, opts ...TransactionOption) error {
  88. if ctx.Value(transactionInProgressKey{}) != nil {
  89. return errNestedTransaction
  90. }
  91. db := c.path()
  92. t := &Transaction{
  93. c: c,
  94. ctx: withResourceHeader(ctx, db),
  95. maxAttempts: DefaultTransactionMaxAttempts,
  96. }
  97. for _, opt := range opts {
  98. opt.config(t)
  99. }
  100. var txOpts *pb.TransactionOptions
  101. if t.readOnly {
  102. txOpts = &pb.TransactionOptions{
  103. Mode: &pb.TransactionOptions_ReadOnly_{&pb.TransactionOptions_ReadOnly{}},
  104. }
  105. }
  106. var backoff gax.Backoff
  107. // TODO(jba): use other than the standard backoff parameters?
  108. // TODO(jba): get backoff time from gRPC trailer metadata? See extractRetryDelay in https://code.googlesource.com/gocloud/+/master/spanner/retry.go.
  109. var err error
  110. for i := 0; i < t.maxAttempts; i++ {
  111. var res *pb.BeginTransactionResponse
  112. res, err = t.c.c.BeginTransaction(t.ctx, &pb.BeginTransactionRequest{
  113. Database: db,
  114. Options: txOpts,
  115. })
  116. if err != nil {
  117. return err
  118. }
  119. t.id = res.Transaction
  120. err = f(context.WithValue(ctx, transactionInProgressKey{}, 1), t)
  121. // Read after write can only be checked client-side, so we make sure to check
  122. // even if the user does not.
  123. if err == nil && t.readAfterWrite {
  124. err = errReadAfterWrite
  125. }
  126. if err != nil {
  127. t.rollback()
  128. // Prefer f's returned error to rollback error.
  129. return err
  130. }
  131. _, err = t.c.c.Commit(t.ctx, &pb.CommitRequest{
  132. Database: t.c.path(),
  133. Writes: t.writes,
  134. Transaction: t.id,
  135. })
  136. // If a read-write transaction returns Aborted, retry.
  137. // On success or other failures, return here.
  138. if t.readOnly || grpc.Code(err) != codes.Aborted {
  139. // According to the Firestore team, we should not roll back here
  140. // if err != nil. But spanner does.
  141. // See https://code.googlesource.com/gocloud/+/master/spanner/transaction.go#740.
  142. return err
  143. }
  144. if txOpts == nil {
  145. // txOpts can only be nil if is the first retry of a read-write transaction.
  146. // (It is only set here and in the body of "if t.readOnly" above.)
  147. // Mention the transaction ID in BeginTransaction so the service
  148. // knows it is a retry.
  149. txOpts = &pb.TransactionOptions{
  150. Mode: &pb.TransactionOptions_ReadWrite_{
  151. &pb.TransactionOptions_ReadWrite{RetryTransaction: t.id},
  152. },
  153. }
  154. }
  155. // Use exponential backoff to avoid contention with other running
  156. // transactions.
  157. if cerr := sleep(ctx, backoff.Pause()); cerr != nil {
  158. err = cerr
  159. break
  160. }
  161. }
  162. // If we run out of retries, return the last error we saw (which should
  163. // be the Aborted from Commit, or a context error).
  164. if err != nil {
  165. t.rollback()
  166. }
  167. return err
  168. }
  169. func (t *Transaction) rollback() {
  170. _ = t.c.c.Rollback(t.ctx, &pb.RollbackRequest{
  171. Database: t.c.path(),
  172. Transaction: t.id,
  173. })
  174. // Ignore the rollback error.
  175. // TODO(jba): Log it?
  176. // Note: Rollback is idempotent so it will be retried by the gapic layer.
  177. }
  178. // Get gets the document in the context of the transaction. The transaction holds a
  179. // pessimistic lock on the returned document.
  180. func (t *Transaction) Get(dr *DocumentRef) (*DocumentSnapshot, error) {
  181. docsnaps, err := t.GetAll([]*DocumentRef{dr})
  182. if err != nil {
  183. return nil, err
  184. }
  185. ds := docsnaps[0]
  186. if !ds.Exists() {
  187. return ds, status.Errorf(codes.NotFound, "%q not found", dr.Path)
  188. }
  189. return ds, nil
  190. }
  191. // GetAll retrieves multiple documents with a single call. The DocumentSnapshots are
  192. // returned in the order of the given DocumentRefs. If a document is not present, the
  193. // corresponding DocumentSnapshot's Exists method will return false. The transaction
  194. // holds a pessimistic lock on all of the returned documents.
  195. func (t *Transaction) GetAll(drs []*DocumentRef) ([]*DocumentSnapshot, error) {
  196. if len(t.writes) > 0 {
  197. t.readAfterWrite = true
  198. return nil, errReadAfterWrite
  199. }
  200. return t.c.getAll(t.ctx, drs, t.id)
  201. }
  202. // A Queryer is a Query or a CollectionRef. CollectionRefs act as queries whose
  203. // results are all the documents in the collection.
  204. type Queryer interface {
  205. query() *Query
  206. }
  207. // Documents returns a DocumentIterator based on given Query or CollectionRef. The
  208. // results will be in the context of the transaction.
  209. func (t *Transaction) Documents(q Queryer) *DocumentIterator {
  210. if len(t.writes) > 0 {
  211. t.readAfterWrite = true
  212. return &DocumentIterator{err: errReadAfterWrite}
  213. }
  214. return &DocumentIterator{
  215. iter: newQueryDocumentIterator(t.ctx, q.query(), t.id),
  216. }
  217. }
  218. // Create adds a Create operation to the Transaction.
  219. // See DocumentRef.Create for details.
  220. func (t *Transaction) Create(dr *DocumentRef, data interface{}) error {
  221. return t.addWrites(dr.newCreateWrites(data))
  222. }
  223. // Set adds a Set operation to the Transaction.
  224. // See DocumentRef.Set for details.
  225. func (t *Transaction) Set(dr *DocumentRef, data interface{}, opts ...SetOption) error {
  226. return t.addWrites(dr.newSetWrites(data, opts))
  227. }
  228. // Delete adds a Delete operation to the Transaction.
  229. // See DocumentRef.Delete for details.
  230. func (t *Transaction) Delete(dr *DocumentRef, opts ...Precondition) error {
  231. return t.addWrites(dr.newDeleteWrites(opts))
  232. }
  233. // Update adds a new Update operation to the Transaction.
  234. // See DocumentRef.Update for details.
  235. func (t *Transaction) Update(dr *DocumentRef, data []Update, opts ...Precondition) error {
  236. return t.addWrites(dr.newUpdatePathWrites(data, opts))
  237. }
  238. func (t *Transaction) addWrites(ws []*pb.Write, err error) error {
  239. if t.readOnly {
  240. return errWriteReadOnly
  241. }
  242. if err != nil {
  243. return err
  244. }
  245. t.writes = append(t.writes, ws...)
  246. return nil
  247. }