Debian Codegraph @

internal/fanoutconsumer/traces.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package fanoutconsumer // import "go.opentelemetry.io/collector/internal/fanoutconsumer"
5
6 import (
7 "context"
8
9 "go.uber.org/multierr"
10
11 "go.opentelemetry.io/collector/consumer"
12 "go.opentelemetry.io/collector/pdata/ptrace"
13 )
14
15 // NewTraces wraps multiple trace consumers in a single one.
16 // It fans out the incoming data to all the consumers, and does smart routing:
17 // - Clones only to the consumer that needs to mutate the data.
18 // - If all consumers needs to mutate the data one will get the original mutable data.
19 func NewTraces(tcs []consumer.Traces) consumer.Traces {
20 // Don't wrap if there is only one non-mutating consumer.
21 if len(tcs) == 1 && !tcs[0].Capabilities().MutatesData {
22 return tcs[0]
23 }
24
25 tc := &tracesConsumer{}
26 for i := range tcs {
27 if tcs[i].Capabilities().MutatesData {
28 tc.mutable = append(tc.mutable, tcs[i])
29 } else {
30 tc.readonly = append(tc.readonly, tcs[i])
31 }
32 }
33 return tc
34 }
35
36 type tracesConsumer struct {
37 mutable []consumer.Traces
38 readonly []consumer.Traces
39 }
40
41 func (tsc *tracesConsumer) Capabilities() consumer.Capabilities {
42 // If all consumers are mutating, then the original data will be passed to one of them.
43 return consumer.Capabilities{MutatesData: len(tsc.mutable) > 0 && len(tsc.readonly) == 0}
44 }
45
46 // ConsumeTraces exports the ptrace.Traces to all consumers wrapped by the current one.
47 func (tsc *tracesConsumer) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {
48 var errs error
49
50 if len(tsc.mutable) > 0 {
51 // Clone the data before sending to all mutating consumers except the last one.
52 for i := 0; i < len(tsc.mutable)-1; i++ {
53 errs = multierr.Append(errs, tsc.mutable[i].ConsumeTraces(ctx, cloneTraces(td)))
54 }
55 // Send data as is to the last mutating consumer only if there are no other non-mutating consumers and the
56 // data is mutable. Never share the same data between a mutating and a non-mutating consumer since the
57 // non-mutating consumer may process data async and the mutating consumer may change the data before that.
58 lastConsumer := tsc.mutable[len(tsc.mutable)-1]
59 if len(tsc.readonly) == 0 && !td.IsReadOnly() {
60 errs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, td))
61 } else {
62 errs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, cloneTraces(td)))
63 }
64 }
65
66 // Mark the data as read-only if it will be sent to more than one read-only consumer.
67 if len(tsc.readonly) > 1 && !td.IsReadOnly() {
68 td.MarkReadOnly()
69 }
70 for _, tc := range tsc.readonly {
71 errs = multierr.Append(errs, tc.ConsumeTraces(ctx, td))
72 }
73
74 return errs
75 }
76
77 func cloneTraces(td ptrace.Traces) ptrace.Traces {
78 clonedTraces := ptrace.NewTraces()
79 td.CopyTo(clonedTraces)
80 return clonedTraces
81 }