go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/server/dsmapper/utils.go (about) 1 // Copyright 2018 The LUCI 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 // 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 15 package dsmapper 16 17 import ( 18 "context" 19 20 "go.chromium.org/luci/common/logging" 21 "go.chromium.org/luci/common/retry/transient" 22 "go.chromium.org/luci/gae/service/datastore" 23 24 "go.chromium.org/luci/server/dsmapper/dsmapperpb" 25 ) 26 27 // runTxn runs a datastore transaction retrying the body on transient errors or 28 // when encountering a commit conflict. 29 func runTxn(ctx context.Context, cb func(context.Context) error) error { 30 var attempt int 31 var innerErr error 32 33 err := datastore.RunInTransaction(ctx, func(ctx context.Context) error { 34 attempt++ 35 if attempt != 1 { 36 if innerErr != nil { 37 logging.Warningf(ctx, "Retrying the transaction after the error: %s", innerErr) 38 } else { 39 logging.Warningf(ctx, "Retrying the transaction: failed to commit") 40 } 41 } 42 innerErr = cb(ctx) 43 if transient.Tag.In(innerErr) { 44 return datastore.ErrConcurrentTransaction // causes a retry 45 } 46 return innerErr 47 }, nil) 48 49 if err != nil { 50 logging.WithError(err).Errorf(ctx, "Transaction failed") 51 if innerErr != nil { 52 return innerErr 53 } 54 // Here it can only be a commit error (i.e. produced by RunInTransaction 55 // itself, not by its callback). We treat them as transient. 56 return transient.Tag.Apply(err) 57 } 58 59 return nil 60 } 61 62 func isFinalState(s dsmapperpb.State) bool { 63 return s == dsmapperpb.State_SUCCESS || s == dsmapperpb.State_FAIL || s == dsmapperpb.State_ABORTED 64 }