knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/injection/context.go (about) 1 /* 2 Copyright 2019 The Knative Authors 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 package injection 18 19 import ( 20 "context" 21 22 "k8s.io/client-go/rest" 23 ) 24 25 // nsKey is the key that namespaces are associated with on 26 // contexts returned by WithNamespaceScope. 27 type nsKey struct{} 28 29 // WithNamespaceScope associates a namespace scoping with the 30 // provided context, which will scope the informers produced 31 // by the downstream informer factories. 32 func WithNamespaceScope(ctx context.Context, namespace string) context.Context { 33 return context.WithValue(ctx, nsKey{}, namespace) 34 } 35 36 // HasNamespaceScope determines whether the provided context has 37 // been scoped to a particular namespace. 38 func HasNamespaceScope(ctx context.Context) bool { 39 return GetNamespaceScope(ctx) != "" 40 } 41 42 // GetNamespaceScope accesses the namespace associated with the 43 // provided context. This should be called when the injection 44 // logic is setting up shared informer factories. 45 func GetNamespaceScope(ctx context.Context) string { 46 value := ctx.Value(nsKey{}) 47 if value == nil { 48 return "" 49 } 50 return value.(string) 51 } 52 53 // cfgKey is the key that the config is associated with. 54 type cfgKey struct{} 55 56 // WithConfig associates a given config with the context. 57 func WithConfig(ctx context.Context, cfg *rest.Config) context.Context { 58 return context.WithValue(ctx, cfgKey{}, cfg) 59 } 60 61 // GetConfig gets the current config from the context. 62 func GetConfig(ctx context.Context) *rest.Config { 63 value := ctx.Value(cfgKey{}) 64 if value == nil { 65 return nil 66 } 67 return value.(*rest.Config) 68 } 69 70 // rvKey is the key that the resource version is associated with. 71 type rvKey struct{} 72 73 // WithResourceVersion associates a resource version with the context. 74 func WithResourceVersion(ctx context.Context, resourceVersion string) context.Context { 75 return context.WithValue(ctx, rvKey{}, resourceVersion) 76 } 77 78 // GetResourceVersion gets the resource version associated with the context. 79 func GetResourceVersion(ctx context.Context) string { 80 value := ctx.Value(rvKey{}) 81 if value == nil { 82 return "" 83 } 84 return value.(string) 85 }