123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- package tracestate
- import (
- "fmt"
- "regexp"
- )
- const (
- keyMaxSize = 256
- valueMaxSize = 256
- maxKeyValuePairs = 32
- )
- const (
- keyWithoutVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,255}`
- keyWithVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}`
- keyFormat = `(` + keyWithoutVendorFormat + `)|(` + keyWithVendorFormat + `)`
- valueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]`
- )
- var keyValidationRegExp = regexp.MustCompile(`^(` + keyFormat + `)$`)
- var valueValidationRegExp = regexp.MustCompile(`^(` + valueFormat + `)$`)
- type Tracestate struct {
- entries []Entry
- }
- type Entry struct {
-
-
-
- Key string
-
-
- Value string
- }
- func (ts *Tracestate) Entries() []Entry {
- if ts == nil {
- return nil
- }
- return ts.entries
- }
- func (ts *Tracestate) remove(key string) *Entry {
- for index, entry := range ts.entries {
- if entry.Key == key {
- ts.entries = append(ts.entries[:index], ts.entries[index+1:]...)
- return &entry
- }
- }
- return nil
- }
- func (ts *Tracestate) add(entries []Entry) error {
- for _, entry := range entries {
- ts.remove(entry.Key)
- }
- if len(ts.entries)+len(entries) > maxKeyValuePairs {
- return fmt.Errorf("adding %d key-value pairs to current %d pairs exceeds the limit of %d",
- len(entries), len(ts.entries), maxKeyValuePairs)
- }
- ts.entries = append(entries, ts.entries...)
- return nil
- }
- func isValid(entry Entry) bool {
- return keyValidationRegExp.MatchString(entry.Key) &&
- valueValidationRegExp.MatchString(entry.Value)
- }
- func containsDuplicateKey(entries ...Entry) (string, bool) {
- keyMap := make(map[string]int)
- for _, entry := range entries {
- if _, ok := keyMap[entry.Key]; ok {
- return entry.Key, true
- }
- keyMap[entry.Key] = 1
- }
- return "", false
- }
- func areEntriesValid(entries ...Entry) (*Entry, bool) {
- for _, entry := range entries {
- if !isValid(entry) {
- return &entry, false
- }
- }
- return nil, true
- }
- func New(parent *Tracestate, entries ...Entry) (*Tracestate, error) {
- if parent == nil && len(entries) == 0 {
- return nil, nil
- }
- if entry, ok := areEntriesValid(entries...); !ok {
- return nil, fmt.Errorf("key-value pair {%s, %s} is invalid", entry.Key, entry.Value)
- }
- if key, duplicate := containsDuplicateKey(entries...); duplicate {
- return nil, fmt.Errorf("contains duplicate keys (%s)", key)
- }
- tracestate := Tracestate{}
- if parent != nil && len(parent.entries) > 0 {
- tracestate.entries = append([]Entry{}, parent.entries...)
- }
- err := tracestate.add(entries)
- if err != nil {
- return nil, err
- }
- return &tracestate, nil
- }
|