Debian Codegraph @

pdata/internal/state.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal // import "go.opentelemetry.io/collector/pdata/internal"
5 import (
6 "sync/atomic"
7
8 "go.opentelemetry.io/collector/featuregate"
9 )
10
11 var _ = featuregate.GlobalRegistry().MustRegister(
12 "pdata.useCustomProtoEncoding",
13 featuregate.StageStable,
14 featuregate.WithRegisterDescription("When enabled, enable custom proto encoding. This is required step to enable featuregate pdata.useProtoPooling."),
15 featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector/issues/13631"),
16 featuregate.WithRegisterFromVersion("v0.133.0"),
17 featuregate.WithRegisterToVersion("v0.137.0"),
18 )
19
20 var UseProtoPooling = featuregate.GlobalRegistry().MustRegister(
21 "pdata.useProtoPooling",
22 featuregate.StageAlpha,
23 featuregate.WithRegisterDescription("When enabled, enable using local memory pools for underlying data that the pdata messages are pushed to."),
24 featuregate.WithRegisterReferenceURL("https://github.com/open-telemetry/opentelemetry-collector/issues/13631"),
25 featuregate.WithRegisterFromVersion("v0.133.0"),
26 )
27
28 // State defines an ownership state of pmetric.Metrics, plog.Logs or ptrace.Traces.
29 type State struct {
30 refs atomic.Int32
31 state uint32
32 }
33
34 const (
35 defaultState uint32 = 0
36 stateReadOnlyBit = uint32(1 << 0)
37 statePipelineOwnedBit = uint32(1 << 1)
38 )
39
40 func NewState() *State {
41 st := &State{
42 state: defaultState,
43 }
44 st.refs.Store(1)
45 return st
46 }
47
48 func (st *State) MarkReadOnly() {
49 st.state |= stateReadOnlyBit
50 }
51
52 func (st *State) IsReadOnly() bool {
53 return st.state&stateReadOnlyBit != 0
54 }
55
56 // AssertMutable panics if the state is not StateMutable.
57 func (st *State) AssertMutable() {
58 if st.state&stateReadOnlyBit != 0 {
59 panic("invalid access to shared data")
60 }
61 }
62
63 // MarkPipelineOwned marks the data as owned by the pipeline, returns true if the data were
64 // previously not owned by the pipeline, otherwise false.
65 func (st *State) MarkPipelineOwned() bool {
66 if st.state&statePipelineOwnedBit != 0 {
67 return false
68 }
69 st.state |= statePipelineOwnedBit
70 return true
71 }
72
73 // Ref add one to the count of active references.
74 func (st *State) Ref() {
75 st.refs.Add(1)
76 }
77
78 // Unref returns true if reference count got to 0 which means no more active references,
79 // otherwise it returns false.
80 func (st *State) Unref() bool {
81 refs := st.refs.Add(-1)
82 switch {
83 case refs > 0:
84 return false
85 case refs == 0:
86 return true
87 default:
88 panic("Cannot unref freed data")
89 }
90 }