github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/runtime/context.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 runtime 19 20 import ( 21 "fmt" 22 "github.com/aacfactory/errors" 23 "github.com/aacfactory/fns/barriers" 24 "github.com/aacfactory/fns/commons/versions" 25 "github.com/aacfactory/fns/context" 26 "github.com/aacfactory/fns/services" 27 "github.com/aacfactory/fns/shareds" 28 "github.com/aacfactory/workers" 29 "time" 30 ) 31 32 var ( 33 contextKey = []byte("@fns:context:runtime") 34 ) 35 36 func With(ctx context.Context, rt *Runtime) context.Context { 37 ctx.SetLocalValue(contextKey, rt) 38 return ctx 39 } 40 41 func Load(ctx context.Context) *Runtime { 42 v := ctx.LocalValue(contextKey) 43 if v == nil { 44 panic(fmt.Sprintf("%+v", errors.Warning("fns: there is no runtime in context"))) 45 return nil 46 } 47 rt, ok := v.(*Runtime) 48 if !ok { 49 panic(fmt.Sprintf("%+v", errors.Warning("fns: runtime in context is not github.com/aacfactory/fns/runtime.Runtime"))) 50 return nil 51 } 52 return rt 53 } 54 55 func AppId(ctx context.Context) []byte { 56 return Load(ctx).AppId() 57 } 58 59 func AppName(ctx context.Context) string { 60 return Load(ctx).AppName() 61 } 62 63 func AppVersion(ctx context.Context) versions.Version { 64 return Load(ctx).AppVersion() 65 } 66 67 func Endpoints(ctx context.Context) services.Endpoints { 68 rt := Load(ctx) 69 return rt.Endpoints() 70 } 71 72 func TryExecute(ctx context.Context, task workers.Task) bool { 73 rt := Load(ctx) 74 return rt.TryExecute(context.TODO(), task) 75 } 76 77 func Execute(ctx context.Context, task workers.Task) { 78 rt := Load(ctx) 79 rt.Execute(context.TODO(), task) 80 } 81 82 func Barrier(ctx context.Context, key []byte, fn func() (result interface{}, err error)) (result barriers.Result, err error) { 83 rt := Load(ctx) 84 barrier := rt.Barrier() 85 result, err = barrier.Do(ctx, key, fn) 86 return 87 } 88 89 func AcquireLocker(ctx context.Context, key []byte, ttl time.Duration) (locker shareds.Locker, err error) { 90 rt := Load(ctx) 91 locker, err = rt.Shared().Lockers().Acquire(ctx, key, ttl) 92 return 93 } 94 95 func SharedStore(ctx context.Context) (store shareds.Store) { 96 rt := Load(ctx) 97 store = rt.Shared().Store() 98 return 99 }