1 /* 2 Copyright The ORAS Authors. 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 syncutil 16 17 import "context" 18 19 // Once is an object that will perform exactly one action. 20 // Unlike sync.Once, this Once allowes the action to have return values. 21 type Once struct { 22 result interface{} 23 err error 24 status chan bool 25 } 26 27 // NewOnce creates a new Once instance. 28 func NewOnce() *Once { 29 status := make(chan bool, 1) 30 status <- true 31 return &Once{ 32 status: status, 33 } 34 } 35 36 // Do calls the function f if and only if Do is being called first time or all 37 // previous function calls are cancelled, deadline exceeded, or panicking. 38 // When `once.Do(ctx, f)` is called multiple times, the return value of the 39 // first call of the function f is stored, and is directly returned for other 40 // calls. 41 // Besides the return value of the function f, including the error, Do returns 42 // true if the function f passed is called first and is not cancelled, deadline 43 // exceeded, or panicking. Otherwise, returns false. 44 func (o *Once) Do(ctx context.Context, f func() (interface{}, error)) (bool, interface{}, error) { 45 defer func() { 46 if r := recover(); r != nil { 47 o.status <- true 48 panic(r) 49 } 50 }() 51 for { 52 select { 53 case inProgress := <-o.status: 54 if !inProgress { 55 return false, o.result, o.err 56 } 57 result, err := f() 58 if err == context.Canceled || err == context.DeadlineExceeded { 59 o.status <- true 60 return false, nil, err 61 } 62 o.result, o.err = result, err 63 close(o.status) 64 return true, result, err 65 case <-ctx.Done(): 66 return false, nil, ctx.Err() 67 } 68 } 69 } 70