go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/external.go (about) 1 // Copyright 2015 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 clock 16 17 import ( 18 "context" 19 "time" 20 ) 21 22 // Unique value for clock key. 23 var clockKey = "clock.Clock" 24 25 // Factory is a generator function that produces a Clock instnace. 26 type Factory func(context.Context) Clock 27 28 // SetFactory creates a new Context using the supplied Clock factory. 29 func SetFactory(ctx context.Context, f Factory) context.Context { 30 return context.WithValue(ctx, &clockKey, f) 31 } 32 33 // Set creates a new Context using the supplied Clock. 34 func Set(ctx context.Context, c Clock) context.Context { 35 return SetFactory(ctx, func(context.Context) Clock { return c }) 36 } 37 38 // Get returns the Clock set in the supplied Context, defaulting to 39 // SystemClock() if none is set. 40 func Get(ctx context.Context) (clock Clock) { 41 if v := ctx.Value(&clockKey); v != nil { 42 if f, ok := v.(Factory); ok { 43 clock = f(ctx) 44 } 45 } 46 if clock == nil { 47 clock = GetSystemClock() 48 } 49 return 50 } 51 52 // Now calls Clock.Now on the Clock instance stored in the supplied Context. 53 func Now(ctx context.Context) time.Time { 54 return Get(ctx).Now() 55 } 56 57 // Sleep calls Clock.Sleep on the Clock instance stored in the supplied Context. 58 func Sleep(ctx context.Context, d time.Duration) TimerResult { 59 return Get(ctx).Sleep(ctx, d) 60 } 61 62 // NewTimer calls Clock.NewTimer on the Clock instance stored in the supplied 63 // Context. 64 func NewTimer(ctx context.Context) Timer { 65 return Get(ctx).NewTimer(ctx) 66 } 67 68 // After waits a duration using the Clock instance stored in the supplied 69 // Context. Then sends the current time over the returned channel. 70 // 71 // If the supplied Context is canceled, the timer will expire immediately. 72 func After(ctx context.Context, d time.Duration) <-chan TimerResult { 73 return after(ctx, Get(ctx), d) 74 } 75 76 func after(ctx context.Context, c Clock, d time.Duration) <-chan TimerResult { 77 t := c.NewTimer(ctx) 78 t.Reset(d) 79 return t.GetC() 80 } 81 82 // Since is an equivalent of time.Since. 83 func Since(ctx context.Context, t time.Time) time.Duration { 84 return Now(ctx).Sub(t) 85 } 86 87 // Until is an equivalent of time.Until. 88 func Until(ctx context.Context, t time.Time) time.Duration { 89 return t.Sub(Now(ctx)) 90 }