github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/barriers/barrier.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package barriers 19 20 import ( 21 "github.com/aacfactory/configures" 22 "github.com/aacfactory/errors" 23 "github.com/aacfactory/fns/commons/bytex" 24 "github.com/aacfactory/fns/commons/objects" 25 "github.com/aacfactory/fns/context" 26 "golang.org/x/sync/singleflight" 27 ) 28 29 type Result interface { 30 objects.Object 31 } 32 33 type Barrier interface { 34 Do(ctx context.Context, key []byte, fn func() (result interface{}, err error)) (result Result, err error) 35 } 36 37 type BarrierBuilder interface { 38 Build(ctx context.Context, config configures.Config) (barrier Barrier, err error) 39 } 40 41 func New() (b Barrier) { 42 b = &barrier{ 43 group: new(singleflight.Group), 44 } 45 return 46 } 47 48 // Barrier 49 // @barrier 50 // 当@authorization 存在时,则key为 services.HashRequest(r, services.HashRequestWithToken()) 51 type barrier struct { 52 group *singleflight.Group 53 } 54 55 func (b *barrier) Do(_ context.Context, key []byte, fn func() (result interface{}, err error)) (r Result, err error) { 56 if len(key) == 0 { 57 key = []byte{'-'} 58 } 59 groupKey := bytex.ToString(key) 60 v, doErr, _ := b.group.Do(bytex.ToString(key), func() (v interface{}, err error) { 61 v, err = fn() 62 return 63 }) 64 b.group.Forget(groupKey) 65 if doErr != nil { 66 err = errors.Wrap(doErr) 67 return 68 } 69 r = objects.New(v) 70 return 71 }