knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/observability/attributekey/key.go (about)

     1  /*
     2  Copyright 2025 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 attributekey
    18  
    19  import (
    20  	"fmt"
    21  
    22  	"go.opentelemetry.io/otel/attribute"
    23  )
    24  
    25  type ValueType interface {
    26  	string | bool | int64 | int | float64 |
    27  		[]string | []bool | []int64 | []int | []float64
    28  }
    29  
    30  type (
    31  	Type[T ValueType] string
    32  	String            = Type[string]
    33  	Bool              = Type[bool]
    34  	Int               = Type[int]
    35  	Int64             = Type[int64]
    36  	Float64           = Type[float64]
    37  )
    38  
    39  func (key Type[T]) With(val T) attribute.KeyValue {
    40  	k := string(key)
    41  
    42  	switch v := any(val).(type) {
    43  	case string:
    44  		return attribute.String(k, v)
    45  	case bool:
    46  		return attribute.Bool(k, v)
    47  	case int64:
    48  		return attribute.Int64(k, v)
    49  	case int:
    50  		return attribute.Int(k, v)
    51  	case float64:
    52  		return attribute.Float64(k, v)
    53  	case []string:
    54  		return attribute.StringSlice(k, v)
    55  	case []bool:
    56  		return attribute.BoolSlice(k, v)
    57  	case []int64:
    58  		return attribute.Int64Slice(k, v)
    59  	case []int:
    60  		return attribute.IntSlice(k, v)
    61  	case []float64:
    62  		return attribute.Float64Slice(k, v)
    63  	default:
    64  		// note - this can't happen due to type constraints
    65  		panic(fmt.Sprintf("unsupported attribute type: %T", v))
    66  	}
    67  }