github.com/m3db/m3@v1.5.0/src/query/source/source.go (about) 1 // Copyright (c) 2021 Uber Technologies, Inc. 2 // 3 // Permission is hereby granted, free of charge, to any person obtaining a copy 4 // of this software and associated documentation files (the "Software"), to deal 5 // in the Software without restriction, including without limitation the rights 6 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 // copies of the Software, and to permit persons to whom the Software is 8 // furnished to do so, subject to the following conditions: 9 // 10 // The above copyright notice and this permission notice shall be included in 11 // all copies or substantial portions of the Software. 12 // 13 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 // THE SOFTWARE. 20 21 // Package source identifies the source of query requests. 22 package source 23 24 import ( 25 "context" 26 ) 27 28 type key int 29 30 const ( 31 typedKey key = iota 32 rawKey 33 ) 34 35 // Deserializer deserializes the raw source bytes into a type for easier use. 36 // The raw source can be nil and the Deserializer can return a typed empty value for the application. 37 type Deserializer func([]byte) (interface{}, error) 38 39 // NewContext returns a new context with the source bytes as a value if the source is non-nil. 40 // If a non-nil deserializer is provided an additional typed value is added for easier use. 41 func NewContext(ctx context.Context, source []byte, deserialize Deserializer) (context.Context, error) { 42 if source == nil { 43 return ctx, nil 44 } 45 ctx = context.WithValue(ctx, rawKey, source) 46 if deserialize != nil { 47 typed, err := deserialize(source) 48 if err != nil { 49 return nil, err 50 } 51 ctx = context.WithValue(ctx, typedKey, typed) 52 } 53 return ctx, nil 54 } 55 56 // FromContext extracts the typed source, or false if it doesn't exist. 57 func FromContext(ctx context.Context) (interface{}, bool) { 58 typed := ctx.Value(typedKey) 59 if typed == nil { 60 return nil, false 61 } 62 return typed, true 63 } 64 65 // RawFromContext extracts the raw bytes of the source, or false if it doesn't exist. 66 // This is used by middleware to propagate the source across API boundaries. Application code should use FromContext. 67 func RawFromContext(ctx context.Context) ([]byte, bool) { 68 b, ok := ctx.Value(rawKey).([]byte) 69 return b, ok 70 }