go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/rpc/pagination/size.go (about) 1 // Copyright 2021 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 pagination 16 17 import ( 18 "fmt" 19 20 "google.golang.org/grpc/codes" 21 22 "go.chromium.org/luci/grpc/appstatus" 23 ) 24 25 // InvalidPageSize annotates the error with InvalidArgument appstatus. 26 func InvalidPageSize(err error) error { 27 return appstatus.Attachf(err, codes.InvalidArgument, "invalid page size, must be >= 0") 28 } 29 30 type requestWithPageSize interface { 31 GetPageSize() int32 32 } 33 34 // ValidatePageSize validates and caps page size from the given request. 35 func ValidatePageSize(req requestWithPageSize, defaultValue, maxValue int32) (int32, error) { 36 if defaultValue > maxValue { 37 panic(fmt.Errorf("invalid use: defaultValue %d must be <= maxValue %d", defaultValue, maxValue)) 38 } 39 switch v := req.GetPageSize(); { 40 case v < 0: 41 return 0, InvalidPageSize(fmt.Errorf("page_size %d", v)) 42 case v == 0: 43 return defaultValue, nil 44 case v < maxValue: 45 return v, nil 46 default: 47 return maxValue, nil 48 } 49 }