summaryrefslogtreecommitdiff
path: root/vendor/go.opencensus.io/trace/tracestate/tracestate.go
blob: 2d6c713eb3a198ab97ba9cc6896941398bea686c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
// Copyright 2018, OpenCensus Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package tracestate implements support for the Tracestate header of the
// W3C TraceContext propagation format.
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 + `)$`)

// Tracestate represents tracing-system specific context in a list of key-value pairs. Tracestate allows different
// vendors propagate additional information and inter-operate with their legacy Id formats.
type Tracestate struct {
	entries []Entry
}

// Entry represents one key-value pair in a list of key-value pair of Tracestate.
type Entry struct {
	// Key is an opaque string up to 256 characters printable. It MUST begin with a lowercase letter,
	// and can only contain lowercase letters a-z, digits 0-9, underscores _, dashes -, asterisks *, and
	// forward slashes /.
	Key string

	// Value is an opaque string up to 256 characters printable ASCII RFC0020 characters (i.e., the
	// range 0x20 to 0x7E) except comma , and =.
	Value string
}

// Entries returns a slice of Entry.
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
}

// New creates a Tracestate object from a parent and/or entries (key-value pair).
// Entries from the parent are copied if present. The entries passed to this function
// are inserted in front of those copied from the parent. If an entry copied from the
// parent contains the same key as one of the entry in entries then the entry copied
// from the parent is removed. See add func.
//
// An error is returned with nil Tracestate if
//  1. one or more entry in entries is invalid.
//  2. two or more entries in the input entries have the same key.
//  3. the number of entries combined from the parent and the input entries exceeds maxKeyValuePairs.
//     (duplicate entry is counted only once).
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
}