go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/resultdb/internal/resultcount/resultcount.go (about) 1 // Copyright 2020 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 resultcount 16 17 import ( 18 "context" 19 20 "cloud.google.com/go/spanner" 21 "google.golang.org/grpc/codes" 22 23 "go.chromium.org/luci/common/data/rand/mathrand" 24 "go.chromium.org/luci/server/span" 25 26 "go.chromium.org/luci/resultdb/internal/invocations" 27 "go.chromium.org/luci/resultdb/internal/spanutil" 28 ) 29 30 // Total number of shards for each invocation in TestResultCount table. 31 const nShards = 10 32 33 // IncrementTestResultCount increases the count in one random shard of the invocation. 34 func IncrementTestResultCount(ctx context.Context, id invocations.ID, delta int64) error { 35 if delta == 0 { 36 return nil 37 } 38 39 shardId := mathrand.Int63n(ctx, nShards) 40 var count spanner.NullInt64 41 err := spanutil.ReadRow(ctx, "TestResultCounts", id.Key(shardId), map[string]any{ 42 "TestResultCount": &count, 43 }) 44 if err != nil && spanner.ErrCode(err) != codes.NotFound { 45 return err 46 } 47 48 span.BufferWrite(ctx, spanutil.InsertOrUpdateMap("TestResultCounts", map[string]any{ 49 "InvocationId": id, 50 "ShardId": shardId, 51 "TestResultCount": count.Int64 + delta, 52 })) 53 return nil 54 } 55 56 // ReadTestResultCount returns the total number of test results of requested 57 // invocations. 58 func ReadTestResultCount(ctx context.Context, ids invocations.IDSet) (int64, error) { 59 if len(ids) == 0 { 60 return 0, nil 61 } 62 63 st := spanner.NewStatement(` 64 SELECT SUM(TestResultCount) 65 FROM TestResultCounts 66 WHERE InvocationId IN UNNEST(@invIDs) 67 `) 68 st.Params = spanutil.ToSpannerMap(map[string]any{ 69 "invIDs": ids, 70 }) 71 var count spanner.NullInt64 72 err := spanutil.QueryFirstRow(ctx, st, &count) 73 return count.Int64, err 74 }