Debian Codegraph @

CONTRIBUTING.md

raw
1 # Contributing to opentelemetry-go
2
3 The Go special interest group (SIG) meets regularly. See the
4 OpenTelemetry
5 [community](https://github.com/open-telemetry/community#golang-sdk)
6 repo for information on this and other language SIGs.
7
8 See the [public meeting
9 notes](https://docs.google.com/document/d/1E5e7Ld0NuU1iVvf-42tOBpu2VBBLYnh73GJuITGJTTU/edit)
10 for a summary description of past meetings. To request edit access,
11 join the meeting or get in touch on
12 [Slack](https://cloud-native.slack.com/archives/C01NPAXACKT).
13
14 ## Development
15
16 You can view and edit the source code by cloning this repository:
17
18 ```sh
19 git clone https://github.com/open-telemetry/opentelemetry-go.git
20 ```
21
22 Run `make test` to run the tests instead of `go test`.
23
24 There are some generated files checked into the repo. To make sure
25 that the generated files are up-to-date, run `make` (or `make
26 precommit` - the `precommit` target is the default).
27
28 The `precommit` target also fixes the formatting of the code and
29 checks the status of the go module files.
30
31 Additionally, there is a `codespell` target that checks for common
32 typos in the code. It is not run by default, but you can run it
33 manually with `make codespell`. It will set up a virtual environment
34 in `venv` and install `codespell` there.
35
36 If after running `make precommit` the output of `git status` contains
37 `nothing to commit, working tree clean` then it means that everything
38 is up-to-date and properly formatted.
39
40 ## Pull Requests
41
42 ### How to Send Pull Requests
43
44 Everyone is welcome to contribute code to `opentelemetry-go` via
45 GitHub pull requests (PRs).
46
47 To create a new PR, fork the project in GitHub and clone the upstream
48 repo:
49
50 ```sh
51 go get -d go.opentelemetry.io/otel
52 ```
53
54 (This may print some warning about "build constraints exclude all Go
55 files", just ignore it.)
56
57 This will put the project in `${GOPATH}/src/go.opentelemetry.io/otel`.
58 Alternatively, you can use `git` directly with:
59
60 ```sh
61 git clone https://github.com/open-telemetry/opentelemetry-go
62 ```
63
64 (Note that `git clone` is *not* using the `go.opentelemetry.io/otel` name -
65 that name is a kind of a redirector to GitHub that `go get` can
66 understand, but `git` does not.)
67
68 This will add the project as `opentelemetry-go` within the current directory.
69
70 Enter the newly created directory and add your fork as a new remote:
71
72 ```sh
73 git remote add <YOUR_FORK> [email protected]:<YOUR_GITHUB_USERNAME>/opentelemetry-go
74 ```
75
76 Check out a new branch, make modifications, run linters and tests, update
77 `CHANGELOG.md`, and push the branch to your fork:
78
79 ```sh
80 git checkout -b <YOUR_BRANCH_NAME>
81 # edit files
82 # update changelog
83 make precommit
84 git add -p
85 git commit
86 git push <YOUR_FORK> <YOUR_BRANCH_NAME>
87 ```
88
89 Open a pull request against the main `opentelemetry-go` repo. Be sure to add the pull
90 request ID to the entry you added to `CHANGELOG.md`.
91
92 Avoid rebasing and force-pushing to your branch to facilitate reviewing the pull request.
93 Rewriting Git history makes it difficult to keep track of iterations during code review.
94 All pull requests are squashed to a single commit upon merge to `main`.
95
96 ### How to Receive Comments
97
98 * If the PR is not ready for review, please put `[WIP]` in the title,
99 tag it as `work-in-progress`, or mark it as
100 [`draft`](https://github.blog/2019-02-14-introducing-draft-pull-requests/).
101 * Make sure CLA is signed and CI is clear.
102
103 ### How to Get PRs Merged
104
105 A PR is considered **ready to merge** when:
106
107 * It has received two qualified approvals[^1].
108
109 This is not enforced through automation, but needs to be validated by the
110 maintainer merging.
111 * At least one of the qualified approvals needs to be from an
112 [Approver]/[Maintainer] affiliated with a different company than the author
113 of the PR.
114 * PRs introducing changes that have already been discussed and consensus
115 reached only need one qualified approval. The discussion and resolution
116 needs to be linked to the PR.
117 * Trivial changes[^2] only need one qualified approval.
118
119 * All feedback has been addressed.
120 * All PR comments and suggestions are resolved.
121 * All GitHub Pull Request reviews with a status of "Request changes" have
122 been addressed. Another review by the objecting reviewer with a different
123 status can be submitted to clear the original review, or the review can be
124 dismissed by a [Maintainer] when the issues from the original review have
125 been addressed.
126 * Any comments or reviews that cannot be resolved between the PR author and
127 reviewers can be submitted to the community [Approver]s and [Maintainer]s
128 during the weekly SIG meeting. If consensus is reached among the
129 [Approver]s and [Maintainer]s during the SIG meeting the objections to the
130 PR may be dismissed or resolved or the PR closed by a [Maintainer].
131 * Any substantive changes to the PR require existing Approval reviews be
132 cleared unless the approver explicitly states that their approval persists
133 across changes. This includes changes resulting from other feedback.
134 [Approver]s and [Maintainer]s can help in clearing reviews and they should
135 be consulted if there are any questions.
136
137 * The PR branch is up to date with the base branch it is merging into.
138 * To ensure this does not block the PR, it should be configured to allow
139 maintainers to update it.
140
141 * It has been open for review for at least one working day. This gives people
142 reasonable time to review.
143 * Trivial changes[^2] do not have to wait for one day and may be merged with
144 a single [Maintainer]'s approval.
145
146 * All required GitHub workflows have succeeded.
147 * Urgent fix can take exception as long as it has been actively communicated
148 among [Maintainer]s.
149
150 Any [Maintainer] can merge the PR once the above criteria have been met.
151
152 [^1]: A qualified approval is a GitHub Pull Request review with "Approve"
153 status from an OpenTelemetry Go [Approver] or [Maintainer].
154 [^2]: Trivial changes include: typo corrections, cosmetic non-substantive
155 changes, documentation corrections or updates, dependency updates, etc.
156
157 ## Design Choices
158
159 As with other OpenTelemetry clients, opentelemetry-go follows the
160 [OpenTelemetry Specification](https://opentelemetry.io/docs/specs/otel).
161
162 It's especially valuable to read through the [library
163 guidelines](https://opentelemetry.io/docs/specs/otel/library-guidelines).
164
165 ### Focus on Capabilities, Not Structure Compliance
166
167 OpenTelemetry is an evolving specification, one where the desires and
168 use cases are clear, but the methods to satisfy those use cases are
169 not.
170
171 As such, Contributions should provide functionality and behavior that
172 conforms to the specification, but the interface and structure are
173 flexible.
174
175 It is preferable to have contributions follow the idioms of the
176 language rather than conform to specific API names or argument
177 patterns in the spec.
178
179 For a deeper discussion, see
180 [this](https://github.com/open-telemetry/opentelemetry-specification/issues/165).
181
182 ## Tests
183
184 Each functionality should be covered by tests.
185
186 Performance-critical functionality should also be covered by benchmarks.
187
188 - Pull requests adding a performance-critical functionality
189 should have `go test -bench` output in their description.
190 - Pull requests changing a performance-critical functionality
191 should have [`benchstat`](https://pkg.go.dev/golang.org/x/perf/cmd/benchstat)
192 output in their description.
193
194 ## Dependencies
195
196 This project uses [Go Modules] for dependency management. All modules will use
197 `go.mod` to explicitly list all direct and indirect dependencies, ensuring a
198 clear dependency graph. The `go.sum` file for each module will be committed to
199 the repository and used to verify the integrity of downloaded modules,
200 preventing malicious tampering.
201
202 This project uses automated dependency update tools (i.e. dependabot,
203 renovatebot) to manage updates to dependencies. This ensures that dependencies
204 are kept up-to-date with the latest security patches and features and are
205 reviewed before being merged. If you would like to propose a change to a
206 dependency it should be done through a pull request that updates the `go.mod`
207 file and includes a description of the change.
208
209 See the [versioning and compatibility](./VERSIONING.md) policy for more details
210 about dependency compatibility.
211
212 [Go Modules]: https://pkg.go.dev/cmd/go#hdr-Modules__module_versions__and_more
213
214 ### Environment Dependencies
215
216 This project does not partition dependencies based on the environment (i.e.
217 `development`, `staging`, `production`).
218
219 Only the dependencies explicitly included in the released modules have been
220 tested and verified to work with the released code. No other guarantee is made
221 about the compatibility of other dependencies.
222
223 ## Documentation
224
225 Each (non-internal, non-test) package must be documented using
226 [Go Doc Comments](https://go.dev/doc/comment),
227 preferably in a `doc.go` file.
228
229 Prefer using [Examples](https://pkg.go.dev/testing#hdr-Examples)
230 instead of putting code snippets in Go doc comments.
231 In some cases, you can even create [Testable Examples](https://go.dev/blog/examples).
232
233 You can install and run a "local Go Doc site" in the following way:
234
235 ```sh
236 go install golang.org/x/pkgsite/cmd/pkgsite@latest
237 pkgsite
238 ```
239
240 [`go.opentelemetry.io/otel/metric`](https://pkg.go.dev/go.opentelemetry.io/otel/metric)
241 is an example of a very well-documented package.
242
243 ### README files
244
245 Each (non-internal, non-test, non-documentation) package must contain a
246 `README.md` file containing at least a title, and a `pkg.go.dev` badge.
247
248 The README should not be a repetition of Go doc comments.
249
250 You can verify the presence of all README files with the `make verify-readmes`
251 command.
252
253 ## Style Guide
254
255 One of the primary goals of this project is that it is actually used by
256 developers. With this goal in mind the project strives to build
257 user-friendly and idiomatic Go code adhering to the Go community's best
258 practices.
259
260 For a non-comprehensive but foundational overview of these best practices
261 the [Effective Go](https://golang.org/doc/effective_go.html) documentation
262 is an excellent starting place.
263
264 We also recommend following the
265 [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments)
266 that collects common comments made during reviews of Go code.
267
268 As a convenience for developers building this project the `make precommit`
269 will format, lint, validate, and in some cases fix the changes you plan to
270 submit. This check will need to pass for your changes to be able to be
271 merged.
272
273 In addition to idiomatic Go, the project has adopted certain standards for
274 implementations of common patterns. These standards should be followed as a
275 default, and if they are not followed documentation needs to be included as
276 to the reasons why.
277
278 ### Configuration
279
280 When creating an instantiation function for a complex `type T struct`, it is
281 useful to allow variable number of options to be applied. However, the strong
282 type system of Go restricts the function design options. There are a few ways
283 to solve this problem, but we have landed on the following design.
284
285 #### `config`
286
287 Configuration should be held in a `struct` named `config`, or prefixed with
288 specific type name this Configuration applies to if there are multiple
289 `config` in the package. This type must contain configuration options.
290
291 ```go
292 // config contains configuration options for a thing.
293 type config struct {
294 // options ...
295 }
296 ```
297
298 In general the `config` type will not need to be used externally to the
299 package and should be unexported. If, however, it is expected that the user
300 will likely want to build custom options for the configuration, the `config`
301 should be exported. Please, include in the documentation for the `config`
302 how the user can extend the configuration.
303
304 It is important that internal `config` are not shared across package boundaries.
305 Meaning a `config` from one package should not be directly used by another. The
306 one exception is the API packages. The configs from the base API, eg.
307 `go.opentelemetry.io/otel/trace.TracerConfig` and
308 `go.opentelemetry.io/otel/metric.InstrumentConfig`, are intended to be consumed
309 by the SDK therefore it is expected that these are exported.
310
311 When a config is exported we want to maintain forward and backward
312 compatibility, to achieve this no fields should be exported but should
313 instead be accessed by methods.
314
315 Optionally, it is common to include a `newConfig` function (with the same
316 naming scheme). This function wraps any defaults setting and looping over
317 all options to create a configured `config`.
318
319 ```go
320 // newConfig returns an appropriately configured config.
321 func newConfig(options ...Option) config {
322 // Set default values for config.
323 config := config{/* […] */}
324 for _, option := range options {
325 config = option.apply(config)
326 }
327 // Perform any validation here.
328 return config
329 }
330 ```
331
332 If validation of the `config` options is also performed this can return an
333 error as well that is expected to be handled by the instantiation function
334 or propagated to the user.
335
336 Given the design goal of not having the user need to work with the `config`,
337 the `newConfig` function should also be unexported.
338
339 #### `Option`
340
341 To set the value of the options a `config` contains, a corresponding
342 `Option` interface type should be used.
343
344 ```go
345 type Option interface {
346 apply(config) config
347 }
348 ```
349
350 Having `apply` unexported makes sure that it will not be used externally.
351 Moreover, the interface becomes sealed so the user cannot easily implement
352 the interface on its own.
353
354 The `apply` method should return a modified version of the passed config.
355 This approach, instead of passing a pointer, is used to prevent the config from being allocated to the heap.
356
357 The name of the interface should be prefixed in the same way the
358 corresponding `config` is (if at all).
359
360 #### Options
361
362 All user configurable options for a `config` must have a related unexported
363 implementation of the `Option` interface and an exported configuration
364 function that wraps this implementation.
365
366 The wrapping function name should be prefixed with `With*` (or in the
367 special case of a boolean options `Without*`) and should have the following
368 function signature.
369
370 ```go
371 func With*(…) Option { … }
372 ```
373
374 ##### `bool` Options
375
376 ```go
377 type defaultFalseOption bool
378
379 func (o defaultFalseOption) apply(c config) config {
380 c.Bool = bool(o)
381 return c
382 }
383
384 // WithOption sets a T to have an option included.
385 func WithOption() Option {
386 return defaultFalseOption(true)
387 }
388 ```
389
390 ```go
391 type defaultTrueOption bool
392
393 func (o defaultTrueOption) apply(c config) config {
394 c.Bool = bool(o)
395 return c
396 }
397
398 // WithoutOption sets a T to have Bool option excluded.
399 func WithoutOption() Option {
400 return defaultTrueOption(false)
401 }
402 ```
403
404 ##### Declared Type Options
405
406 ```go
407 type myTypeOption struct {
408 MyType MyType
409 }
410
411 func (o myTypeOption) apply(c config) config {
412 c.MyType = o.MyType
413 return c
414 }
415
416 // WithMyType sets T to have include MyType.
417 func WithMyType(t MyType) Option {
418 return myTypeOption{t}
419 }
420 ```
421
422 ##### Functional Options
423
424 ```go
425 type optionFunc func(config) config
426
427 func (fn optionFunc) apply(c config) config {
428 return fn(c)
429 }
430
431 // WithMyType sets t as MyType.
432 func WithMyType(t MyType) Option {
433 return optionFunc(func(c config) config {
434 c.MyType = t
435 return c
436 })
437 }
438 ```
439
440 #### Instantiation
441
442 Using this configuration pattern to configure instantiation with a `NewT`
443 function.
444
445 ```go
446 func NewT(options ...Option) T {…}
447 ```
448
449 Any required parameters can be declared before the variadic `options`.
450
451 #### Dealing with Overlap
452
453 Sometimes there are multiple complex `struct` that share common
454 configuration and also have distinct configuration. To avoid repeated
455 portions of `config`s, a common `config` can be used with the union of
456 options being handled with the `Option` interface.
457
458 For example.
459
460 ```go
461 // config holds options for all animals.
462 type config struct {
463 Weight float64
464 Color string
465 MaxAltitude float64
466 }
467
468 // DogOption apply Dog specific options.
469 type DogOption interface {
470 applyDog(config) config
471 }
472
473 // BirdOption apply Bird specific options.
474 type BirdOption interface {
475 applyBird(config) config
476 }
477
478 // Option apply options for all animals.
479 type Option interface {
480 BirdOption
481 DogOption
482 }
483
484 type weightOption float64
485
486 func (o weightOption) applyDog(c config) config {
487 c.Weight = float64(o)
488 return c
489 }
490
491 func (o weightOption) applyBird(c config) config {
492 c.Weight = float64(o)
493 return c
494 }
495
496 func WithWeight(w float64) Option { return weightOption(w) }
497
498 type furColorOption string
499
500 func (o furColorOption) applyDog(c config) config {
501 c.Color = string(o)
502 return c
503 }
504
505 func WithFurColor(c string) DogOption { return furColorOption(c) }
506
507 type maxAltitudeOption float64
508
509 func (o maxAltitudeOption) applyBird(c config) config {
510 c.MaxAltitude = float64(o)
511 return c
512 }
513
514 func WithMaxAltitude(a float64) BirdOption { return maxAltitudeOption(a) }
515
516 func NewDog(name string, o ...DogOption) Dog {…}
517 func NewBird(name string, o ...BirdOption) Bird {…}
518 ```
519
520 ### Interfaces
521
522 To allow other developers to better comprehend the code, it is important
523 to ensure it is sufficiently documented. One simple measure that contributes
524 to this aim is self-documenting by naming method parameters. Therefore,
525 where appropriate, methods of every exported interface type should have
526 their parameters appropriately named.
527
528 #### Interface Stability
529
530 All exported stable interfaces that include the following warning in their
531 documentation are allowed to be extended with additional methods.
532
533 > Warning: methods may be added to this interface in minor releases.
534
535 These interfaces are defined by the OpenTelemetry specification and will be
536 updated as the specification evolves.
537
538 Otherwise, stable interfaces MUST NOT be modified.
539
540 #### How to Change Specification Interfaces
541
542 When an API change must be made, we will update the SDK with the new method one
543 release before the API change. This will allow the SDK one version before the
544 API change to work seamlessly with the new API.
545
546 If an incompatible version of the SDK is used with the new API the application
547 will fail to compile.
548
549 #### How Not to Change Specification Interfaces
550
551 We have explored using a v2 of the API to change interfaces and found that there
552 was no way to introduce a v2 and have it work seamlessly with the v1 of the API.
553 Problems happened with libraries that upgraded to v2 when an application did not,
554 and would not produce any telemetry.
555
556 More detail of the approaches considered and their limitations can be found in
557 the [Use a V2 API to evolve interfaces](https://github.com/open-telemetry/opentelemetry-go/issues/3920)
558 issue.
559
560 #### How to Change Other Interfaces
561
562 If new functionality is needed for an interface that cannot be changed it MUST
563 be added by including an additional interface. That added interface can be a
564 simple interface for the specific functionality that you want to add or it can
565 be a super-set of the original interface. For example, if you wanted to a
566 `Close` method to the `Exporter` interface:
567
568 ```go
569 type Exporter interface {
570 Export()
571 }
572 ```
573
574 A new interface, `Closer`, can be added:
575
576 ```go
577 type Closer interface {
578 Close()
579 }
580 ```
581
582 Code that is passed the `Exporter` interface can now check to see if the passed
583 value also satisfies the new interface. E.g.
584
585 ```go
586 func caller(e Exporter) {
587 /* ... */
588 if c, ok := e.(Closer); ok {
589 c.Close()
590 }
591 /* ... */
592 }
593 ```
594
595 Alternatively, a new type that is the super-set of an `Exporter` can be created.
596
597 ```go
598 type ClosingExporter struct {
599 Exporter
600 Close()
601 }
602 ```
603
604 This new type can be used similar to the simple interface above in that a
605 passed `Exporter` type can be asserted to satisfy the `ClosingExporter` type
606 and the `Close` method called.
607
608 This super-set approach can be useful if there is explicit behavior that needs
609 to be coupled with the original type and passed as a unified type to a new
610 function, but, because of this coupling, it also limits the applicability of
611 the added functionality. If there exist other interfaces where this
612 functionality should be added, each one will need their own super-set
613 interfaces and will duplicate the pattern. For this reason, the simple targeted
614 interface that defines the specific functionality should be preferred.
615
616 See also:
617 [Keeping Your Modules Compatible: Working with interfaces](https://go.dev/blog/module-compatibility#working-with-interfaces).
618
619 ### Testing
620
621 We allow using [`testify`](https://github.com/stretchr/testify) even though
622 it is seen as non-idiomatic according to
623 the [Go Test Comments](https://go.dev/wiki/TestComments#assert-libraries) page.
624
625 The tests should never leak goroutines.
626
627 Use the term `ConcurrentSafe` in the test name when it aims to verify the
628 absence of race conditions. The top-level tests with this term will be run
629 many times in the `test-concurrent-safe` CI job to increase the chance of
630 catching concurrency issues. This does not apply to subtests when this term
631 is not in their root name.
632
633 ### Internal packages
634
635 The use of internal packages should be scoped to a single module. A sub-module
636 should never import from a parent internal package. This creates a coupling
637 between the two modules where a user can upgrade the parent without the child,
638 and if the internal package API has changed, it will fail to upgrade[^3].
639
640 There are two known exceptions to this rule:
641
642 - `go.opentelemetry.io/otel/internal/global`
643 - This package manages global state for all of opentelemetry-go. It needs to
644 be a single package in order to ensure the uniqueness of the global state.
645 - `go.opentelemetry.io/otel/internal/baggage`
646 - This package provides values in a `context.Context` that need to be
647 recognized by `go.opentelemetry.io/otel/baggage` and
648 `go.opentelemetry.io/otel/bridge/opentracing` but remain private.
649
650 If you have duplicate code in multiple modules, make that code into a Go
651 template stored in `go.opentelemetry.io/otel/internal/shared` and use [gotmpl]
652 to render the templates in the desired locations. See [#4404] for an example of
653 this.
654
655 [^3]: https://github.com/open-telemetry/opentelemetry-go/issues/3548
656
657 ### Ignoring context cancellation
658
659 OpenTelemetry API implementations need to ignore the cancellation of the context that is
660 passed when recording a value (e.g. starting a span, recording a measurement, emitting a log).
661 Recording methods should not return an error describing the cancellation state of the context
662 when they complete, nor should they abort any work.
663
664 This rule may not apply if the OpenTelemetry specification defines a timeout mechanism for
665 the method. In that case the context cancellation can be used for the timeout with the
666 restriction that this behavior is documented for the method. Otherwise, timeouts
667 are expected to be handled by the user calling the API, not the implementation.
668
669 Stoppage of the telemetry pipeline is handled by calling the appropriate `Shutdown` method
670 of a provider. It is assumed the context passed from a user is not used for this purpose.
671
672 Outside of the direct recording of telemetry from the API (e.g. exporting telemetry,
673 force flushing telemetry, shutting down a signal provider) the context cancellation
674 should be honored. This means all work done on behalf of the user provided context
675 should be canceled.
676
677 ### Observability
678
679 OpenTelemetry Go SDK components should be instrumented to enable users observability for the health and performance of the telemetry pipeline itself.
680 This allows operators to understand how well their observability infrastructure is functioning and to identify potential issues before they impact their applications.
681
682 This section outlines the best practices for building instrumentation in OpenTelemetry Go SDK components.
683
684 #### Environment Variable Activation
685
686 Observability features are currently experimental.
687 They should be disabled by default and activated through the `OTEL_GO_X_OBSERVABILITY` environment variable.
688 This follows the established experimental feature pattern used throughout the SDK.
689
690 Components should check for this environment variable using a consistent pattern:
691
692 ```go
693 import "go.opentelemetry.io/otel/*/internal/x"
694
695 if x.Observability.Enabled() {
696 // Initialize observability metrics
697 }
698 ```
699
700 **References**:
701
702 - [stdouttrace exporter](./exporters/stdout/stdouttrace/internal/x/x.go)
703 - [sdk](./sdk/internal/x/x.go)
704
705 #### Encapsulation
706
707 Instrumentation should be encapsulated within a dedicated `struct` (e.g. `instrumentation`).
708 It should not be mixed into the instrumented component.
709
710 Prefer this:
711
712 ```go
713 type SDKComponent struct {
714 inst *instrumentation
715 }
716
717 type instrumentation struct {
718 inflight otelconv.SDKComponentInflight
719 exported otelconv.SDKComponentExported
720 }
721 ```
722
723 To this:
724
725 ```go
726 // ❌ Avoid this pattern.
727 type SDKComponent struct {
728 /* other SDKComponent fields... */
729
730 inflight otelconv.SDKComponentInflight
731 exported otelconv.SDKComponentExported
732 }
733 ```
734
735 The instrumentation code should not bloat the code being instrumented.
736 Likely, this means its own file, or its own package if it is complex or reused.
737
738 #### Initialization
739
740 Instrumentation setup should be explicit, side-effect free, and local to the relevant component.
741 Avoid relying on global or implicit [side effects][side-effect] for initialization.
742
743 Encapsulate setup in constructor functions, ensuring clear ownership and scope:
744
745 ```go
746 import (
747 "errors"
748
749 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
750 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
751 )
752
753 type SDKComponent struct {
754 inst *instrumentation
755 }
756
757 func NewSDKComponent(config Config) (*SDKComponent, error) {
758 inst, err := newInstrumentation()
759 if err != nil {
760 return nil, err
761 }
762 return &SDKComponent{inst: inst}, nil
763 }
764
765 type instrumentation struct {
766 inflight otelconv.SDKComponentInflight
767 exported otelconv.SDKComponentExported
768 }
769
770 func newInstrumentation() (*instrumentation, error) {
771 if !x.Observability.Enabled() {
772 return nil, nil
773 }
774
775 meter := otel.GetMeterProvider().Meter(
776 "<component-package-name>",
777 metric.WithInstrumentationVersion(sdk.Version()),
778 metric.WithSchemaURL(semconv.SchemaURL),
779 )
780
781 inst := &instrumentation{}
782
783 var err, e error
784 inst.inflight, e = otelconv.NewSDKComponentInflight(meter)
785 err = errors.Join(err, e)
786
787 inst.exported, e = otelconv.NewSDKComponentExported(meter)
788 err = errors.Join(err, e)
789
790 return inst, err
791 }
792 ```
793
794 ```go
795 // ❌ Avoid this pattern.
796 func (c *Component) initObservability() {
797 // Initialize observability metrics
798 if !x.Observability.Enabled() {
799 return
800 }
801
802 // Initialize observability metrics
803 c.inst = &instrumentation{/* ... */}
804 }
805 ```
806
807 [side-effect]: https://en.wikipedia.org/wiki/Side_effect_(computer_science)
808
809 #### Performance
810
811 When observability is disabled there should be little to no overhead.
812
813 ```go
814 func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
815 if e.inst != nil {
816 attrs := expensiveOperation()
817 e.inst.recordSpanInflight(ctx, int64(len(spans)), attrs...)
818 }
819 // Export spans...
820 }
821 ```
822
823 ```go
824 // ❌ Avoid this pattern.
825 func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
826 attrs := expensiveOperation()
827 e.inst.recordSpanInflight(ctx, int64(len(spans)), attrs...)
828 // Export spans...
829 }
830
831 func (i *instrumentation) recordSpanInflight(ctx context.Context, count int64, attrs ...attribute.KeyValue) {
832 if i == nil || i.inflight == nil {
833 return
834 }
835 i.inflight.Add(ctx, count, metric.WithAttributes(attrs...))
836 }
837 ```
838
839 When observability is enabled, the instrumentation code paths should be optimized to reduce allocation and computation overhead.
840
841 ##### Attribute and Option Allocation Management
842
843 Pool attribute slices and options with [`sync.Pool`] to minimize allocations in measurement calls with dynamic attributes.
844
845 ```go
846 var (
847 attrPool = sync.Pool{
848 New: func() any {
849 // Pre-allocate common capacity
850 knownCap := 8 // Adjust based on expected usage
851 s := make([]attribute.KeyValue, 0, knownCap)
852 // Return a pointer to avoid extra allocation on Put().
853 return &s
854 },
855 }
856
857 addOptPool = &sync.Pool{
858 New: func() any {
859 const n = 1 // WithAttributeSet
860 o := make([]metric.AddOption, 0, n)
861 // Return a pointer to avoid extra allocation on Put().
862 return &o
863 },
864 }
865 )
866
867 func (i *instrumentation) record(ctx context.Context, value int64, baseAttrs ...attribute.KeyValue) {
868 attrs := attrPool.Get().(*[]attribute.KeyValue)
869 defer func() {
870 *attrs = (*attrs)[:0] // Reset.
871 attrPool.Put(attrs)
872 }()
873
874 *attrs = append(*attrs, baseAttrs...)
875 // Add any dynamic attributes.
876 *attrs = append(*attrs, semconv.OTelComponentName("exporter-1"))
877
878 addOpt := addOptPool.Get().(*[]metric.AddOption)
879 defer func() {
880 *addOpt = (*addOpt)[:0]
881 addOptPool.Put(addOpt)
882 }()
883
884 set := attribute.NewSet(*attrs...)
885 *addOpt = append(*addOpt, metric.WithAttributeSet(set))
886
887 i.counter.Add(ctx, value, *addOpt...)
888 }
889 ```
890
891 Pools are most effective when there are many pooled objects of the same sufficiently large size, and the objects are repeatedly used.
892 This amortizes the cost of allocation and synchronization.
893 Ideally, the pools should be scoped to be used as widely as possible within the component to maximize this efficiency while still ensuring correctness.
894
895 [`sync.Pool`]: https://pkg.go.dev/sync#Pool
896
897 ##### Cache common attribute sets for repeated measurements
898
899 If a static set of attributes are used for measurements and they are known at compile time, pre-compute and cache these attributes.
900
901 ```go
902 type spanLiveSetKey struct {
903 sampled bool
904 }
905
906 var spanLiveSetCache = map[spanLiveSetKey]attribute.Set{
907 {true}: attribute.NewSet(
908 otelconv.SDKSpanLive{}.AttrSpanSamplingResult(
909 otelconv.SpanSamplingResultRecordAndSample,
910 ),
911 ),
912 {false}: attribute.NewSet(
913 otelconv.SDKSpanLive{}.AttrSpanSamplingResult(
914 otelconv.SpanSamplingResultRecordOnly,
915 ),
916 ),
917 }
918
919 func spanLiveSet(sampled bool) attribute.Set {
920 key := spanLiveSetKey{sampled: sampled}
921 return spanLiveSetCache[key]
922 }
923 ```
924
925 ##### Benchmarking
926
927 Always provide benchmarks when introducing or refactoring instrumentation.
928 Demonstrate the impact (allocs/op, B/op, ns/op) in enabled/disabled scenarios:
929
930 ```go
931 func BenchmarkExportSpans(b *testing.B) {
932 scenarios := []struct {
933 name string
934 obsEnabled bool
935 }{
936 {"ObsDisabled", false},
937 {"ObsEnabled", true},
938 }
939
940 for _, scenario := range scenarios {
941 b.Run(scenario.name, func(b *testing.B) {
942 b.Setenv(
943 "OTEL_GO_X_OBSERVABILITY",
944 strconv.FormatBool(scenario.obsEnabled),
945 )
946
947 exporter := NewExporter()
948 spans := generateTestSpans(100)
949
950 b.ResetTimer()
951 b.ReportAllocs()
952
953 for i := 0; i < b.N; i++ {
954 _ = exporter.ExportSpans(context.Background(), spans)
955 }
956 })
957 }
958 }
959 ```
960
961 #### Error Handling and Robustness
962
963 Errors should be reported back to the caller if possible, and partial failures should be handled as gracefully as possible.
964
965 ```go
966 func newInstrumentation() (*instrumentation, error) {
967 if !x.Observability.Enabled() {
968 return nil, nil
969 }
970
971 m := otel.GetMeterProvider().Meter(/* initialize meter */)
972 counter, err := otelconv.NewSDKComponentCounter(m)
973 // Use the partially initialized counter if available.
974 i := &instrumentation{counter: counter}
975 // Return any error to the caller.
976 return i, err
977 }
978 ```
979
980 ```go
981 // ❌ Avoid this pattern.
982 func newInstrumentation() *instrumentation {
983 if !x.Observability.Enabled() {
984 return nil, nil
985 }
986
987 m := otel.GetMeterProvider().Meter(/* initialize meter */)
988 counter, err := otelconv.NewSDKComponentCounter(m)
989 if err != nil {
990 // ❌ Do not dump the error to the OTel Handler. Return it to the
991 // caller.
992 otel.Handle(err)
993 // ❌ Do not return nil if we can still use the partially initialized
994 // counter.
995 return nil
996 }
997 return &instrumentation{counter: counter}
998 }
999 ```
1000
1001 If the instrumented component cannot report the error to the user, let it report the error to `otel.Handle`.
1002
1003 #### Context Propagation
1004
1005 Ensure observability measurements receive the correct context, especially for trace exemplars and distributed context:
1006
1007 ```go
1008 func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
1009 // Use the provided context for observability measurements
1010 e.inst.recordSpanExportStarted(ctx, len(spans))
1011
1012 err := e.doExport(ctx, spans)
1013
1014 if err != nil {
1015 e.inst.recordSpanExportFailed(ctx, len(spans), err)
1016 } else {
1017 e.inst.recordSpanExportSucceeded(ctx, len(spans))
1018 }
1019
1020 return err
1021 }
1022 ```
1023
1024 ```go
1025 // ❌ Avoid this pattern.
1026 func (e *Exporter) ExportSpans(ctx context.Context, spans []trace.ReadOnlySpan) error {
1027 // ❌ Do not break the context propagation.
1028 e.inst.recordSpanExportStarted(context.Background(), len(spans))
1029
1030 err := e.doExport(ctx, spans)
1031
1032 /* ... */
1033
1034 return err
1035 }
1036 ```
1037
1038 #### Semantic Conventions Compliance
1039
1040 All observability metrics should follow the [OpenTelemetry Semantic Conventions for SDK metrics](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/otel/sdk-metrics.md).
1041
1042 Use the metric semantic conventions convenience package [otelconv](./semconv/v1.40.0/otelconv/metric.go).
1043
1044 ##### Component Identification
1045
1046 Component names and types should follow [semantic convention](https://github.com/open-telemetry/semantic-conventions/blob/1cf2476ae5e518225a766990a28a6d5602bd5a30/docs/registry/attributes/otel.md#otel-component-attributes).
1047
1048 If a component is not a well-known type specified in the semantic conventions, use the package path scope type as a stable identifier.
1049
1050 ```go
1051 componentType := "go.opentelemetry.io/otel/sdk/trace.Span"
1052 ```
1053
1054 ```go
1055 // ❌ Do not do this.
1056 componentType := "trace-span"
1057 ```
1058
1059 The component name should be a stable unique identifier for the specific instance of the component.
1060
1061 Use a global counter to ensure uniqueness if necessary.
1062
1063 ```go
1064 // Unique 0-based ID counter for component instances.
1065 var componentIDCounter atomic.Int64
1066
1067 // nextID returns the next unique ID for a component.
1068 func nextID() int64 {
1069 return componentIDCounter.Add(1) - 1
1070 }
1071
1072 // componentName returns a unique name for the component instance.
1073 func componentName() attribute.KeyValue {
1074 id := nextID()
1075 name := fmt.Sprintf("%s/%d", componentType, id)
1076 return semconv.OTelComponentName(name)
1077 }
1078 ```
1079
1080 The component ID will need to be resettable for deterministic testing.
1081 If tests are in a different package than the component being tested (i.e. a `<component package>_test` package name), use a generated `counter` internal package to manage the counter.
1082 See [stdouttrace exporter example](./exporters/stdout/stdouttrace/internal/gen.go) for reference.
1083
1084 #### Testing
1085
1086 Use deterministic testing with isolated state:
1087
1088 ```go
1089 func TestObservability(t *testing.T) {
1090 // Restore state after test to ensure this does not affect other tests.
1091 prev := otel.GetMeterProvider()
1092 t.Cleanup(func() { otel.SetMeterProvider(prev) })
1093
1094 // Isolate the meter provider for deterministic testing
1095 reader := metric.NewManualReader()
1096 meterProvider := metric.NewMeterProvider(metric.WithReader(reader))
1097 otel.SetMeterProvider(meterProvider)
1098
1099 // Use t.Setenv to ensure environment variable is restored after test.
1100 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
1101
1102 // Reset component ID counter to ensure deterministic component names.
1103 componentIDCounter.Store(0)
1104
1105 /* ... test code ... */
1106 }
1107 ```
1108
1109 Test order should not affect results.
1110 Ensure that any global state (e.g. component ID counters) is reset between tests.
1111
1112 ## Approvers and Maintainers
1113
1114 ### Maintainers
1115
1116 - [Damien Mathieu](https://github.com/dmathieu), Elastic ([GPG](https://keys.openpgp.org/search?q=5A126B972A81A6CE443E5E1B408B8E44F0873832))
1117 - [David Ashpole](https://github.com/dashpole), Google ([GPG](https://keys.openpgp.org/search?q=C0D1BDDCAAEAE573673085F176327DA4D864DC70))
1118 - [Robert Pająk](https://github.com/pellared), Splunk ([GPG](https://keys.openpgp.org/search?q=CDAD3A60476A3DE599AA5092E5F7C35A4DBE90C2))
1119 - [Sam Xie](https://github.com/XSAM), Splunk ([GPG](https://keys.openpgp.org/search?q=AEA033782371ABB18EE39188B8044925D6FEEBEA))
1120 - [Tyler Yahn](https://github.com/MrAlias), Splunk ([GPG](https://keys.openpgp.org/search?q=0x46B0F3E1A8B1BA5A))
1121
1122 For more information about the maintainer role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#maintainer).
1123
1124 ### Approvers
1125
1126 - [Flc](https://github.com/flc1125), Independent
1127
1128 For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver).
1129
1130 ### Triagers
1131
1132 - [Alex Kats](https://github.com/akats7), Capital One
1133
1134 For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager).
1135
1136 ### Emeritus
1137
1138 - [Aaron Clawson](https://github.com/MadVikingGod)
1139 - [Anthony Mirabella](https://github.com/Aneurysm9)
1140 - [Cheng-Zhen Yang](https://github.com/scorpionknifes)
1141 - [Chester Cheung](https://github.com/hanyuancheung)
1142 - [Evan Torrie](https://github.com/evantorrie)
1143 - [Gustavo Silva Paiva](https://github.com/paivagustavo)
1144 - [Josh MacDonald](https://github.com/jmacd)
1145 - [Liz Fong-Jones](https://github.com/lizthegrey)
1146
1147 For more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager).
1148
1149 ### Become an Approver or a Maintainer
1150
1151 See the [community membership document in OpenTelemetry community
1152 repo](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md).
1153
1154 [Approver]: #approvers
1155 [Maintainer]: #maintainers
1156 [gotmpl]: https://pkg.go.dev/go.opentelemetry.io/build-tools/gotmpl
1157 [#4404]: https://github.com/open-telemetry/opentelemetry-go/pull/4404