-
Couldn't load subscription status.
- Fork 1.8k
Add xpdata.MapBuilder struct #13617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add xpdata.MapBuilder struct #13617
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
3f9b54a
First draft of xpdata.MapBuilder
jade-guiton-dd ed145aa
Remove all methods except UnsafeIntoMap, add release note and test
jade-guiton-dd 5407ac3
Add copyright header
jade-guiton-dd 02189bf
make goporto
jade-guiton-dd aaf42c3
lint
jade-guiton-dd b5a52e8
Remove mention of DistinctIntoMap in doc comment
jade-guiton-dd 3f02174
Merge branch 'main' into xpdata-mapbuilder
mx-psi 6df2fb6
Remove "mark as read-only" logic
jade-guiton-dd 95e5ed4
Merge branch 'main' into xpdata-mapbuilder
mx-psi 47a01f9
Merge branch 'main' into xpdata-mapbuilder
jade-guiton-dd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| # Use this changelog template to create an entry for release notes. | ||
|
|
||
| # One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' | ||
| change_type: 'enhancement' | ||
|
|
||
| # The name of the component, or a single word describing the area of concern, (e.g. otlpreceiver) | ||
| component: xpdata | ||
|
|
||
| # A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). | ||
| note: Add experimental MapBuilder struct to optimize pcommon.Map construction | ||
|
|
||
| # One or more tracking issues or pull requests related to the change | ||
| issues: [13617] | ||
|
|
||
| # (Optional) One or more lines of additional information to render under the primary note. | ||
| # These lines will be padded with 2 spaces and then inserted directly into the document. | ||
| # Use pipe (|) for multiline entries. | ||
| subtext: | ||
|
|
||
| # Optional: The change log or logs in which this entry should be included. | ||
| # e.g. '[user]' or '[user, api]' | ||
| # Include 'user' if the change is relevant to end users. | ||
| # Include 'api' if there is a change to a library API. | ||
| # Default: '[user]' | ||
| change_logs: [api] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| // Copyright The OpenTelemetry Authors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package xpdata // import "go.opentelemetry.io/collector/pdata/xpdata" | ||
|
|
||
| import ( | ||
| "go.opentelemetry.io/collector/pdata/internal" | ||
| otlpcommon "go.opentelemetry.io/collector/pdata/internal/data/protogen/common/v1" | ||
| "go.opentelemetry.io/collector/pdata/pcommon" | ||
| ) | ||
|
|
||
| // MapBuilder is an experimental struct which can be used to create a pcommon.Map more efficiently | ||
| // than by repeated use of the Put family of methods, which check for duplicate keys on every call | ||
| // (a linear time operation). | ||
| // A zero-initialized MapBuilder is ready for use. | ||
| type MapBuilder struct { | ||
| state internal.State | ||
| pairs []otlpcommon.KeyValue | ||
| } | ||
|
|
||
| // EnsureCapacity increases the capacity of this MapBuilder instance, if necessary, | ||
| // to ensure that it can hold at least the number of elements specified by the capacity argument. | ||
| func (mb *MapBuilder) EnsureCapacity(capacity int) { | ||
| mb.state.AssertMutable() | ||
| oldValues := mb.pairs | ||
| if capacity <= cap(oldValues) { | ||
| return | ||
| } | ||
| mb.pairs = make([]otlpcommon.KeyValue, len(oldValues), capacity) | ||
| copy(mb.pairs, oldValues) | ||
| } | ||
|
|
||
| func (mb *MapBuilder) getValue(i int) pcommon.Value { | ||
| return pcommon.Value(internal.NewValue(&mb.pairs[i].Value, &mb.state)) | ||
| } | ||
|
|
||
| // AppendEmpty appends a key/value pair to the MapBuilder and return the inserted value. | ||
| // This method does not check for duplicate keys and has an amortized constant time complexity. | ||
| func (mb *MapBuilder) AppendEmpty(k string) pcommon.Value { | ||
| mb.state.AssertMutable() | ||
| mb.pairs = append(mb.pairs, otlpcommon.KeyValue{Key: k}) | ||
| return mb.getValue(len(mb.pairs) - 1) | ||
| } | ||
|
|
||
| // UnsafeIntoMap transfers the contents of a MapBuilder into a Map, without checking for duplicate keys. | ||
| // If the MapBuilder contains duplicate keys, the behavior of the resulting Map is unspecified; | ||
| // consider using DistinctIntoMap if you are unsure or performance is not a concern. | ||
| // This operation has constant time complexity and makes no allocations. | ||
| // After this operation, the MapBuilder becomes read-only. | ||
| func (mb *MapBuilder) UnsafeIntoMap(m pcommon.Map) { | ||
| mb.state.AssertMutable() | ||
| internal.GetMapState(internal.Map(m)).AssertMutable() | ||
| mb.state = internal.StateReadOnly // to avoid modifying a Map later marked as ReadOnly through builder Values | ||
| *internal.GetOrigMap(internal.Map(m)) = mb.pairs | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // Copyright The OpenTelemetry Authors | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
|
|
||
| package xpdata_test | ||
|
|
||
| import ( | ||
| "testing" | ||
|
|
||
| "github.com/stretchr/testify/assert" | ||
|
|
||
| "go.opentelemetry.io/collector/pdata/pcommon" | ||
| "go.opentelemetry.io/collector/pdata/xpdata" | ||
| ) | ||
|
|
||
| func TestMapBuilder(t *testing.T) { | ||
| var mb xpdata.MapBuilder | ||
| mb.EnsureCapacity(3) | ||
| mb.AppendEmpty("key1").SetStr("val") | ||
| mb.AppendEmpty("key2").SetInt(42) | ||
|
|
||
| m := pcommon.NewMap() | ||
| mb.UnsafeIntoMap(m) | ||
|
|
||
| assert.Equal(t, 2, m.Len()) | ||
| val, ok := m.Get("key1") | ||
| assert.True(t, ok && val.Type() == pcommon.ValueTypeStr && val.Str() == "val") | ||
| val, ok = m.Get("key2") | ||
| assert.True(t, ok && val.Type() == pcommon.ValueTypeInt && val.Int() == 42) | ||
|
|
||
| assert.Panics(t, func() { | ||
| mb.AppendEmpty("key3") // mb should now be read-only | ||
| }) | ||
| assert.NotPanics(t, func() { | ||
| m.PutEmpty("key3") // m should still be mutable | ||
| }) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What is the purpose of this map if it is ReadOnly?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alternative is to "move" the values into the returned Map, so then the builder becomes empty and the Map will be mutable.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
Values returned byAppendEmptyuse thestateof theMapBuilder. But theMapwe return has its ownstate, which may later be changed toReadOnly. So to avoid indirectly modifying aReadOnlyMapthrough aValuereturned by theMapBuilder, we mark theMapBuilderitself asReadOnlyonce we're done with it. But we don't modify the state of theMap, it stays mutable through this function.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
After thinking about it some more, I'm pretty sure that even with these precautions it's still possible to bypass read-only protections.
"Exploit" details
ptrace.Traces.MarkReadOnly()or equivalents for other signalsBut I noticed that the
Map.MoveTomethod doesn't handle that edge case either: even if the targetMapis later marked as read-only, you can still modify its entries usingValues previously obtained from the sourceMap.So I won't bother trying to bullet-proof it and just do what you suggested, ie.
UnsafeIntoMapwill make the builder empty, but it won't turn it ReadOnly.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is consider UB (and may crash) to modify references after data are passed to the next component because we don't have any mutexes, etc. So I think you are worried about something that is prohibited.